dsh-ppt 0.12.0 → 0.13.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,19 +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",
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.",
118
120
  "演示文稿编辑": "Presentation editor",
119
121
  "修改本插件生成的成品,保存时同步更新 HTML、可编辑 PPTX 和工程文件。": "Edit presentations generated by this plugin. Saving updates the HTML, editable PPTX and project file together.",
120
122
  "载入最新版本,保留我的输入": "Load latest and keep my input",
@@ -165,6 +167,14 @@ const EN = Object.freeze({
165
167
  "成品包包含 PPTX、HTML 和工程文件。请先保存修改,再下载最新版本。": "The bundle includes the PPTX, HTML and project file. Save your edits before downloading the latest version.",
166
168
  "下载 HTML": "Download HTML",
167
169
  "备份工程": "Back up project",
170
+ "快捷键:Ctrl/⌘+S 保存 · Esc 取消或返回 · Alt+←/→ 切换页面": "Shortcuts: Ctrl/⌘+S save · Esc cancel or go back · Alt+←/→ switch slides",
171
+ "未保存": "Unsaved",
172
+ "有未保存修改,确定取消吗?": "Discard unsaved changes?",
173
+ "已取消未保存的修改。": "Unsaved changes discarded.",
174
+ "有未保存修改,离开页面会丢失。": "You have unsaved changes that will be lost.",
175
+ "重试": "Retry",
176
+ "复制示例": "Copy example",
177
+ "已复制示例": "Example copied",
168
178
  "演示文稿": "Presentations"
169
179
  });
170
180
  function languageOf(locale = localeService) {
@@ -181,246 +191,306 @@ function useLanguage(locale) {
181
191
  const [, rerender] = useState(0);
182
192
  useEffect(() => { const update = () => rerender(n => n + 1); update(); return locale?.subscribe?.(update); }, [locale]);
183
193
  }
184
-
185
- const ROUTE = 'api/dsh-ppt/workbench';
186
- const fields = [['title', '标题'], ['subtitle', '副标题'], ['kicker', '眉题'], ['text', '正文'], ['bullets', '要点(每行一条)'], ['notes', '演讲备注']];
187
- const css = `
188
- .pptw {color:var(--fg,#27354b);font:14px/1.6 system-ui,sans-serif;min-width:0;max-width:1140px;margin:0 auto;padding:8px}
189
- .pptw *{box-sizing:border-box}.pptw h2{font-size:22px;margin:0}.pptw h3{font-size:16px;margin:12px 0 6px}
190
- .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}
191
- .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}
192
- .pptw button.primary{background:#245ee9;border-color:#245ee9;color:#fff}.pptw button:disabled{opacity:.45;cursor:default}
193
- .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}
194
- .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}
195
- .pptw .pages{display:flex;flex-direction:column;gap:5px;max-height:480px;overflow:auto}.pptw .pages button[aria-current=true]{background:#245ee9;color:#fff}
196
- .pptw .preview{border:1px solid var(--border,#ced8e6);border-radius:12px;overflow:hidden;background:#f0f4fa;aspect-ratio:16/9;position:relative}
197
- .pptw iframe{position:absolute;inset:0;width:100%;height:100%;border:0}.pptw .render-page{width:100%;display:block}
198
- .pptw .notice{border-radius:9px;padding:10px 12px;margin:10px 0;background:#edf4ff;color:#17408e;overflow-wrap:anywhere}.pptw .error{background:#fff1ef;color:#922d20}
199
- .pptw .card{border:1px solid var(--border,#d5dfeb);border-radius:12px;padding:12px;margin:10px 0;background:var(--bg-surface,#fff)}
200
- .pptw .project-list{display:flex;flex-direction:column;gap:8px}.pptw .project-list button{display:block;width:100%}
201
- .pptw .file{font-size:12px;overflow-wrap:anywhere}.pptw .image-preview{width:100%;max-height:160px;object-fit:contain;background:#edf2f8;border-radius:8px}
202
- .pptw :focus-visible{outline:3px solid #78a8ff;outline-offset:2px}.pptw .dirty{color:#986114;font-size:13px}
203
- [role=dialog]:has(.pptw){width:min(1200px,calc(100vw - 48px))!important;max-width:1200px!important}
204
- @media(max-width:700px){.pptw .layout{grid-template-columns:1fr}.pptw .pages{max-height:180px}.pptw .preview{min-height:190px}.pptw{padding:3px}
205
- [role=dialog]:has(.pptw){width:100%!important;max-width:100%!important;flex-direction:column!important}
206
- [role=dialog]:has(.pptw)>nav+div{min-width:0;width:100%}
207
- [role=dialog]:has(.pptw)>nav+div>div:has(.pptw){padding:12px!important;min-width:0}
208
- [role=dialog]:has(.pptw) nav{width:100%!important;flex-basis:auto!important;border-right:0;max-height:170px;overflow:auto}
209
- [role=dialog]:has(.pptw) nav>div:has(>button){display:flex;flex-direction:row!important;flex-wrap:wrap;flex-shrink:0;gap:4px}
210
- }`;
211
-
212
- async function action(body, signal) {
213
- const response = await fetch(new URL(ROUTE, document.baseURI), { method: 'POST', credentials: 'same-origin', signal,
214
- headers: { 'content-type': 'application/json', 'x-dsh-ppt-action': '1' }, body: JSON.stringify(body) });
215
- let value;
216
- try { value = await response.json(); } catch { throw new Error(t("无法读取服务响应,请检查插件是否加载")) }
217
- 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; }
218
- return value;
219
- }
220
- function draftFor(slide) {
221
- return { title: slide.title || '', subtitle: slide.subtitle || '', kicker: slide.kicker || '', text: slide.text || '',
222
- bullets: (slide.bullets || []).join('\n'), notes: slide.notes || '' };
223
- }
224
- function editorHtml(html, nonce) {
225
- 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)};
226
- function tell(field){parent.postMessage({type:'dsh-ppt-select',nonce:nonce,field:field},'*')}
227
- document.addEventListener('keydown',function(e){e.stopImmediatePropagation();if(e.key!=='Tab')e.preventDefault()},true);
228
- document.addEventListener('touchstart',function(e){e.stopImmediatePropagation()},true);
229
- document.addEventListener('touchend',function(e){e.stopImmediatePropagation()},true);
230
- document.addEventListener('wheel',function(e){e.stopImmediatePropagation()},{capture:true,passive:true});
231
- document.addEventListener('click',function(e){const n=e.target.closest('h1,h2,.subtitle,.kicker,.statement-title,.quote-text,.quote-attr,li');if(!n)return;
232
- e.preventDefault();e.stopImmediatePropagation();let field=n.matches('li')?'bullets':n.matches('.subtitle,.quote-attr')?'subtitle':n.matches('.kicker')?'kicker':'title';tell(field)},true);
233
- 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)});
234
- })();<\/script>`;
235
- 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'">`;
236
- // Presenter code contains a quoted </body>; only append at the document end.
237
- return html.replace(/<head>/i, '<head>' + policy).replace(/<\/body>(\s*<\/html>\s*)$/i, bridge + '</body>$1');
238
- }
239
- function createImageLoader() {
240
- let current = null;
241
- function cancel() {
242
- const reader = current; current = null;
243
- if (reader?.readyState === 1) reader.abort();
244
- }
245
- return {
246
- cancel,
247
- get pending() { return current !== null; },
248
- read(file, success, failure) {
249
- cancel(); const reader = new FileReader(); current = reader;
250
- const settle = callback => { if (current !== reader) return; current = null; callback(); };
251
- reader.onload = () => settle(() => success(String(reader.result)));
252
- reader.onerror = () => settle(failure);
253
- reader.onabort = () => { if (current === reader) current = null; };
254
- try { reader.readAsDataURL(file); } catch { settle(failure); }
255
- },
256
- };
257
- }
258
- 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 {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 } = {}) {
259
277
  useLanguage(locale);
260
- const [projects, setProjects] = useState([]), [project, setProject] = useState(null), [selected, setSelected] = useState('');
261
- const [draft, setDraft] = useState({}), [image, setImage] = useState(null), [dirty, setDirty] = useState(false);
262
- const [busy, setBusy] = useState(false), [job, setJob] = useState(''), [message, setMessage] = useState(''), [error, setError] = useState('');
263
- const [mode, setMode] = useState('html'), [raster, setRaster] = useState('');
264
- const [conflict, setConflict] = useState(false), [overlaps, setOverlaps] = useState([]);
265
- const frame = useRef(null), previewBox = useRef(null), fieldRefs = useRef({}), alive = useRef(true), operations = useRef(new Set());
266
- const imageLoader = useRef(null);
267
- if (!imageLoader.current) imageLoader.current = createImageLoader();
268
- const nonce = useRef(crypto.randomUUID());
269
- const previewDocument = useMemo(() => project?.html ? editorHtml(project.html, nonce.current) : '', [project?.html]);
270
- const index = project ? Math.max(0, project.slides.findIndex(s => s.id === selected)) : 0;
271
- const slide = project?.slides[index];
272
- function adopt(next, preferred) {
273
- imageLoader.current.cancel();
274
- setProject(next);
275
- const row = next.slides.find(s => s.id === preferred) || next.slides[0];
276
- setSelected(row.id); setDraft(draftFor(row)); setImage(null); setDirty(false); setRaster(''); setOverlaps([]);
277
- if (!next.render) setMode('html');
278
- }
279
- async function perform(work, success, label = t("正在处理,请稍候…")) {
280
- setBusy(true); setJob(label); setError(''); setMessage(''); setConflict(false);
281
- const controller = new AbortController(); operations.current.add(controller);
282
- try { const result = await work(controller.signal); if (alive.current && success) success(result); }
283
- catch (e) { if (alive.current) { setError(e.message || t("操作失败")); setConflict(e.status === 409); } }
284
- finally { operations.current.delete(controller); if (alive.current) setBusy(false); }
285
- }
286
- function refreshList() { return perform(signal => action({ operation: 'list' }, signal), value => setProjects(value.projects)); }
287
- useEffect(() => {
288
- alive.current = true; const abort = new AbortController();
289
- action({ operation: 'list' }, abort.signal).then(value => { if (alive.current) setProjects(value.projects) }).catch(e => { if (!abort.signal.aborted) setError(e.message) });
290
- return () => { alive.current = false; abort.abort(); imageLoader.current.cancel(); for (const operation of operations.current) operation.abort(); };
291
- }, []);
292
- useEffect(() => {
293
- function receive(event) {
294
- if (event.source !== frame.current?.contentWindow || event.data?.nonce !== nonce.current || event.data.type !== 'dsh-ppt-select' || mode !== 'html') return;
295
- const key = event.data.field;
296
- const field = fields.find(([field]) => field === key);
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) {
313
+ if (event.source !== frame.current?.contentWindow || event.data?.nonce !== nonce.current || mode !== 'html') return;
314
+ if (event.data.type === 'dsh-ppt-shortcut') { handleShortcut(event.data.key); return; }
315
+ if (event.data.type !== 'dsh-ppt-select') return;
316
+ const key = event.data.field;
317
+ const field = fields.find(([field]) => field === key);
297
318
  if (field) { fieldRefs.current[key]?.focus(); fieldRefs.current[key]?.scrollIntoView({ block: 'nearest' }); setMessage(t("已定位到") + t(field[1]) + t(",在字段中修改后保存。")); }
298
- }
299
- window.addEventListener('message', receive); return () => window.removeEventListener('message', receive);
300
- }, [mode]);
301
- useEffect(() => {
302
- if (mode !== 'html' || !project || !previewBox.current) return;
303
- // Align iframe edges/dimensions when the host uses fractional text metrics.
304
- const box = previewBox.current;
305
- function align() {
306
- const target = frame.current; if (!target) return;
307
- const r = box.getBoundingClientRect(), x = r.x + box.clientLeft, y = r.y + box.clientTop;
308
- target.style.width = box.clientWidth + 'px'; target.style.height = box.clientHeight + 'px';
309
- target.style.transform = 'translate(' + (Math.ceil(x) - x) + 'px,' + (Math.ceil(y) - y) + 'px)';
310
- }
311
- align(); const observer = new ResizeObserver(align); observer.observe(box);
312
- window.addEventListener('scroll', align, true);
313
- return () => { observer.disconnect(); window.removeEventListener('scroll', align, true); };
314
- }, [mode, !!project]);
315
- function jump() { frame.current?.contentWindow?.postMessage({ type: 'dsh-ppt-jump', nonce: nonce.current, page: index }, '*'); }
316
- useEffect(() => { jump(); }, [index, project?.revision, mode]);
317
- useEffect(() => {
318
- if (mode !== 'pptx' || !project?.render) return;
319
- const abort = new AbortController(); setRaster('');
320
- 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) });
321
- return () => abort.abort();
322
- }, [mode, index, project?.revision]);
323
- function open(id) { return perform(signal => action({ operation: 'open', id }, signal), value => { adopt(value.project); setMessage(t("点击预览里的文字,或在下方修改字段。")); }); }
324
- function keepInputsAndReload() {
325
- const original = draftFor(slide), keys = fields.filter(([key]) => draft[key] !== original[key]).map(([key]) => key), pending = { ...draft }, pendingImage = image;
326
- return perform(signal => action({ operation: 'open', id: project.id }, signal), value => {
327
- const row = value.project.slides.find(s => s.id === selected);
328
- if (!row) { setError(t("当前页已被删除,输入仍保留,请复制需要的内容后取消修改。")); return; }
329
- const latest = draftFor(row), merged = { ...latest }, shared = [];
330
- 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] }); }
331
- adopt(value.project, selected); setDraft(merged); setImage(pendingImage); setDirty(keys.length > 0 || !!pendingImage); setOverlaps(shared);
332
- setMessage(t("已载入最新版本并保留你的修改,请核对后再保存。"));
333
- });
334
- }
335
- function choose(row) { if (dirty || busy) return; imageLoader.current.cancel(); setSelected(row.id); setDraft(draftFor(row)); setImage(null); setMessage(''); }
336
- function save() {
337
- const original = draftFor(slide), patch = {};
338
- 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];
339
- if (image) patch.image = { src: image.src, alt: image.alt, fit: image.fit, caption: image.caption };
340
- return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, slide: slide.id, patch }, signal), value => {
341
- adopt(value.project, slide.id); setMessage(value.changed === false ? t("内容没有变化。") : t("已保存,HTML、PPTX 和工程文件已同步更新。"));
342
- });
343
- }
344
- function move(delta) {
345
- const order = project.slides.map(s => s.id); [order[index], order[index + delta]] = [order[index + delta], order[index]];
346
- return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, order }, signal), value => { adopt(value.project, slide.id); setMessage(t("页面顺序已更新,可撤销。")); });
347
- }
348
- function structure(operation) {
349
- return perform(signal => action({ operation, id: project.id, expectedRevision: project.revision, slide: slide.id }, signal), value => {
350
- adopt(value.project, value.selected);
351
- setMessage(operation === 'duplicate' ? t("页面已复制,图片、图表和备注一并保留,可撤销。") : t("页面已删除,可撤销。"));
352
- });
353
- }
354
- function undo() { return perform(signal => action({ operation: 'undo', id: project.id, expectedRevision: project.revision }, signal), value => { adopt(value.project, selected); setMessage(t("已撤销上次修改。")); }); }
355
- function render() {
356
- 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,较大文件可能需要几分钟…"));
357
- }
358
- function download(kind) {
359
- const url = new URL('api/dsh-ppt/download', document.baseURI);
360
- url.searchParams.set('id', project.id); url.searchParams.set('kind', kind); url.searchParams.set('revision', String(project.revision));
361
- // An authenticated attachment response keeps the click's user gesture and
362
- // works in WebViews whose native download handler cannot read blob URLs.
363
- const link = document.createElement('a'); link.href = url.href; link.download = '';
364
- link.hidden = true; document.body.append(link); link.click(); link.remove();
365
- setMessage(t("已请求下载,请查看浏览器的下载列表。"));
366
- }
367
- function upload(event) {
368
- const file = event.target.files?.[0]; event.target.value = ''; if (!file) return;
369
- imageLoader.current.cancel(); setMessage(''); setError('');
370
- if (!['image/png', 'image/jpeg'].includes(file.type) || file.size > 5 * 1024 * 1024) { setError(t("请选择 5 MiB 以内的 PNG 或 JPEG 图片。")); return; }
371
- imageLoader.current.read(file, data => {
372
- if (!alive.current) return;
373
- setImage({ src: data, alt: slide.image?.alt || file.name.replace(/\.[^.]+$/, ''), caption: slide.image?.caption || '', fit: slide.image?.fit || 'contain', name: file.name });
374
- setDirty(true); setError(''); setMessage(t("图片已载入,保存后生效。"));
375
- }, () => { if (alive.current) { setError(t("无法读取图片,请重试。")); setMessage(''); } });
376
- if (imageLoader.current.pending) setMessage(t("正在读取图片,切换页面会取消本次读取。"));
377
- }
378
- const currentImage = image?.src || (slide?.image?.assetId && project.assets[slide.image.assetId]?.data);
379
- const imagePending = imageLoader.current.pending;
380
- return h('div', { className: 'pptw' }, h('style', null, css),
381
- h('h2', null, t("演示文稿编辑")), h('p', { className: 'muted' }, t("修改本插件生成的成品,保存时同步更新 HTML、可编辑 PPTX 和工程文件。")),
382
- error && h('div', { role: 'alert', className: 'notice error' }, error),
383
- conflict && project && h('button', { disabled: busy, onClick: keepInputsAndReload }, t("载入最新版本,保留我的输入")),
384
- message && h('div', { role: 'status', className: 'notice' }, message),
385
- busy && h('div', { role: 'status', className: 'muted' }, job),
386
- !project ? h(React.Fragment, null,
387
- h('div', { className: 'tools' }, h('button', { onClick: refreshList, disabled: busy }, t("刷新项目"))),
388
- 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)))) :
389
- h('div', { className: 'card' }, h('h3', null, t("还没有可以编辑的项目")), h('p', null, t("先在对话中让助手生成演示文稿。已有项目可以让助手调用 ppt_check 检查一次,它会出现在这里。")), h('p', { className: 'muted' }, t("示例:请把这份材料制作成可直接交付的演示文稿,生成 HTML、PPTX 和工程文件。")))
390
- ) : h(React.Fragment, null,
391
- h('div', { className: 'tools' }, h('button', { disabled: busy || dirty, onClick: () => { imageLoader.current.cancel(); setImage(null); setProject(null); refreshList(); } }, t("返回项目")), h('strong', null, project.title), h('span', { className: 'muted' }, project.slides.length + t(" 页 · 修订 ") + project.revision)),
392
- h('div', { className: 'layout' },
393
- 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("未命名页"))))),
394
- 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("下移")),
395
- h('button', { disabled: busy || dirty || imagePending || project.slides.length >= 120, onClick: () => structure('duplicate') }, t("复制本页")),
396
- h('button', { disabled: busy || dirty || imagePending || project.slides.length <= 1, onClick: () => structure('remove') }, t("删除本页")))),
397
- h('div', null,
398
- h('div', { className: 'tools' }, h('button', { disabled: busy, 'aria-pressed': mode === 'html', onClick: () => setMode('html') }, t("HTML 预览")),
399
- h('button', { disabled: busy || !project.render, 'aria-pressed': mode === 'pptx', onClick: () => setMode('pptx') }, t("最终 PPTX 预览")),
400
- h('button', { disabled: busy || dirty || imagePending, onClick: render }, t("渲染当前 PPTX"))),
401
- 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("正在载入当前页渲染…"))),
402
- h('p', { className: 'muted' }, mode === 'html' ? t("这是 HTML 放映预览。最终 PPTX 的字体和排版请用上方渲染检查。点击文字可定位编辑字段。") : t("这是当前 PPTX 文件的实际渲染图片,仍需检查每页画面;PowerPoint / WPS 可能因字体环境而不同。")),
403
- project.render?.missingFonts?.length ? h('div', { role: 'alert', className: 'notice error' }, t("渲染引擎报告缺失字体:") + project.render.missingFonts.join('、') + t("。请替换为目标电脑可用字体后重新渲染。")) : null,
404
- h('div', { className: 'card' }, h('h3', null, t("编辑第 ") + (index + 1) + t(" 页")),
405
- dirty && h('p', { className: 'dirty' }, t("有未保存修改,请先保存或取消,再切换页面。")),
406
- 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,
407
- 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); } }))),
408
- h('label', { htmlFor: 'pptw-image' }, slide.image ? t("替换图片(PNG / JPEG)") : t("添加图片(会改为图文布局)")),
409
- h('input', { id: 'pptw-image', type: 'file', accept: 'image/png,image/jpeg', disabled: busy, onChange: upload }),
410
- currentImage && h('img', { className: 'image-preview', src: currentImage, alt: image?.alt || slide.image?.alt || t("当前图片") }),
411
- 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("填满并裁切")))),
412
- h('div', { className: 'tools' }, h('button', { className: 'primary', disabled: busy || imagePending || !dirty, onClick: save }, t("保存此页")), h('button', { 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("撤销上次修改")))),
413
- h('details', { className: 'card' }, h('summary', null, t("质量提醒(") + project.quality.warningCount + (languageOf() === 'en' ? ')' : ')')), (project.quality.issues || []).map((issue, i) => h('p', { key: i }, t("第 ") + issue.slide + t(" 页:") + (languageOf() === 'en' ? issue.messageEn : issue.message) + (languageOf() === 'en' ? ' ' : ';') + (languageOf() === 'en' ? issue.suggestionEn : issue.suggestion)))),
319
+ }
320
+ window.addEventListener('message', receive); return () => window.removeEventListener('message', receive);
321
+ }, [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)))),
414
484
  h('p', { className: 'muted' }, t("成品包包含 PPTX、HTML 和工程文件。请先保存修改,再下载最新版本。")),
415
- 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("备份工程")))
416
- )
417
- )
418
- )
419
- );
420
- }
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
+ }
421
491
  function apply(ctx) {
422
492
  try { localeService = ctx.get?.('locale') || ctx.locale; } catch { localeService = ctx.locale; }
423
493
  ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: 'dsh-ppt', order: 58, label: () => t("演示文稿"), inject: () => ({ locale: localeService }) }, __withFirstRun(Workbench)));
424
- }
425
- return { inject: ['slots', 'locale'], apply, __internals: { draftFor, editorHtml, createImageLoader } };
426
- } });
494
+ }
495
+ return { inject: ['slots', 'locale'], apply, __internals: { draftFor, editorHtml, createImageLoader } };
496
+ } });