dsh-ppt 0.13.0 → 0.14.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/lib/client.js CHANGED
@@ -1,10 +1,10 @@
1
- // Browser source, distributed directly. tsc deliberately does not rewrite this file.
2
- window.__ModuleLoader__.load({ id: 'dsh-ppt', factory: require => {
1
+ // Browser source, distributed directly. tsc deliberately does not rewrite this file.
2
+ window.__ModuleLoader__.load({ id: 'dsh-ppt', factory: require => {
3
3
  const React = require('react');
4
4
  var __FR_KEY = "dsh-first-run:dsh-ppt:v1";
5
5
  var __FR_TITLE = "演示文稿 · 首次使用(4 步)";
6
- var __FR_TITLE_EN = "Presentations · First steps";
7
- var __FR_STEPS_EN = [{title:"Choose a theme",body:"Choose from swiss, velvet, data, soft and bold before building your presentation."},{title:"Provide actual material",body:"Give the assistant your points, data and tables. It produces an editable PPTX and an HTML presentation.",tryIt:"Turn this quarterly update into eight slides using the data theme."},{title:"Review in the browser",body:"Step through the HTML preview, then edit text, images and speaker notes in this panel."},{title:"Check the final slides",body:"Review the final PPTX in PowerPoint or WPS, or use the optional renderer to check fonts and layout before delivery."}];
6
+ var __FR_TITLE_EN = "Presentations · First steps";
7
+ var __FR_STEPS_EN = [{title:"Choose a theme",body:"Choose from swiss, velvet, data, soft and bold before building your presentation."},{title:"Provide actual material",body:"Give the assistant your points, data and tables. It produces an editable PPTX and an HTML presentation.",tryIt:"Turn this quarterly update into eight slides using the data theme."},{title:"Review in the browser",body:"Step through the HTML preview, then edit text, images and speaker notes in this panel."},{title:"Check the final slides",body:"Review the final PPTX in PowerPoint or WPS, or use the optional renderer to check fonts and layout before delivery."}];
8
8
  var __FR_STEPS = [{"title":"先选主题","body":"内置 5 套主题(swiss / velvet / data / soft / bold),先定风格再生成内容。"},{"title":"给内容,不给空话","body":"把要点、数据、表格直接给助手,它会排成幻灯片并同时产出 PPTX 与网页版。","tryIt":"把这份季度总结做成 8 页汇报,用 data 主题"},{"title":"先在浏览器里过一遍","body":"网页版可直接翻页预览,确认排版没问题再导出。"},{"title":"导出后看图核对","body":"渲染成图检查一遍再交付,避免字体缺失或溢出。"}];
9
9
 
10
10
  // ---- first-run guide (shared snippet; keep in sync across plugins) ----
@@ -37,48 +37,48 @@ function __frEnsureCss() {
37
37
  }
38
38
  function __frRead() { try { return localStorage.getItem(__FR_KEY) === 'done'; } catch (e) { return false; } }
39
39
  function __frWrite() { try { localStorage.setItem(__FR_KEY, 'done'); } catch (e) {} }
40
- function __FirstRunCard(props) {
41
- useLanguage(props?.locale || localeService);
42
- var english = languageOf(props?.locale || localeService) === 'en';
43
- var steps = english ? __FR_STEPS_EN : __FR_STEPS;
44
- var text = (zh, en) => english ? en : zh;
40
+ function __FirstRunCard(props) {
41
+ useLanguage(props?.locale || localeService);
42
+ var english = languageOf(props?.locale || localeService) === 'en';
43
+ var steps = english ? __FR_STEPS_EN : __FR_STEPS;
44
+ var text = (zh, en) => english ? en : zh;
45
45
  var doneState = React.useState(__frRead);
46
46
  var done = doneState[0], setDone = doneState[1];
47
47
  var idxState = React.useState(0);
48
48
  var index = idxState[0], setIndex = idxState[1];
49
49
  React.useEffect(function () { __frEnsureCss(); }, []);
50
50
  if (done) return null;
51
- var step = steps[index];
52
- var last = index >= steps.length - 1;
51
+ var step = steps[index];
52
+ var last = index >= steps.length - 1;
53
53
  var close = function () { __frWrite(); setDone(true); };
54
54
  var kids = [
55
55
  React.createElement('div', { className: 'fr-head', key: 'h' },
56
56
  React.createElement('span', { className: 'fr-dot' }),
57
- React.createElement('span', { className: 'fr-title' }, english ? __FR_TITLE_EN : __FR_TITLE),
58
- React.createElement('span', { className: 'fr-count' }, (index + 1) + ' / ' + steps.length)),
57
+ React.createElement('span', { className: 'fr-title' }, english ? __FR_TITLE_EN : __FR_TITLE),
58
+ React.createElement('span', { className: 'fr-count' }, (index + 1) + ' / ' + steps.length)),
59
59
  React.createElement('div', { className: 'fr-step', key: 't' }, step.title),
60
60
  React.createElement('div', { className: 'fr-body', key: 'b' }, step.body),
61
61
  ];
62
62
  if (step.tryIt) kids.push(React.createElement('div', { className: 'fr-try', key: 'y' },
63
- React.createElement('span', null, text('可以直接说', 'Try saying')),
64
- React.createElement('code', null, text('「', '“') + step.tryIt + text('」', '”'))));
65
- var buttons = [React.createElement('div', { className: 'fr-progress', key: 'p' }, steps.map(function (_, i) {
63
+ React.createElement('span', null, text('可以直接说', 'Try saying')),
64
+ React.createElement('code', null, text('「', '“') + step.tryIt + text('」', '”'))));
65
+ var buttons = [React.createElement('div', { className: 'fr-progress', key: 'p' }, steps.map(function (_, i) {
66
66
  return React.createElement('span', { key: i, className: 'fr-seg' + (i <= index ? ' on' : '') });
67
67
  }))];
68
- buttons.push(React.createElement('button', { className: 'fr-btn ghost', type: 'button', onClick: close, key: 's' }, text('跳过', 'Skip')));
69
- if (index > 0) buttons.push(React.createElement('button', { className: 'fr-btn', type: 'button', key: 'prev', onClick: function () { setIndex(index - 1); } }, text('上一步', 'Back')));
70
- buttons.push(React.createElement('button', { className: 'fr-btn primary', type: 'button', key: 'next', onClick: function () { if (last) close(); else setIndex(index + 1); } }, last ? text('开始使用', 'Start') : text('下一步', 'Next')));
68
+ buttons.push(React.createElement('button', { className: 'fr-btn ghost', type: 'button', onClick: close, key: 's' }, text('跳过', 'Skip')));
69
+ if (index > 0) buttons.push(React.createElement('button', { className: 'fr-btn', type: 'button', key: 'prev', onClick: function () { setIndex(index - 1); } }, text('上一步', 'Back')));
70
+ buttons.push(React.createElement('button', { className: 'fr-btn primary', type: 'button', key: 'next', onClick: function () { if (last) close(); else setIndex(index + 1); } }, last ? text('开始使用', 'Start') : text('下一步', 'Next')));
71
71
  kids.push(React.createElement('div', { className: 'fr-bar', key: 'bar' }, buttons));
72
72
  return React.createElement('div', { className: 'fr-card' }, kids);
73
73
  }
74
74
  function __withFirstRun(Component) {
75
75
  return function FirstRunWrapped(props) {
76
- return React.createElement(React.Fragment, null, React.createElement(__FirstRunCard, props), React.createElement(Component, props));
76
+ return React.createElement(React.Fragment, null, React.createElement(__FirstRunCard, props), React.createElement(Component, props));
77
77
  };
78
78
  }
79
79
  // ---- end first-run guide ----
80
-
81
- const { useState, useEffect, useRef, useMemo } = React;
80
+
81
+ const { useState, useEffect, useRef, useMemo } = React;
82
82
  const h = React.createElement;
83
83
 
84
84
  // Interface language follows DSH; user content and stored records keep their original text.
@@ -102,21 +102,21 @@ const EN = Object.freeze({
102
102
  "内容没有变化。": "No changes to save.",
103
103
  "已保存,HTML、PPTX 和工程文件已同步更新。": "Saved. HTML, PPTX and project files were updated together.",
104
104
  "页面顺序已更新,可撤销。": "Slides reordered. You can undo this change.",
105
- "复制本页": "Duplicate slide",
106
- "删除本页": "Delete slide",
107
- "页面已复制,图片、图表和备注一并保留,可撤销。": "Slide duplicated with its images, charts and notes. You can undo this change.",
108
- "页面已删除,可撤销。": "Slide deleted. You can undo this change.",
105
+ "复制本页": "Duplicate slide",
106
+ "删除本页": "Delete slide",
107
+ "页面已复制,图片、图表和备注一并保留,可撤销。": "Slide duplicated with its images, charts and notes. You can undo this change.",
108
+ "页面已删除,可撤销。": "Slide deleted. You can undo this change.",
109
109
  "已撤销上次修改。": "Last change undone.",
110
110
  "当前 PPTX 已生成逐页图片,请查看画面。": "Slide images were rendered from the current PPTX. Review each slide.",
111
111
  "正在渲染最终 PPTX,较大文件可能需要几分钟…": "Rendering the final PPTX. Large files may take a few minutes…",
112
112
  "已请求下载,请查看浏览器的下载列表。": "Download requested. Check your browser’s downloads.",
113
- "请选择 5 MiB 以内的 PNG 或 JPEG 图片。": "Choose a PNG or JPEG image up to 5 MiB.",
113
+ "请选择 5 MiB 以内的 PNG 或 JPEG 图片。": "Choose a PNG or JPEG image up to 5 MiB.",
114
114
  "无法读取图片,请重试。": "Could not read the image. Try again.",
115
- "正在读取图片,切换页面会取消本次读取。": "Reading the image. Switching slides cancels this upload.",
116
- "图片已载入,保存后生效。": "Image loaded. Save this slide to apply it.",
117
- "下载讲稿 Markdown": "Download speaker notes",
118
- "另存副本": "Save a copy",
119
- "副本已保存,原文件保留。副本从工程生成,不包含 Office 手工修改。": "Copy saved. Original files are preserved. The copy is rebuilt from the project and does not include external Office edits.",
115
+ "正在读取图片,切换页面会取消本次读取。": "Reading the image. Switching slides cancels this upload.",
116
+ "图片已载入,保存后生效。": "Image loaded. Save this slide to apply it.",
117
+ "下载讲稿 Markdown": "Download speaker notes",
118
+ "另存副本": "Save a copy",
119
+ "副本已保存,原文件保留。副本从工程生成,不包含 Office 手工修改。": "Copy saved. Original files are preserved. The copy is rebuilt from the project and does not include external Office edits.",
120
120
  "演示文稿编辑": "Presentation editor",
121
121
  "修改本插件生成的成品,保存时同步更新 HTML、可编辑 PPTX 和工程文件。": "Edit presentations generated by this plugin. Saving updates the HTML, editable PPTX and project file together.",
122
122
  "载入最新版本,保留我的输入": "Load latest and keep my input",
@@ -191,306 +191,500 @@ function useLanguage(locale) {
191
191
  const [, rerender] = useState(0);
192
192
  useEffect(() => { const update = () => rerender(n => n + 1); update(); return locale?.subscribe?.(update); }, [locale]);
193
193
  }
194
-
195
- const ROUTE = 'api/dsh-ppt/workbench';
196
- const fields = [['title', '标题'], ['subtitle', '副标题'], ['kicker', '眉题'], ['text', '正文'], ['bullets', '要点(每行一条)'], ['notes', '演讲备注']];
197
- const css = `
198
- .pptw {color:var(--fg,#27354b);font:14px/1.6 system-ui,sans-serif;min-width:0;max-width:1140px;margin:0 auto;padding:8px}
199
- .pptw *{box-sizing:border-box}.pptw h2{font-size:22px;margin:0}.pptw h3{font-size:16px;margin:12px 0 6px}
200
- .pptw .muted{color:var(--fg-muted,#66768a);font-size:13px}.pptw .tools{display:flex;gap:8px;flex-wrap:wrap;margin:12px 0;align-items:center}
201
- .pptw button{font:inherit;border:1px solid var(--border,#ccd8e5);border-radius:9px;background:var(--bg-surface,#fff);color:inherit;padding:7px 12px;cursor:pointer;text-align:left;white-space:normal}
202
- .pptw button.primary{background:#245ee9;border-color:#245ee9;color:#fff}.pptw button:disabled{opacity:.45;cursor:default}
203
- .pptw input:not([type=file]),.pptw textarea,.pptw select{font:inherit;color:inherit;width:100%;background:var(--bg,#fff);border:1px solid var(--border,#c9d5e4);border-radius:8px;padding:8px 10px}
204
- .pptw textarea{resize:vertical}.pptw label{display:block;margin:8px 0 3px}.pptw .layout{display:grid;grid-template-columns:minmax(130px,190px) minmax(0,1fr);gap:14px}
205
- .pptw .pages{display:flex;flex-direction:column;gap:5px;max-height:480px;overflow:auto}.pptw .pages button[aria-current=true]{background:#245ee9;color:#fff}
206
- .pptw .preview{border:1px solid var(--border,#ced8e6);border-radius:12px;overflow:hidden;background:#f0f4fa;aspect-ratio:16/9;position:relative}
207
- .pptw iframe{position:absolute;inset:0;width:100%;height:100%;border:0}.pptw .render-page{width:100%;display:block}
208
- .pptw .notice{border-radius:9px;padding:10px 12px;margin:10px 0;background:#edf4ff;color:#17408e;overflow-wrap:anywhere}.pptw .error{background:#fff1ef;color:#922d20}
209
- .pptw .card{border:1px solid var(--border,#d5dfeb);border-radius:12px;padding:12px;margin:10px 0;background:var(--bg-surface,#fff)}
210
- .pptw .project-list{display:flex;flex-direction:column;gap:8px}.pptw .project-list button{display:block;width:100%}
211
- .pptw .file{font-size:12px;overflow-wrap:anywhere}.pptw .image-preview{width:100%;max-height:160px;object-fit:contain;background:#edf2f8;border-radius:8px}
212
- .pptw :focus-visible{outline:3px solid #78a8ff;outline-offset:2px}.pptw .dirty{color:#986114;font-size:13px}
213
- .pptw .badge-dirty{color:#986114;font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;background:rgba(245,158,11,.14);border:1px solid rgba(245,158,11,.35);margin-left:4px}
214
- .pptw .notice button{margin-left:8px;padding:2px 9px;border-radius:6px;border:1px solid currentColor;background:transparent;color:inherit;font-size:12px;cursor:pointer}
215
- [role=dialog]:has(.pptw){width:min(1200px,calc(100vw - 48px))!important;max-width:1200px!important}
216
- @media(max-width:700px){.pptw .layout{grid-template-columns:1fr}.pptw .pages{max-height:180px}.pptw .preview{min-height:190px}.pptw{padding:3px}
217
- [role=dialog]:has(.pptw){width:100%!important;max-width:100%!important;flex-direction:column!important}
218
- [role=dialog]:has(.pptw)>nav+div{min-width:0;width:100%}
219
- [role=dialog]:has(.pptw)>nav+div>div:has(.pptw){padding:12px!important;min-width:0}
220
- [role=dialog]:has(.pptw) nav{width:100%!important;flex-basis:auto!important;border-right:0;max-height:170px;overflow:auto}
221
- [role=dialog]:has(.pptw) nav>div:has(>button){display:flex;flex-direction:row!important;flex-wrap:wrap;flex-shrink:0;gap:4px}
222
- }`;
223
-
224
- async function action(body, signal) {
225
- const response = await fetch(new URL(ROUTE, document.baseURI), { method: 'POST', credentials: 'same-origin', signal,
226
- headers: { 'content-type': 'application/json', 'x-dsh-ppt-action': '1' }, body: JSON.stringify(body) });
227
- let value;
228
- try { value = await response.json(); } catch { throw new Error(t("无法读取服务响应,请检查插件是否加载")) }
229
- if (!response.ok || value.ok === false) { const localized = languageOf() === 'en' ? value.messageEn || englishError(value.message, response.status) : value.message; const hint = languageOf() === 'en' ? value.installationHintEn : value.installationHint; const error = new Error((localized || t("操作未完成")) + (hint ? '\n' + hint : '')); error.status = response.status; throw error; }
230
- return value;
231
- }
232
- function draftFor(slide) {
233
- return { title: slide.title || '', subtitle: slide.subtitle || '', kicker: slide.kicker || '', text: slide.text || '',
234
- bullets: (slide.bullets || []).join('\n'), notes: slide.notes || '' };
235
- }
236
- function editorHtml(html, nonce) {
237
- 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)};
238
- function tell(field){parent.postMessage({type:'dsh-ppt-select',nonce:nonce,field:field},'*')}
239
- document.addEventListener('keydown',function(e){
240
- var mod=e.ctrlKey||e.metaKey;
241
- if(mod&&(e.key==='s'||e.key==='S')){e.preventDefault();e.stopImmediatePropagation();parent.postMessage({type:'dsh-ppt-shortcut',nonce:nonce,key:'save'},'*');return}
242
- if(e.key==='Escape'){e.preventDefault();e.stopImmediatePropagation();parent.postMessage({type:'dsh-ppt-shortcut',nonce:nonce,key:'escape'},'*');return}
243
- if(e.altKey&&(e.key==='ArrowLeft'||e.key==='ArrowRight')){e.preventDefault();e.stopImmediatePropagation();parent.postMessage({type:'dsh-ppt-shortcut',nonce:nonce,key:e.key==='ArrowLeft'?'prev':'next'},'*');return}
244
- e.stopImmediatePropagation();if(e.key!=='Tab')e.preventDefault()
245
- },true);
246
- document.addEventListener('touchstart',function(e){e.stopImmediatePropagation()},true);
247
- document.addEventListener('touchend',function(e){e.stopImmediatePropagation()},true);
248
- document.addEventListener('wheel',function(e){e.stopImmediatePropagation()},{capture:true,passive:true});
249
- document.addEventListener('click',function(e){const n=e.target.closest('h1,h2,.subtitle,.kicker,.statement-title,.quote-text,.quote-attr,li');if(!n)return;
250
- e.preventDefault();e.stopImmediatePropagation();let field=n.matches('li')?'bullets':n.matches('.subtitle,.quote-attr')?'subtitle':n.matches('.kicker')?'kicker':'title';tell(field)},true);
251
- 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)});
252
- })();<\/script>`;
253
- 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'">`;
254
- // Presenter code contains a quoted </body>; only append at the document end.
255
- return html.replace(/<head>/i, '<head>' + policy).replace(/<\/body>(\s*<\/html>\s*)$/i, bridge + '</body>$1');
256
- }
257
- function createImageLoader() {
258
- let current = null;
259
- function cancel() {
260
- const reader = current; current = null;
261
- if (reader?.readyState === 1) reader.abort();
262
- }
263
- return {
264
- cancel,
265
- get pending() { return current !== null; },
266
- read(file, success, failure) {
267
- cancel(); const reader = new FileReader(); current = reader;
268
- const settle = callback => { if (current !== reader) return; current = null; callback(); };
269
- reader.onload = () => settle(() => success(String(reader.result)));
270
- reader.onerror = () => settle(failure);
271
- reader.onabort = () => { if (current === reader) current = null; };
272
- try { reader.readAsDataURL(file); } catch { settle(failure); }
273
- },
274
- };
275
- }
276
- function Workbench({ locale } = {}) {
194
+
195
+ const ROUTE = 'api/dsh-ppt/workbench';
196
+ const fields = [['title', '标题'], ['subtitle', '副标题'], ['kicker', '眉题'], ['text', '正文'], ['bullets', '要点(每行一条)'], ['notes', '演讲备注']];
197
+ const css = `
198
+ .pptw {--fg:var(--dsw-alias-label-primary,#27354b);--fg-muted:var(--dsw-alias-label-tertiary,#66768a);--bg:var(--dsw-alias-bg-layer-1,#fff);--bg-surface:var(--dsw-alias-bg-layer-2,#fff);--border:var(--dsw-alias-border-l3,#ccd8e5);color:var(--fg);font:14px/1.6 system-ui,sans-serif;min-width:0;max-width:1140px;margin:0 auto;padding:8px}
199
+ .pptw *{box-sizing:border-box}.pptw h2{font-size:22px;margin:0}.pptw h3{font-size:16px;margin:12px 0 6px}
200
+ .pptw .muted{color:var(--fg-muted,#66768a);font-size:13px}.pptw .tools{display:flex;gap:8px;flex-wrap:wrap;margin:12px 0;align-items:center}
201
+ .pptw button{font:inherit;border:1px solid var(--border,#ccd8e5);border-radius:9px;background:var(--bg-surface,#fff);color:inherit;padding:7px 12px;cursor:pointer;text-align:left;white-space:normal}
202
+ .pptw button.primary{background:#245ee9;border-color:#245ee9;color:#fff}.pptw button:disabled{opacity:.45;cursor:default}
203
+ .pptw input:not([type=file]),.pptw textarea,.pptw select{font:inherit;color:inherit;width:100%;background:var(--bg,#fff);border:1px solid var(--border,#c9d5e4);border-radius:8px;padding:8px 10px}
204
+ .pptw textarea{resize:vertical}.pptw label{display:block;margin:8px 0 3px}.pptw .layout{display:grid;grid-template-columns:minmax(130px,190px) minmax(0,1fr);gap:14px}
205
+ .pptw .pages{display:flex;flex-direction:column;gap:5px;max-height:480px;overflow:auto}.pptw .pages button[aria-current=true]{background:#245ee9;color:#fff}
206
+ .pptw .preview{border:1px solid var(--border,#ced8e6);border-radius:12px;overflow:hidden;background:#f0f4fa;aspect-ratio:16/9;position:relative}
207
+ .pptw iframe{position:absolute;inset:0;width:100%;height:100%;border:0}.pptw .render-page{width:100%;display:block}
208
+ .pptw .notice{border-radius:9px;padding:10px 12px;margin:10px 0;background:color-mix(in srgb,#5686fe 12%,var(--bg-surface));color:var(--fg);overflow-wrap:anywhere}.pptw .error{background:color-mix(in srgb,#f25a5a 14%,var(--bg-surface))}
209
+ .pptw .card{border:1px solid var(--border,#d5dfeb);border-radius:12px;padding:12px;margin:10px 0;background:var(--bg-surface,#fff)}
210
+ .pptw .coaching{margin-top:24px}.pptw .coaching-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 14px}
211
+ .pptw .coaching label.choice{display:flex;gap:8px;align-items:flex-start}.pptw .coaching input[type=checkbox]{width:auto;flex:none;margin-top:5px}
212
+ .pptw .coaching pre{white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;margin:6px 0}.pptw .coaching blockquote{margin:8px 0;padding-left:12px;border-left:3px solid var(--border,#ccd8e5);overflow-wrap:anywhere}
213
+ .pptw .coaching .card{overflow-wrap:anywhere}.pptw .coaching .before-after{display:grid;grid-template-columns:1fr 1fr;gap:12px}
214
+ .pptw .project-list{display:flex;flex-direction:column;gap:8px}.pptw .project-list button{display:block;width:100%}
215
+ .pptw .file{font-size:12px;overflow-wrap:anywhere}.pptw .image-preview{width:100%;max-height:160px;object-fit:contain;background:#edf2f8;border-radius:8px}
216
+ .pptw :focus-visible{outline:3px solid #78a8ff;outline-offset:2px}.pptw .dirty{color:#986114;font-size:13px}
217
+ .pptw .badge-dirty{color:#986114;font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;background:rgba(245,158,11,.14);border:1px solid rgba(245,158,11,.35);margin-left:4px}
218
+ .pptw .notice button{margin-left:8px;padding:2px 9px;border-radius:6px;border:1px solid currentColor;background:transparent;color:inherit;font-size:12px;cursor:pointer}
219
+ [role=dialog]:has(.pptw){width:min(1200px,calc(100vw - 48px))!important;max-width:1200px!important}
220
+ @media(max-width:700px){.pptw .layout{grid-template-columns:1fr}.pptw .pages{max-height:180px}.pptw .preview{min-height:190px}.pptw{padding:3px}
221
+ .pptw .coaching-grid,.pptw .coaching .before-after{grid-template-columns:1fr}
222
+ [role=dialog]:has(.pptw){width:100%!important;max-width:100%!important;flex-direction:column!important}
223
+ [role=dialog]:has(.pptw)>nav+div{min-width:0;width:100%}
224
+ [role=dialog]:has(.pptw)>nav+div>div:has(.pptw){padding:12px!important;min-width:0}
225
+ [role=dialog]:has(.pptw) nav{width:100%!important;flex-basis:auto!important;border-right:0;max-height:170px;overflow:auto}
226
+ [role=dialog]:has(.pptw) nav>div:has(>button){display:flex;flex-direction:row!important;flex-wrap:wrap;flex-shrink:0;gap:4px}
227
+ }`;
228
+
229
+ async function action(body, signal) {
230
+ const response = await fetch(new URL(ROUTE, document.baseURI), { method: 'POST', credentials: 'same-origin', signal,
231
+ headers: { 'content-type': 'application/json', 'x-dsh-ppt-action': '1' }, body: JSON.stringify(body) });
232
+ let value;
233
+ try { value = await response.json(); } catch { throw new Error(t("无法读取服务响应,请检查插件是否加载")) }
234
+ if (!response.ok || value.ok === false) { const localized = languageOf() === 'en' ? value.messageEn || englishError(value.message, response.status) : value.message; const hint = languageOf() === 'en' ? value.installationHintEn : value.installationHint; const error = new Error((localized || t("操作未完成")) + (hint ? '\n' + hint : '')); error.status = response.status; throw error; }
235
+ return value;
236
+ }
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 || '' };
240
+ }
241
+ function editorHtml(html, nonce) {
242
+ 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
+ function tell(field){parent.postMessage({type:'dsh-ppt-select',nonce:nonce,field:field},'*')}
244
+ document.addEventListener('keydown',function(e){
245
+ var mod=e.ctrlKey||e.metaKey;
246
+ if(mod&&(e.key==='s'||e.key==='S')){e.preventDefault();e.stopImmediatePropagation();parent.postMessage({type:'dsh-ppt-shortcut',nonce:nonce,key:'save'},'*');return}
247
+ if(e.key==='Escape'){e.preventDefault();e.stopImmediatePropagation();parent.postMessage({type:'dsh-ppt-shortcut',nonce:nonce,key:'escape'},'*');return}
248
+ if(e.altKey&&(e.key==='ArrowLeft'||e.key==='ArrowRight')){e.preventDefault();e.stopImmediatePropagation();parent.postMessage({type:'dsh-ppt-shortcut',nonce:nonce,key:e.key==='ArrowLeft'?'prev':'next'},'*');return}
249
+ e.stopImmediatePropagation();if(e.key!=='Tab')e.preventDefault()
250
+ },true);
251
+ document.addEventListener('touchstart',function(e){e.stopImmediatePropagation()},true);
252
+ document.addEventListener('touchend',function(e){e.stopImmediatePropagation()},true);
253
+ 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;
255
+ 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)});
257
+ })();<\/script>`;
258
+ 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
+ // Presenter code contains a quoted </body>; only append at the document end.
260
+ return html.replace(/<head>/i, '<head>' + policy).replace(/<\/body>(\s*<\/html>\s*)$/i, bridge + '</body>$1');
261
+ }
262
+ function createImageLoader() {
263
+ let current = null;
264
+ function cancel() {
265
+ const reader = current; current = null;
266
+ if (reader?.readyState === 1) reader.abort();
267
+ }
268
+ return {
269
+ cancel,
270
+ get pending() { return current !== null; },
271
+ read(file, success, failure) {
272
+ cancel(); const reader = new FileReader(); current = reader;
273
+ const settle = callback => { if (current !== reader) return; current = null; callback(); };
274
+ reader.onload = () => settle(() => success(String(reader.result)));
275
+ reader.onerror = () => settle(failure);
276
+ reader.onabort = () => { if (current === reader) current = null; };
277
+ try { reader.readAsDataURL(file); } catch { settle(failure); }
278
+ },
279
+ };
280
+ }
281
+ function CoachingPanel({ project, selected, blocked, onAdopt, onChoose }) {
282
+ const L = (zh, en) => languageOf() === 'en' ? en : zh;
283
+ const [mode, setMode] = useState(''), [routes, setRoutes] = useState([]), [route, setRoute] = useState('');
284
+ const [difficulty, setDifficulty] = useState('normal'), [audience, setAudience] = useState('general'), [limit, setLimit] = useState(1);
285
+ const [scope, setScope] = useState('all'), [material, setMaterial] = useState(''), [run, setRun] = useState(null), [history, setHistory] = useState([]);
286
+ const [answer, setAnswer] = useState(''), [patches, setPatches] = useState([]), [backups, setBackups] = useState([]);
287
+ const [busy, setBusy] = useState(false), [error, setError] = useState(''), [notice, setNotice] = useState('');
288
+ const active = useRef(null), alive = useRef(true), current = useRef(null), runRef = useRef(null), reading = useRef(0);
289
+ current.current = { project, selected, blocked }; runRef.current = run;
290
+ const stale = !!run && (run.stale || run.revision !== project.revision);
291
+ const maxCalls = mode === 'review' ? limit : limit + 1;
292
+ const modeName = value => value === 'review' ? L('AI 预审', 'AI review') : L('模拟答辩', 'Rehearsal');
293
+ const statusName = value => ({ ready: L('等待下一步', 'Ready'), busy: L('正在调用模型', 'Calling model'), paused: L('已暂停', 'Paused'), complete: L('已结束', 'Finished') })[value] || value;
294
+ const kindName = value => ({ expression: L('表达建议', 'Expression'), logic: L('逻辑问题', 'Logic'), evidence: L('证据缺口', 'Missing evidence') })[value];
295
+ function accept(value) { if (alive.current) { runRef.current = value; setRun(value); } }
296
+ const request = (operation, data = {}, signal) => action({ operation: 'coach-' + operation, id: current.current.project.id, expectedRevision: current.current.project.revision, ...data }, signal);
297
+ async function refresh(signal) { const value = await request('list', {}, signal); if (alive.current) setHistory(value.runs); }
298
+ useEffect(() => {
299
+ alive.current = true;
300
+ return () => {
301
+ alive.current = false; reading.current++;
302
+ if (active.current) {
303
+ active.current.abort();
304
+ const item = runRef.current;
305
+ if (item) void request('stop', { runId: item.id }).catch(() => {});
306
+ }
307
+ };
308
+ }, []);
309
+ useEffect(() => {
310
+ if (!run || run.status !== 'busy' || busy) return;
311
+ const controller = new AbortController();
312
+ const timer = setInterval(() => { void request('get', { runId: run.id }, controller.signal).then(value => { if (!controller.signal.aborted) accept(value.run); }).catch(() => {}); }, 750);
313
+ return () => { clearInterval(timer); controller.abort(); };
314
+ }, [run?.id, run?.status, busy]);
315
+ async function task(work) {
316
+ if (active.current) return;
317
+ const controller = new AbortController(); active.current = controller;
318
+ setBusy(true); setError(''); setNotice('');
319
+ try { await work(controller.signal); }
320
+ catch (e) {
321
+ if (!alive.current) return;
322
+ if (!controller.signal.aborted) setError(e.message || L('操作失败', 'Operation failed'));
323
+ const item = runRef.current;
324
+ if (item) { try { accept((await request('get', { runId: item.id })).run); } catch { /* Keep visible results. */ } }
325
+ } finally {
326
+ if (active.current === controller) active.current = null;
327
+ if (alive.current) setBusy(false);
328
+ }
329
+ }
330
+ function configure(value) {
331
+ if (active.current || !canLeave()) return;
332
+ setMode(value); setLimit(value === 'review' ? 1 : 3); accept(null); setPatches([]); setBackups([]); setAnswer('');
333
+ return task(async signal => {
334
+ const results = await Promise.allSettled([request('options', {}, signal), refresh(signal)]);
335
+ if (signal.aborted || !alive.current) return;
336
+ const available = results[0];
337
+ if (available.status === 'rejected') throw available.reason;
338
+ const models = available.value.routes;
339
+ setRoutes(models);
340
+ const preferred = models.findIndex(r => r.provider === project.modelRoute?.provider && r.model === project.modelRoute?.model);
341
+ setRoute(models.length ? String(Math.max(0, preferred)) : '');
342
+ if (!models.length) setNotice(L('先在 DSH 的模型设置中配置可用模型,再点“刷新模型”。成品仍可直接下载。', 'Configure a model in DSH, then refresh models. Your finished files remain available.'));
343
+ if (results[1].status === 'rejected') throw results[1].reason;
344
+ });
345
+ }
346
+ function canLeave() {
347
+ const item = runRef.current, question = item?.questions.at(-1);
348
+ return !(item?.mode === 'practice' && question && !question.feedback && answer.trim() && answer.trim() !== (question.answer || '')) || window.confirm(L('当前回答尚未提交,离开会丢失。继续吗?', 'Your answer has not been submitted and will be lost. Continue?'));
349
+ }
350
+ async function advance(item, signal, response) {
351
+ let next = (await request('step', { runId: item.id, confirmed: true, ...(response === undefined ? {} : { answer: response }) }, signal)).run;
352
+ accept(next);
353
+ // Only this explicit Start click authorizes the configured review rounds.
354
+ while (next.mode === 'review' && next.status === 'ready' && !next.stale && !signal.aborted && current.current.project.revision === next.revision) {
355
+ next = (await request('step', { runId: next.id, confirmed: true }, signal)).run; accept(next);
356
+ }
357
+ await refresh(signal);
358
+ if (alive.current && response !== undefined) setAnswer('');
359
+ }
360
+ function start() {
361
+ if (current.current.blocked) return;
362
+ return task(async signal => {
363
+ const model = routes[Number(route)]; if (!model) throw new Error(L('请选择模型', 'Choose a model'));
364
+ reading.current++;
365
+ const item = (await request('create', { confirmed: true, mode, ...model, difficulty, audience, limit, material,
366
+ language: languageOf(), ...(scope === 'current' ? { slideId: current.current.selected } : {}) }, signal)).run;
367
+ accept(item); await advance(item, signal);
368
+ });
369
+ }
370
+ function stop() {
371
+ active.current?.abort();
372
+ if (runRef.current) void request('stop', { runId: runRef.current.id }).then(value => accept(value.run)).catch(e => { if (alive.current) setError(e.message); });
373
+ setNotice(L('已请求停止。已完成的结果保留,本次调用仍可能计费。', 'Stop requested. Completed results are kept; the current call may still be billed.'));
374
+ }
375
+ function finish() { return task(async signal => { accept((await request('finish', { runId: run.id }, signal)).run); await refresh(signal); }); }
376
+ function openReport(id) { if (!canLeave()) return; return task(async signal => { const value = (await request('get', { runId: id }, signal)).run; accept(value); setMode(value.mode); setAnswer(value.questions.at(-1)?.answer || ''); setPatches([]); setBackups([]); }); }
377
+ function removeReport() {
378
+ if (!window.confirm(L('删除这次本地演练记录?幻灯片成品不受影响。', 'Delete this local rehearsal record? Presentation files are kept.'))) return;
379
+ return task(async signal => { await request('delete', { runId: run.id }, signal); accept(null); await refresh(signal); });
380
+ }
381
+ function exportReport() {
382
+ const url = new URL('api/dsh-ppt/download', document.baseURI);
383
+ for (const [key, value] of Object.entries({ id: project.id, kind: 'coaching', revision: project.revision, run: run.id })) url.searchParams.set(key, String(value));
384
+ const link = document.createElement('a'); link.href = url.href; link.download = ''; link.hidden = true; document.body.append(link); link.click(); link.remove();
385
+ }
386
+ function applySelected() {
387
+ if (current.current.blocked || stale) return;
388
+ return task(async signal => {
389
+ const value = await request('apply', { runId: run.id, confirmed: true, selected: patches, backup: backups }, signal);
390
+ if (alive.current) onAdopt(value.project);
391
+ });
392
+ }
393
+ async function uploadMaterial(event) {
394
+ const file = event.target.files?.[0]; event.target.value = ''; if (!file) return;
395
+ const ticket = ++reading.current;
396
+ if (!/\.(txt|md)$/i.test(file.name) || file.size > 100000) { setError(L('请选择 100 KB 以内的 TXT / Markdown 文件。', 'Choose a TXT / Markdown file up to 100 KB.')); return; }
397
+ try {
398
+ const value = await file.text();
399
+ if (!alive.current || ticket !== reading.current) return;
400
+ if (value.length > 20000) throw new Error(L('补充材料最多 20000 字符。', 'Supporting material: up to 20,000 characters.'));
401
+ setMaterial(value); setError('');
402
+ } catch (e) { if (alive.current && ticket === reading.current) setError(e.message); }
403
+ }
404
+ function toggle(set, values, id) { set(values.includes(id) ? values.filter(v => v !== id) : [...values, id]); }
405
+ function pageButton(id) {
406
+ const index = project.slides.findIndex(s => s.id === id);
407
+ return h('button', { disabled: blocked || index < 0, onClick: () => onChoose(id) }, L('查看第 ' + (index + 1) + ' 页', 'View slide ' + (index + 1)));
408
+ }
409
+ function source(card) { return card.reference ? h('blockquote', null, h('small', { className: 'muted' }, card.reference === 'material' ? L('补充材料中的原文', 'Quote from supporting material') : L('幻灯片中的原文', 'Quote from slides')), h('pre', null, card.quote)) : h('p', { className: 'muted' }, L('未匹配到材料原文,请核对或补充依据。', 'No matching source quote. Verify or add supporting evidence.')); }
410
+ const last = run?.questions.at(-1);
411
+ useEffect(() => {
412
+ if (!last || last.feedback || !answer.trim() || answer.trim() === (last.answer || '')) return;
413
+ const warn = event => { event.preventDefault(); event.returnValue = ''; };
414
+ window.addEventListener('beforeunload', warn); return () => window.removeEventListener('beforeunload', warn);
415
+ }, [run?.id, last?.id, last?.feedback, last?.answer, answer]);
416
+ return h('section', { className: 'card coaching', 'aria-label': L('可选演练', 'Optional rehearsal'), onKeyDown: e => { if (e.key === 'Escape' || (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { e.stopPropagation(); if (e.key.toLowerCase() === 's') e.preventDefault(); } } },
417
+ h('h3', null, L('想再准备充分一点?', 'Want to prepare further?')),
418
+ h('p', { className: 'muted' }, L('成品已可下载。以下两项按需开启,不影响直接交付。', 'Your files are ready to download. Both options below are optional.')),
419
+ h('div', { className: 'tools' }, h('button', { disabled: busy, 'aria-pressed': mode === 'review', onClick: () => configure('review') }, L('AI 预审', 'AI review')), h('button', { disabled: busy, 'aria-pressed': mode === 'practice', onClick: () => configure('practice') }, L('模拟答辩', 'Rehearsal')),
420
+ mode && h('button', { disabled: busy, onClick: () => { if (canLeave()) { setMode(''); accept(null); setAnswer(''); } } }, L('收起', 'Collapse'))),
421
+ mode && h(React.Fragment, null,
422
+ error && h('div', { role: 'alert', className: 'notice error' }, error),
423
+ notice && h('div', { role: 'status', className: 'notice' }, notice),
424
+ busy && h('div', { role: 'status', className: 'tools' }, L('正在处理…可以继续预览或下载成品。', 'Working… You can still preview or download your presentation.'), h('button', { onClick: stop }, L('停止', 'Stop'))),
425
+ !run && h(React.Fragment, null,
426
+ h('p', null, mode === 'review' ? L('AI 根据材料模拟质疑与回答,最多保留 5 个值得改进的问题。', 'AI simulates questions and answers based on your material, keeping up to five useful findings.') : L('AI 一次问一题,你来回答;可随时结束并整理已完成的问答。', 'AI asks one question at a time. You answer and can finish at any point.')),
427
+ h('div', { className: 'coaching-grid' },
428
+ h('label', null, L('模型', 'Model'), h('select', { 'aria-label': L('演练模型', 'Rehearsal model'), value: route, disabled: busy, onChange: e => setRoute(e.target.value) }, !routes.length && h('option', { value: '' }, L('暂无可用模型', 'No configured model')), routes.map((r, i) => h('option', { key: i, value: i }, r.label)))),
429
+ h('label', null, L('听众', 'Audience'), h('select', { 'aria-label': L('听众', 'Audience'), value: audience, disabled: busy, onChange: e => setAudience(e.target.value) }, [['general', L('一般听众', 'General audience')], ['management', L('管理层 / 客户', 'Management / clients')], ['academic', L('答辩评委', 'Academic panel')]].map(([v, label]) => h('option', { key: v, value: v }, label)))),
430
+ h('label', null, L('提问强度', 'Difficulty'), h('select', { 'aria-label': L('提问强度', 'Difficulty'), value: difficulty, disabled: busy, onChange: e => setDifficulty(e.target.value) }, [['gentle', L('温和', 'Gentle')], ['normal', L('普通', 'Normal')], ['strict', L('严格', 'Strict')]].map(([v, label]) => h('option', { key: v, value: v }, label)))),
431
+ h('label', null, mode === 'review' ? L('预审轮数', 'Review rounds') : L('答辩题数', 'Questions'), h('select', { 'aria-label': mode === 'review' ? L('预审轮数', 'Review rounds') : L('答辩题数', 'Questions'), value: limit, disabled: busy, onChange: e => setLimit(Number(e.target.value)) }, Array.from({ length: mode === 'review' ? 3 : 5 }, (_, i) => h('option', { key: i, value: i + 1 }, String(i + 1))))),
432
+ h('label', null, L('检查范围', 'Scope'), h('select', { 'aria-label': L('检查范围', 'Scope'), value: scope, disabled: busy, onChange: e => setScope(e.target.value) }, h('option', { value: 'all' }, L('整个工程', 'Whole presentation')), h('option', { value: 'current' }, L('当前页', 'Current slide'))))),
433
+ h('label', { htmlFor: 'ppt-coach-material' }, L('补充材料(可选)', 'Supporting material (optional)')),
434
+ h('textarea', { id: 'ppt-coach-material', rows: 3, maxLength: 20000, value: material, disabled: busy, onChange: e => { reading.current++; setMaterial(e.target.value); } }),
435
+ h('label', null, L('或导入 TXT / Markdown', 'Or import TXT / Markdown'), h('input', { type: 'file', accept: '.txt,.md,text/plain,text/markdown', disabled: busy, onChange: uploadMaterial })),
436
+ h('p', { className: 'muted' }, L('将所选页面的文字、图表数据、备注及补充材料发送给所选 DSH 模型,不发送图片文件。最多 ' + maxCalls + ' 次插件调用;模型服务自身的重试与计费规则仍适用。', 'Sends selected slide text, chart data, notes and supporting material to the chosen DSH model. Image files are excluded. Up to ' + maxCalls + ' plugin calls; provider retry and billing rules still apply.')),
437
+ h('div', { className: 'tools' }, h('button', { disabled: busy || blocked || !routes.length, onClick: start }, mode === 'review' ? L('开始 AI 预审', 'Start AI review') : L('开始模拟答辩', 'Start rehearsal')), h('button', { disabled: busy, onClick: () => configure(mode) }, L('刷新模型', 'Refresh models'))),
438
+ blocked && h('p', { className: 'muted' }, L('请先保存或取消幻灯片修改。', 'Save or cancel slide edits first.'))),
439
+ run && h(React.Fragment, null,
440
+ h('h3', null, modeName(run.mode) + ' · ' + statusName(run.status)),
441
+ h('p', { className: 'muted' }, L('修订 ', 'Revision ') + run.revision + ' · ' + run.route.provider + ' / ' + run.route.model + ' · ' + L('调用 ', 'Calls ') + run.usedCalls + '/' + run.maxCalls),
442
+ h('p', { className: 'muted' }, L('AI 意见不等于事实核验,也不代表真实听众的评价。请先看原文与改动,再决定是否采纳。', 'AI suggestions are not fact checks or predictions of audience feedback. Compare sources and edits before adopting them.')),
443
+ stale && h('div', { role: 'alert', className: 'notice' }, L('工程已经修改。旧报告仍可导出,但不能继续调用或采纳;请重新开始。', 'The presentation changed. You can export this report, but cannot continue or apply it. Start a new rehearsal.')),
444
+ run.error && h('p', { className: 'muted' }, languageOf() === 'en' ? run.error.split(' / ').at(-1) : run.error.split(' / ')[0]),
445
+ run.findings.map(f => {
446
+ const slide = project.slides.find(s => s.id === f.slideId);
447
+ return h('article', { key: f.id, className: 'card' }, h('strong', null, kindName(f.kind) + ' · ' + f.issue), h('div', { className: 'tools' }, pageButton(f.slideId)),
448
+ h('p', null, f.question), h('p', null, f.answer), h('p', null, f.suggestion), source(f),
449
+ f.patch && h(React.Fragment, null, h('details', null, h('summary', null, L('比较原文和建议', 'Compare before and after')), Object.entries(f.patch).map(([key, value]) => h('div', { key }, h('strong', null, t(fields.find(([name]) => name === key)?.[1] || key)), h('div', { className: 'before-after' }, h('div', null, h('small', null, L('原文', 'Before')), h('pre', null, Array.isArray(slide?.[key]) ? slide[key].join('\n') : slide?.[key] || '')), h('div', null, h('small', null, L('建议', 'After')), h('pre', null, Array.isArray(value) ? value.join('\n') : value)))))),
450
+ h('label', { className: 'choice' }, h('input', { type: 'checkbox', disabled: busy || stale, checked: patches.includes(f.id), onChange: () => toggle(setPatches, patches, f.id) }), L('采纳这项表达修改', 'Adopt this expression edit'))),
451
+ h('label', { className: 'choice' }, h('input', { type: 'checkbox', disabled: busy || stale, checked: backups.includes(f.id), onChange: () => toggle(setBackups, backups, f.id) }), L('选为备用问答页', 'Add as a backup Q&A slide')));
452
+ }),
453
+ run.mode === 'review' && run.status === 'complete' && !run.findings.length && h('p', null, L('本次未提出明显问题。仍建议检查事实、字体和最终 PPTX。', 'No findings this time. Still check facts, fonts and the final PPTX.')),
454
+ run.questions.map((q, i) => h('article', { key: q.id, className: 'card' }, h('strong', null, (i + 1) + '. ' + q.question), h('div', { className: 'tools' }, pageButton(q.slideId)), q.answer && h('p', null, L('你的回答:', 'Your answer: ') + q.answer), q.feedback && h('p', null, q.feedback), q.needsEvidence && h('p', { className: 'muted' }, L('待补充依据', 'Evidence needed')), source(q),
455
+ q.answer && h('label', { className: 'choice' }, h('input', { type: 'checkbox', disabled: busy || stale, checked: backups.includes(q.id), onChange: () => toggle(setBackups, backups, q.id) }), L('选为备用问答页', 'Add as a backup Q&A slide')))),
456
+ run.mode === 'practice' && last && !last.feedback && run.status !== 'complete' && !stale && h(React.Fragment, null,
457
+ h('label', { htmlFor: 'ppt-coach-answer' }, L('你的回答', 'Your answer')), h('textarea', { id: 'ppt-coach-answer', maxLength: 4000, rows: 4, value: answer, disabled: busy, onChange: e => setAnswer(e.target.value) }),
458
+ h('button', { disabled: busy || blocked || !answer.trim() || run.usedCalls >= run.maxCalls, onClick: () => task(signal => advance(run, signal, answer)) }, L('提交回答,继续', 'Submit answer and continue'))),
459
+ h('div', { className: 'tools' }, h('button', { disabled: busy, onClick: exportReport }, L('下载问答与材料清单', 'Download Q&A and evidence checklist')),
460
+ h('button', { disabled: busy || blocked || stale || !(patches.length + backups.length), onClick: applySelected }, L('将所选内容保存为副本', 'Save selected changes as a copy')),
461
+ run.status !== 'complete' && h('button', { disabled: busy || run.status === 'busy', onClick: finish }, L('结束并整理已有结果', 'Finish with current results')),
462
+ h('button', { disabled: busy, onClick: () => configure(run.mode) }, L('重新开始', 'Start again')),
463
+ h('button', { disabled: busy || run.status === 'busy', onClick: removeReport }, L('删除本次记录', 'Delete this record'))),
464
+ 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
+ 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
+ }
467
+ function Workbench({ locale } = {}) {
277
468
  useLanguage(locale);
278
- const [projects, setProjects] = useState([]), [project, setProject] = useState(null), [selected, setSelected] = useState('');
279
- const [draft, setDraft] = useState({}), [image, setImage] = useState(null), [dirty, setDirty] = useState(false);
280
- const [busy, setBusy] = useState(false), [job, setJob] = useState(''), [message, setMessage] = useState(''), [error, setError] = useState('');
281
- const [mode, setMode] = useState('html'), [raster, setRaster] = useState('');
282
- const [conflict, setConflict] = useState(false), [overlaps, setOverlaps] = useState([]);
283
- const frame = useRef(null), previewBox = useRef(null), fieldRefs = useRef({}), alive = useRef(true), operations = useRef(new Set());
284
- const imageLoader = useRef(null);
285
- if (!imageLoader.current) imageLoader.current = createImageLoader();
286
- const imagePending = imageLoader.current.pending;
287
- const nonce = useRef(crypto.randomUUID());
288
- const previewDocument = useMemo(() => project?.html ? editorHtml(project.html, nonce.current) : '', [project?.html]);
289
- const index = project ? Math.max(0, project.slides.findIndex(s => s.id === selected)) : 0;
290
- const slide = project?.slides[index];
291
- function adopt(next, preferred) {
292
- imageLoader.current.cancel();
293
- setProject(next);
294
- const row = next.slides.find(s => s.id === preferred) || next.slides[0];
295
- setSelected(row.id); setDraft(draftFor(row)); setImage(null); setDirty(false); setRaster(''); setOverlaps([]);
296
- if (!next.render) setMode('html');
297
- }
298
- async function perform(work, success, label = t("正在处理,请稍候…")) {
299
- setBusy(true); setJob(label); setError(''); setMessage(''); setConflict(false);
300
- const controller = new AbortController(); operations.current.add(controller);
301
- try { const result = await work(controller.signal); if (alive.current && success) success(result); }
302
- catch (e) { if (alive.current) { setError(e.message || t("操作失败")); setConflict(e.status === 409); } }
303
- finally { operations.current.delete(controller); if (alive.current) setBusy(false); }
304
- }
305
- function refreshList() { return perform(signal => action({ operation: 'list' }, signal), value => setProjects(value.projects)); }
306
- useEffect(() => {
307
- alive.current = true; const abort = new AbortController();
308
- action({ operation: 'list' }, abort.signal).then(value => { if (alive.current) setProjects(value.projects) }).catch(e => { if (!abort.signal.aborted) setError(e.message) });
309
- return () => { alive.current = false; abort.abort(); imageLoader.current.cancel(); for (const operation of operations.current) operation.abort(); };
310
- }, []);
311
- useEffect(() => {
312
- function receive(event) {
469
+ const [projects, setProjects] = useState([]), [project, setProject] = useState(null), [selected, setSelected] = useState('');
470
+ const [draft, setDraft] = useState({}), [image, setImage] = useState(null), [dirty, setDirty] = useState(false);
471
+ const [busy, setBusy] = useState(false), [job, setJob] = useState(''), [message, setMessage] = useState(''), [error, setError] = useState('');
472
+ const [mode, setMode] = useState('html'), [raster, setRaster] = useState('');
473
+ const [conflict, setConflict] = useState(false), [overlaps, setOverlaps] = useState([]);
474
+ const frame = useRef(null), previewBox = useRef(null), fieldRefs = useRef({}), alive = useRef(true), operations = useRef(new Set());
475
+ const imageLoader = useRef(null);
476
+ if (!imageLoader.current) imageLoader.current = createImageLoader();
477
+ const imagePending = imageLoader.current.pending;
478
+ const nonce = useRef(crypto.randomUUID());
479
+ const previewDocument = useMemo(() => project?.html ? editorHtml(project.html, nonce.current) : '', [project?.html]);
480
+ const index = project ? Math.max(0, project.slides.findIndex(s => s.id === selected)) : 0;
481
+ const slide = project?.slides[index];
482
+ function adopt(next, preferred) {
483
+ imageLoader.current.cancel();
484
+ setProject(next);
485
+ const row = next.slides.find(s => s.id === preferred) || next.slides[0];
486
+ setSelected(row.id); setDraft(draftFor(row)); setImage(null); setDirty(false); setRaster(''); setOverlaps([]);
487
+ if (!next.render) setMode('html');
488
+ }
489
+ async function perform(work, success, label = t("正在处理,请稍候…")) {
490
+ setBusy(true); setJob(label); setError(''); setMessage(''); setConflict(false);
491
+ const controller = new AbortController(); operations.current.add(controller);
492
+ try { const result = await work(controller.signal); if (alive.current && success) success(result); }
493
+ catch (e) { if (alive.current) { setError(e.message || t("操作失败")); setConflict(e.status === 409); } }
494
+ finally { operations.current.delete(controller); if (alive.current) setBusy(false); }
495
+ }
496
+ function refreshList() { return perform(signal => action({ operation: 'list' }, signal), value => setProjects(value.projects)); }
497
+ useEffect(() => {
498
+ alive.current = true; const abort = new AbortController();
499
+ action({ operation: 'list' }, abort.signal).then(value => { if (alive.current) setProjects(value.projects) }).catch(e => { if (!abort.signal.aborted) setError(e.message) });
500
+ return () => { alive.current = false; abort.abort(); imageLoader.current.cancel(); for (const operation of operations.current) operation.abort(); };
501
+ }, []);
502
+ useEffect(() => {
503
+ function receive(event) {
313
504
  if (event.source !== frame.current?.contentWindow || event.data?.nonce !== nonce.current || mode !== 'html') return;
314
505
  if (event.data.type === 'dsh-ppt-shortcut') { handleShortcut(event.data.key); return; }
315
506
  if (event.data.type !== 'dsh-ppt-select') return;
316
- const key = event.data.field;
317
- const field = fields.find(([field]) => field === key);
507
+ const key = event.data.field;
508
+ const field = fields.find(([field]) => field === key);
318
509
  if (field) { fieldRefs.current[key]?.focus(); fieldRefs.current[key]?.scrollIntoView({ block: 'nearest' }); setMessage(t("已定位到") + t(field[1]) + t(",在字段中修改后保存。")); }
319
- }
320
- window.addEventListener('message', receive); return () => window.removeEventListener('message', receive);
510
+ }
511
+ window.addEventListener('message', receive); return () => window.removeEventListener('message', receive);
321
512
  }, [mode, project, dirty, busy, imagePending, index, selected, draft, image]);
322
- useEffect(() => {
323
- if (mode !== 'html' || !project || !previewBox.current) return;
324
- // Align iframe edges/dimensions when the host uses fractional text metrics.
325
- const box = previewBox.current;
326
- function align() {
327
- const target = frame.current; if (!target) return;
328
- const r = box.getBoundingClientRect(), x = r.x + box.clientLeft, y = r.y + box.clientTop;
329
- target.style.width = box.clientWidth + 'px'; target.style.height = box.clientHeight + 'px';
330
- target.style.transform = 'translate(' + (Math.ceil(x) - x) + 'px,' + (Math.ceil(y) - y) + 'px)';
331
- }
332
- align(); const observer = new ResizeObserver(align); observer.observe(box);
333
- window.addEventListener('scroll', align, true);
334
- return () => { observer.disconnect(); window.removeEventListener('scroll', align, true); };
335
- }, [mode, !!project]);
336
- function jump() { frame.current?.contentWindow?.postMessage({ type: 'dsh-ppt-jump', nonce: nonce.current, page: index }, '*'); }
337
- useEffect(() => { jump(); }, [index, project?.revision, mode]);
338
- useEffect(() => {
339
- if (mode !== 'pptx' || !project?.render) return;
340
- const abort = new AbortController(); setRaster('');
341
- action({ operation: 'page', id: project.id, page: index + 1 }, abort.signal).then(value => setRaster(value.data)).catch(e => { if (!abort.signal.aborted) setError(e.message) });
342
- return () => abort.abort();
343
- }, [mode, index, project?.revision]);
344
- function handleShortcut(key) {
345
- if (key === 'save') { if (project && dirty && !busy && !imagePending) save(); return; }
346
- if (key === 'escape') {
347
- if (!project || busy || imagePending) return;
348
- if (dirty) {
349
- if (!window.confirm(t("有未保存修改,确定取消吗?"))) return;
350
- setDraft(draftFor(slide)); setImage(null); setDirty(false); setError(''); setMessage(t("已取消未保存的修改。"));
351
- } else {
352
- imageLoader.current.cancel(); setProject(null); refreshList();
353
- }
354
- return;
355
- }
356
- if (key === 'prev' || key === 'next') {
357
- if (!project || busy || dirty || imagePending) return;
358
- const next = index + (key === 'next' ? 1 : -1);
359
- if (next >= 0 && next < project.slides.length) choose(project.slides[next]);
360
- }
361
- }
362
- useEffect(() => {
363
- function onKey(event) {
364
- if (event.isComposing || event.defaultPrevented) return;
365
- if (event.key === 'Escape' && event.target && event.target.tagName === 'SELECT') return;
366
- const mod = event.ctrlKey || event.metaKey;
367
- if (mod && (event.key === 's' || event.key === 'S')) {
368
- if (!project) return;
369
- event.preventDefault(); handleShortcut('save'); return;
370
- }
371
- if (event.key === 'Escape') {
372
- if (!project || busy || imagePending) return;
373
- event.preventDefault(); handleShortcut('escape'); return;
374
- }
375
- if (event.altKey && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
376
- if (!project || busy || dirty || imagePending) return;
377
- event.preventDefault(); handleShortcut(event.key === 'ArrowRight' ? 'next' : 'prev');
378
- }
379
- }
380
- document.addEventListener('keydown', onKey);
381
- return () => document.removeEventListener('keydown', onKey);
382
- }, [project, dirty, busy, imagePending, index, selected, draft, image]);
383
- useEffect(() => {
384
- if (!dirty) return;
385
- function warn(event) { event.preventDefault(); event.returnValue = t("有未保存修改,离开页面会丢失。"); }
386
- window.addEventListener('beforeunload', warn);
387
- return () => window.removeEventListener('beforeunload', warn);
388
- }, [dirty]);
389
- function open(id) { return perform(signal => action({ operation: 'open', id }, signal), value => { adopt(value.project); setMessage(t("点击预览里的文字,或在下方修改字段。")); }); }
390
- function keepInputsAndReload() {
391
- const original = draftFor(slide), keys = fields.filter(([key]) => draft[key] !== original[key]).map(([key]) => key), pending = { ...draft }, pendingImage = image;
392
- return perform(signal => action({ operation: 'open', id: project.id }, signal), value => {
393
- const row = value.project.slides.find(s => s.id === selected);
394
- if (!row) { setError(t("当前页已被删除,输入仍保留,请复制需要的内容后取消修改。")); return; }
395
- const latest = draftFor(row), merged = { ...latest }, shared = [];
396
- for (const key of keys) { merged[key] = pending[key]; if (latest[key] !== original[key] && latest[key] !== pending[key]) shared.push({ key, latest: latest[key], yours: pending[key] }); }
397
- adopt(value.project, selected); setDraft(merged); setImage(pendingImage); setDirty(keys.length > 0 || !!pendingImage); setOverlaps(shared);
398
- setMessage(t("已载入最新版本并保留你的修改,请核对后再保存。"));
399
- });
400
- }
401
- function choose(row) { if (dirty || busy) return; imageLoader.current.cancel(); setSelected(row.id); setDraft(draftFor(row)); setImage(null); setMessage(''); }
402
- function save(saveAs = false) {
403
- const original = draftFor(slide), patch = {};
404
- 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];
405
- if (image) patch.image = { src: image.src, alt: image.alt, fit: image.fit, caption: image.caption };
406
- return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, slide: slide.id, patch, saveAs }, signal), value => {
407
- adopt(value.project, slide.id); setMessage(saveAs ? t("副本已保存,原文件保留。副本从工程生成,不包含 Office 手工修改。") : value.changed === false ? t("内容没有变化。") : t("已保存,HTML、PPTX 和工程文件已同步更新。"));
408
- });
409
- }
410
- function move(delta) {
411
- const order = project.slides.map(s => s.id); [order[index], order[index + delta]] = [order[index + delta], order[index]];
412
- return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, order }, signal), value => { adopt(value.project, slide.id); setMessage(t("页面顺序已更新,可撤销。")); });
413
- }
414
- function structure(operation) {
415
- return perform(signal => action({ operation, id: project.id, expectedRevision: project.revision, slide: slide.id }, signal), value => {
416
- adopt(value.project, value.selected);
417
- setMessage(operation === 'duplicate' ? t("页面已复制,图片、图表和备注一并保留,可撤销。") : t("页面已删除,可撤销。"));
418
- });
419
- }
420
- function undo() { return perform(signal => action({ operation: 'undo', id: project.id, expectedRevision: project.revision }, signal), value => { adopt(value.project, selected); setMessage(t("已撤销上次修改。")); }); }
421
- function render() {
422
- 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,较大文件可能需要几分钟…"));
423
- }
424
- function download(kind) {
425
- const url = new URL('api/dsh-ppt/download', document.baseURI);
426
- url.searchParams.set('id', project.id); url.searchParams.set('kind', kind); url.searchParams.set('revision', String(project.revision));
427
- // An authenticated attachment response keeps the click's user gesture and
428
- // works in WebViews whose native download handler cannot read blob URLs.
429
- const link = document.createElement('a'); link.href = url.href; link.download = '';
430
- link.hidden = true; document.body.append(link); link.click(); link.remove();
431
- setMessage(t("已请求下载,请查看浏览器的下载列表。"));
432
- }
433
- function copyExample() {
434
- const text = t("示例:请把这份材料制作成可直接交付的演示文稿,生成 HTML、PPTX 和工程文件。");
435
- try { navigator.clipboard?.writeText(text).then(() => setMessage(t("已复制示例"))).catch(() => {}); } catch (_) { /* ignore */ }
436
- }
437
- function upload(event) {
438
- const file = event.target.files?.[0]; event.target.value = ''; if (!file) return;
439
- imageLoader.current.cancel(); setMessage(''); setError('');
440
- if (!['image/png', 'image/jpeg'].includes(file.type) || file.size > 5 * 1024 * 1024) { setError(t("请选择 5 MiB 以内的 PNG 或 JPEG 图片。")); return; }
441
- imageLoader.current.read(file, data => {
442
- if (!alive.current) return;
443
- setImage({ src: data, alt: slide.image?.alt || file.name.replace(/\.[^.]+$/, ''), caption: slide.image?.caption || '', fit: slide.image?.fit || 'contain', name: file.name });
444
- setDirty(true); setError(''); setMessage(t("图片已载入,保存后生效。"));
445
- }, () => { if (alive.current) { setError(t("无法读取图片,请重试。")); setMessage(''); } });
446
- if (imageLoader.current.pending) setMessage(t("正在读取图片,切换页面会取消本次读取。"));
447
- }
448
- const currentImage = image?.src || (slide?.image?.assetId && project.assets[slide.image.assetId]?.data);
449
- return h('div', { className: 'pptw', 'aria-busy': busy ? 'true' : undefined }, h('style', null, css),
450
- h('h2', null, t("演示文稿编辑")), h('p', { className: 'muted' }, t("修改本插件生成的成品,保存时同步更新 HTML、可编辑 PPTX 和工程文件。")),
451
- h('p', { className: 'muted' }, t("快捷键:Ctrl/⌘+S 保存 · Esc 取消或返回 · Alt+←/→ 切换页面")),
452
- error && h('div', { role: 'alert', className: 'notice error' }, error, ' ', h('button', { disabled: busy, onClick: () => project ? open(project.id) : refreshList() }, t("重试"))),
453
- conflict && project && h('button', { disabled: busy, onClick: keepInputsAndReload }, t("载入最新版本,保留我的输入")),
454
- message && h('div', { role: 'status', className: 'notice' }, message),
455
- busy && h('div', { role: 'status', className: 'muted' }, job),
456
- !project ? h(React.Fragment, null,
457
- h('div', { className: 'tools' }, h('button', { onClick: refreshList, disabled: busy }, t("刷新项目"))),
458
- 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)))) :
459
- 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("复制示例"))))
460
- ) : h(React.Fragment, null,
461
- 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)),
462
- h('div', { className: 'layout' },
463
- 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("未命名页"))))),
464
- 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("下移")),
465
- h('button', { disabled: busy || dirty || imagePending || project.slides.length >= 120, onClick: () => structure('duplicate') }, t("复制本页")),
466
- h('button', { disabled: busy || dirty || imagePending || project.slides.length <= 1, onClick: () => structure('remove') }, t("删除本页")))),
467
- h('div', null,
468
- h('div', { className: 'tools' }, h('button', { disabled: busy, 'aria-pressed': mode === 'html', onClick: () => setMode('html') }, t("HTML 预览")),
469
- h('button', { disabled: busy || !project.render, 'aria-pressed': mode === 'pptx', onClick: () => setMode('pptx') }, t("最终 PPTX 预览")),
470
- h('button', { disabled: busy || dirty || imagePending, onClick: render }, t("渲染当前 PPTX"))),
471
- 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("正在载入当前页渲染…"))),
472
- h('p', { className: 'muted' }, mode === 'html' ? t("这是 HTML 放映预览。最终 PPTX 的字体和排版请用上方渲染检查。点击文字可定位编辑字段。") : t("这是当前 PPTX 文件的实际渲染图片,仍需检查每页画面;PowerPoint / WPS 可能因字体环境而不同。")),
473
- project.render?.missingFonts?.length ? h('div', { role: 'alert', className: 'notice error' }, t("渲染引擎报告缺失字体:") + project.render.missingFonts.join('、') + t("。请替换为目标电脑可用字体后重新渲染。")) : null,
474
- h('div', { className: 'card' }, h('h3', null, t("编辑第 ") + (index + 1) + t(" 页")),
475
- dirty && h('p', { className: 'dirty' }, t("有未保存修改,请先保存或取消,再切换页面。")),
476
- 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,
477
- 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); } }))),
478
- h('label', { htmlFor: 'pptw-image' }, slide.image ? t("替换图片(PNG / JPEG)") : t("添加图片(会改为图文布局)")),
479
- h('input', { id: 'pptw-image', type: 'file', accept: 'image/png,image/jpeg', disabled: busy, onChange: upload }),
480
- currentImage && h('img', { className: 'image-preview', src: currentImage, alt: image?.alt || slide.image?.alt || t("当前图片") }),
481
- 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("填满并裁切")))),
482
- 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("撤销上次修改")))),
483
- 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)))),
513
+ useEffect(() => {
514
+ if (mode !== 'html' || !project || !previewBox.current) return;
515
+ // Align iframe edges/dimensions when the host uses fractional text metrics.
516
+ const box = previewBox.current;
517
+ function align() {
518
+ const target = frame.current; if (!target) return;
519
+ const r = box.getBoundingClientRect(), x = r.x + box.clientLeft, y = r.y + box.clientTop;
520
+ target.style.width = box.clientWidth + 'px'; target.style.height = box.clientHeight + 'px';
521
+ target.style.transform = 'translate(' + (Math.ceil(x) - x) + 'px,' + (Math.ceil(y) - y) + 'px)';
522
+ }
523
+ align(); const observer = new ResizeObserver(align); observer.observe(box);
524
+ window.addEventListener('scroll', align, true);
525
+ return () => { observer.disconnect(); window.removeEventListener('scroll', align, true); };
526
+ }, [mode, !!project]);
527
+ function jump() { frame.current?.contentWindow?.postMessage({ type: 'dsh-ppt-jump', nonce: nonce.current, page: index }, '*'); }
528
+ useEffect(() => { jump(); }, [index, project?.revision, mode]);
529
+ useEffect(() => {
530
+ if (mode !== 'pptx' || !project?.render) return;
531
+ const abort = new AbortController(); setRaster('');
532
+ action({ operation: 'page', id: project.id, page: index + 1 }, abort.signal).then(value => setRaster(value.data)).catch(e => { if (!abort.signal.aborted) setError(e.message) });
533
+ return () => abort.abort();
534
+ }, [mode, index, project?.revision]);
535
+ function handleShortcut(key) {
536
+ if (key === 'save') { if (project && dirty && !busy && !imagePending) save(); return; }
537
+ if (key === 'escape') {
538
+ if (!project || busy || imagePending) return;
539
+ if (dirty) {
540
+ if (!window.confirm(t("有未保存修改,确定取消吗?"))) return;
541
+ setDraft(draftFor(slide)); setImage(null); setDirty(false); setError(''); setMessage(t("已取消未保存的修改。"));
542
+ } else {
543
+ imageLoader.current.cancel(); setProject(null); refreshList();
544
+ }
545
+ return;
546
+ }
547
+ if (key === 'prev' || key === 'next') {
548
+ if (!project || busy || dirty || imagePending) return;
549
+ const next = index + (key === 'next' ? 1 : -1);
550
+ if (next >= 0 && next < project.slides.length) choose(project.slides[next]);
551
+ }
552
+ }
553
+ useEffect(() => {
554
+ function onKey(event) {
555
+ if (event.isComposing || event.defaultPrevented) return;
556
+ if (event.key === 'Escape' && event.target && event.target.tagName === 'SELECT') return;
557
+ const mod = event.ctrlKey || event.metaKey;
558
+ if (mod && (event.key === 's' || event.key === 'S')) {
559
+ if (!project) return;
560
+ event.preventDefault(); handleShortcut('save'); return;
561
+ }
562
+ if (event.key === 'Escape') {
563
+ if (!project || busy || imagePending) return;
564
+ event.preventDefault(); handleShortcut('escape'); return;
565
+ }
566
+ if (event.altKey && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
567
+ if (!project || busy || dirty || imagePending) return;
568
+ event.preventDefault(); handleShortcut(event.key === 'ArrowRight' ? 'next' : 'prev');
569
+ }
570
+ }
571
+ document.addEventListener('keydown', onKey);
572
+ return () => document.removeEventListener('keydown', onKey);
573
+ }, [project, dirty, busy, imagePending, index, selected, draft, image]);
574
+ useEffect(() => {
575
+ if (!dirty) return;
576
+ function warn(event) { event.preventDefault(); event.returnValue = t("有未保存修改,离开页面会丢失。"); }
577
+ window.addEventListener('beforeunload', warn);
578
+ return () => window.removeEventListener('beforeunload', warn);
579
+ }, [dirty]);
580
+ function open(id) { return perform(signal => action({ operation: 'open', id }, signal), value => { adopt(value.project); setMessage(t("点击预览里的文字,或在下方修改字段。")); }); }
581
+ function keepInputsAndReload() {
582
+ const original = draftFor(slide), keys = fields.filter(([key]) => draft[key] !== original[key]).map(([key]) => key), pending = { ...draft }, pendingImage = image;
583
+ return perform(signal => action({ operation: 'open', id: project.id }, signal), value => {
584
+ const row = value.project.slides.find(s => s.id === selected);
585
+ if (!row) { setError(t("当前页已被删除,输入仍保留,请复制需要的内容后取消修改。")); return; }
586
+ const latest = draftFor(row), merged = { ...latest }, shared = [];
587
+ for (const key of keys) { merged[key] = pending[key]; if (latest[key] !== original[key] && latest[key] !== pending[key]) shared.push({ key, latest: latest[key], yours: pending[key] }); }
588
+ adopt(value.project, selected); setDraft(merged); setImage(pendingImage); setDirty(keys.length > 0 || !!pendingImage); setOverlaps(shared);
589
+ setMessage(t("已载入最新版本并保留你的修改,请核对后再保存。"));
590
+ });
591
+ }
592
+ function choose(row) { if (dirty || busy) return; imageLoader.current.cancel(); setSelected(row.id); setDraft(draftFor(row)); setImage(null); setMessage(''); }
593
+ function save(saveAs = false) {
594
+ const original = draftFor(slide), patch = {};
595
+ 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
+ if (image) patch.image = { src: image.src, alt: image.alt, fit: image.fit, caption: image.caption };
597
+ return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, slide: slide.id, patch, saveAs }, signal), value => {
598
+ adopt(value.project, slide.id); setMessage(saveAs ? t("副本已保存,原文件保留。副本从工程生成,不包含 Office 手工修改。") : value.changed === false ? t("内容没有变化。") : t("已保存,HTML、PPTX 和工程文件已同步更新。"));
599
+ });
600
+ }
601
+ function move(delta) {
602
+ const order = project.slides.map(s => s.id); [order[index], order[index + delta]] = [order[index + delta], order[index]];
603
+ return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, order }, signal), value => { adopt(value.project, slide.id); setMessage(t("页面顺序已更新,可撤销。")); });
604
+ }
605
+ function structure(operation) {
606
+ return perform(signal => action({ operation, id: project.id, expectedRevision: project.revision, slide: slide.id }, signal), value => {
607
+ adopt(value.project, value.selected);
608
+ setMessage(operation === 'duplicate' ? t("页面已复制,图片、图表和备注一并保留,可撤销。") : t("页面已删除,可撤销。"));
609
+ });
610
+ }
611
+ function undo() { return perform(signal => action({ operation: 'undo', id: project.id, expectedRevision: project.revision }, signal), value => { adopt(value.project, selected); setMessage(t("已撤销上次修改。")); }); }
612
+ function render() {
613
+ 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
+ }
615
+ function download(kind) {
616
+ const url = new URL('api/dsh-ppt/download', document.baseURI);
617
+ url.searchParams.set('id', project.id); url.searchParams.set('kind', kind); url.searchParams.set('revision', String(project.revision));
618
+ // An authenticated attachment response keeps the click's user gesture and
619
+ // works in WebViews whose native download handler cannot read blob URLs.
620
+ const link = document.createElement('a'); link.href = url.href; link.download = '';
621
+ link.hidden = true; document.body.append(link); link.click(); link.remove();
622
+ setMessage(t("已请求下载,请查看浏览器的下载列表。"));
623
+ }
624
+ function copyExample() {
625
+ const text = t("示例:请把这份材料制作成可直接交付的演示文稿,生成 HTML、PPTX 和工程文件。");
626
+ try { navigator.clipboard?.writeText(text).then(() => setMessage(t("已复制示例"))).catch(() => {}); } catch (_) { /* ignore */ }
627
+ }
628
+ function upload(event) {
629
+ const file = event.target.files?.[0]; event.target.value = ''; if (!file) return;
630
+ imageLoader.current.cancel(); setMessage(''); setError('');
631
+ if (!['image/png', 'image/jpeg'].includes(file.type) || file.size > 5 * 1024 * 1024) { setError(t("请选择 5 MiB 以内的 PNG 或 JPEG 图片。")); return; }
632
+ imageLoader.current.read(file, data => {
633
+ if (!alive.current) return;
634
+ setImage({ src: data, alt: slide.image?.alt || file.name.replace(/\.[^.]+$/, ''), caption: slide.image?.caption || '', fit: slide.image?.fit || 'contain', name: file.name });
635
+ setDirty(true); setError(''); setMessage(t("图片已载入,保存后生效。"));
636
+ }, () => { if (alive.current) { setError(t("无法读取图片,请重试。")); setMessage(''); } });
637
+ if (imageLoader.current.pending) setMessage(t("正在读取图片,切换页面会取消本次读取。"));
638
+ }
639
+ const currentImage = image?.src || (slide?.image?.assetId && project.assets[slide.image.assetId]?.data);
640
+ return h('div', { className: 'pptw', 'aria-busy': busy ? 'true' : undefined }, h('style', null, css),
641
+ h('h2', null, t("演示文稿编辑")), h('p', { className: 'muted' }, t("修改本插件生成的成品,保存时同步更新 HTML、可编辑 PPTX 和工程文件。")),
642
+ 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("载入最新版本,保留我的输入")),
645
+ message && h('div', { role: 'status', className: 'notice' }, message),
646
+ busy && h('div', { role: 'status', className: 'muted' }, job),
647
+ !project ? h(React.Fragment, null,
648
+ h('div', { className: 'tools' }, h('button', { onClick: refreshList, disabled: busy }, t("刷新项目"))),
649
+ 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
+ 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
+ ) : 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)),
653
+ h('div', { className: 'layout' },
654
+ 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("删除本页")))),
658
+ 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"))),
662
+ 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
+ h('p', { className: 'muted' }, mode === 'html' ? t("这是 HTML 放映预览。最终 PPTX 的字体和排版请用上方渲染检查。点击文字可定位编辑字段。") : t("这是当前 PPTX 文件的实际渲染图片,仍需检查每页画面;PowerPoint / WPS 可能因字体环境而不同。")),
664
+ project.render?.missingFonts?.length ? h('div', { role: 'alert', className: 'notice error' }, t("渲染引擎报告缺失字体:") + project.render.missingFonts.join('、') + t("。请替换为目标电脑可用字体后重新渲染。")) : null,
665
+ h('div', { className: 'card' }, h('h3', null, t("编辑第 ") + (index + 1) + t(" 页")),
666
+ dirty && h('p', { className: 'dirty' }, t("有未保存修改,请先保存或取消,再切换页面。")),
667
+ 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); } }))),
669
+ 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 }),
671
+ 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("撤销上次修改")))),
674
+ 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)))),
484
675
  h('p', { className: 'muted' }, t("成品包包含 PPTX、HTML 和工程文件。请先保存修改,再下载最新版本。")),
485
- 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("备份工程")))
486
- )
487
- )
488
- )
489
- );
490
- }
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,
678
+ onChoose: id => { choose(project.slides.find(s => s.id === id)); previewBox.current?.scrollIntoView({ behavior: 'smooth', block: 'center' }); },
679
+ 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
+ )
681
+ )
682
+ )
683
+ );
684
+ }
491
685
  function apply(ctx) {
492
686
  try { localeService = ctx.get?.('locale') || ctx.locale; } catch { localeService = ctx.locale; }
493
687
  ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: 'dsh-ppt', order: 58, label: () => t("演示文稿"), inject: () => ({ locale: localeService }) }, __withFirstRun(Workbench)));
494
- }
495
- return { inject: ['slots', 'locale'], apply, __internals: { draftFor, editorHtml, createImageLoader } };
496
- } });
688
+ }
689
+ return { inject: ['slots', 'locale'], apply, __internals: { draftFor, editorHtml, createImageLoader } };
690
+ } });