dsh-ppt 0.16.1 → 0.17.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,200 +1,302 @@
1
- // Browser source, distributed directly. tsc deliberately does not rewrite this file.
2
- window.__ModuleLoader__.load({ id: 'dsh-ppt', factory: require => {
3
- const React = require('react');
4
- var __FR_KEY = "dsh-first-run:dsh-ppt:v1";
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."}];
8
- var __FR_STEPS = [{"title":"先选主题","body":"内置 5 套主题(swiss / velvet / data / soft / bold),先定风格再生成内容。"},{"title":"给内容,不给空话","body":"把要点、数据、表格直接给助手,它会排成幻灯片并同时产出 PPTX 与网页版。","tryIt":"把这份季度总结做成 8 页汇报,用 data 主题"},{"title":"先在浏览器里过一遍","body":"网页版可直接翻页预览,确认排版没问题再导出。"},{"title":"导出后看图核对","body":"渲染成图检查一遍再交付,避免字体缺失或溢出。"}];
9
-
10
- // ---- first-run guide (shared snippet; keep in sync across plugins) ----
11
- var __FR_STYLE_ID = 'dsh-first-run-css';
12
- var __FR_CSS = [
13
- '.fr-card{border:1px solid var(--dsw-border,rgba(0,0,0,.10));border-radius:12px;padding:14px 16px;margin:0 0 14px;background:linear-gradient(180deg,rgba(59,130,246,.06),rgba(59,130,246,.02))}',
14
- '.fr-head{display:flex;align-items:center;gap:8px;margin-bottom:6px}',
15
- '.fr-dot{width:6px;height:6px;border-radius:50%;background:var(--dsw-accent,#3b82f6)}',
16
- '.fr-title{font-weight:650;font-size:13.5px}',
17
- '.fr-count{margin-left:auto;font-size:11px;color:var(--dsw-text-weak,#6b7280);font-variant-numeric:tabular-nums}',
18
- '.fr-step{font-weight:600;font-size:13px;margin:2px 0 4px}',
19
- '.fr-body{color:var(--dsw-text-weak,#4b5563);font-size:12.5px;line-height:1.65}',
20
- '.fr-try{margin-top:8px;padding:7px 9px;border-radius:8px;background:rgba(59,130,246,.09);font-size:12px;display:flex;gap:8px}',
21
- '.fr-try code{font-family:ui-monospace,monospace;white-space:pre-wrap;word-break:break-word}',
22
- '.fr-bar{display:flex;gap:8px;align-items:center;margin-top:12px}',
23
- '.fr-progress{display:flex;gap:4px;margin-right:auto}',
24
- '.fr-seg{width:16px;height:3px;border-radius:2px;background:var(--dsw-border,rgba(0,0,0,.12))}',
25
- '.fr-seg.on{background:var(--dsw-accent,#3b82f6)}',
26
- '.fr-btn{border:1px solid var(--dsw-border,rgba(0,0,0,.14));background:transparent;color:inherit;border-radius:8px;padding:4px 10px;font-size:12px;cursor:pointer}',
27
- '.fr-btn:hover{background:rgba(0,0,0,.04)}',
28
- '.fr-btn.primary{background:var(--dsw-accent,#3b82f6);border-color:transparent;color:#fff}',
29
- '.fr-btn.ghost{border-color:transparent;color:var(--dsw-text-weak,#6b7280)}',
30
- ].join('\n');
31
- function __frEnsureCss() {
32
- if (typeof document === 'undefined' || document.getElementById(__FR_STYLE_ID)) return;
33
- var el = document.createElement('style');
34
- el.id = __FR_STYLE_ID;
35
- el.textContent = __FR_CSS;
36
- document.head.appendChild(el);
37
- }
38
- function __frRead() { try { return localStorage.getItem(__FR_KEY) === 'done'; } catch (e) { return false; } }
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;
45
- var doneState = React.useState(__frRead);
46
- var done = doneState[0], setDone = doneState[1];
47
- var idxState = React.useState(0);
48
- var index = idxState[0], setIndex = idxState[1];
49
- React.useEffect(function () { __frEnsureCss(); }, []);
50
- if (done) return null;
51
- var step = steps[index];
52
- var last = index >= steps.length - 1;
53
- var close = function () { __frWrite(); setDone(true); };
54
- var kids = [
55
- React.createElement('div', { className: 'fr-head', key: 'h' },
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)),
59
- React.createElement('div', { className: 'fr-step', key: 't' }, step.title),
60
- React.createElement('div', { className: 'fr-body', key: 'b' }, step.body),
61
- ];
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) {
66
- return React.createElement('span', { key: i, className: 'fr-seg' + (i <= index ? ' on' : '') });
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')));
71
- kids.push(React.createElement('div', { className: 'fr-bar', key: 'bar' }, buttons));
72
- return React.createElement('div', { className: 'fr-card' }, kids);
73
- }
74
- function __withFirstRun(Component) {
75
- return function FirstRunWrapped(props) {
76
- return React.createElement(React.Fragment, null, React.createElement(__FirstRunCard, props), React.createElement(Component, props));
1
+ // Generated from templates/client.js, templates/panels/ and templates/workbench-ui.js. Edit the sources.
2
+ (function () {
3
+ /* DSH workbench UI v1. MIT. Canonical source: dsh-suite/ui/workbench-ui.js.
4
+ * Vendored into each plugin: no Suite or extra runtime dependency is required.
5
+ * Styles are scoped to .dshw and never replace the host chrome or theme.
6
+ */
7
+ function createWorkbenchUI(React) {
8
+ const h = React.createElement;
9
+ const { useEffect, useId, useRef } = React;
10
+ const cx = (...values) => values.filter(Boolean).join(' ');
11
+ const paths = {
12
+ book: ['M4 4h6a3 3 0 0 1 2 2v15a4 4 0 0 0-4-2H4z', 'M20 4h-6a3 3 0 0 0-2 2v15a4 4 0 0 1 4-2h4z'],
13
+ calendar: ['M5 5h14a2 2 0 0 1 2 2v13H3V7a2 2 0 0 1 2-2Z', 'M7 3v4M17 3v4M3 10h18'],
14
+ mail: ['M3 5h18v14H3z', 'm3 6 9 7 9-7'],
15
+ rss: ['M4 11a9 9 0 0 1 9 9M4 4a16 16 0 0 1 16 16', 'M4 19h.01'],
16
+ slides: ['M3 4h18v13H3z', 'M12 17v4M8 21h8'],
17
+ shield: ['m12 3 8 3v6c0 4-4 7-8 9-4-2-8-5-8-9V6z', 'm8 12 3 3 5-6'],
18
+ layers: ['M5 3h16v16H5z', 'M2 7v15h15'],
19
+ play: ['m9 6 9 6-9 6Z'],
20
+ video: ['M3 5h12v14H3z', 'm15 10 6-4v12l-6-4'],
21
+ search: ['M10.5 18a7.5 7.5 0 1 0 0-15 7.5 7.5 0 0 0 0 15Z', 'm16 16 5 5'],
22
+ plus: ['M12 5v14M5 12h14'],
23
+ refresh: ['M20 7a9 9 0 1 0 1 8', 'M20 2v5h-5'],
24
+ settings: ['m9 3-.7 2.4-2 .9L4 5.8 2.5 8.4l1.7 1.8v2.3L2.5 14 4 17l2.5-.4 1.9 1L9 20h3l.8-2.4 2-1 2.5.4 1.5-2.7-1.7-1.9v-2.2l1.7-1.8-1.5-2.6-2.5.4-2-1L12 3Z', 'M14 11.5a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0Z'],
25
+ close: ['m6 6 12 12M18 6 6 18'],
26
+ left: ['m14 5-7 7 7 7'],
27
+ right: ['m10 5 7 7-7 7'],
28
+ down: ['m5 9 7 7 7-7'],
29
+ filter: ['M4 5h16M7 12h10M10 19h4'],
30
+ download: ['M12 3v12m-5-5 5 5 5-5', 'M4 16v5h16v-5'],
31
+ upload: ['M12 16V4m-5 5 5-5 5 5', 'M4 16v5h16v-5'],
32
+ copy: ['M8 8h13v13H8z', 'M16 8V3H3v13h5'],
33
+ external: ['M14 3h7v7m0-7L10 14', 'M10 3H3v18h18v-7'],
34
+ file: ['M4 3h10l6 6v12H4z', 'M14 3v6h6M8 13h8M8 17h6'],
35
+ folder: ['M3 5h7l2 3h9v12H3z'],
36
+ edit: ['m15 4 5 5-10 10-6 1 1-6Z', 'm13 6 5 5'],
37
+ trash: ['M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7'],
38
+ more: ['M5 12h.01M12 12h.01M19 12h.01'],
39
+ info: ['M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20Z', 'M12 11v6M12 7h.01'],
40
+ check: ['m5 12 4 4L19 6'],
41
+ quote: ['M4 12h6v7H3v-7c0-4 2-6 5-7M15 12h6v7h-7v-7c0-4 2-6 5-7'],
42
+ star: ['m12 3 2.8 5.7 6.2.9-4.5 4.4 1.1 6.2-5.6-3-5.6 3 1.1-6.2L3 9.6l6.2-.9Z'],
43
+ reply: ['m9 5-7 7 7 7v-5h6c3 0 5 2 6 5 0-8-4-11-12-11Z'],
44
+ link: ['m10 13 4-4M8 16l-2 2a4 4 0 0 1-6-6l4-4a4 4 0 0 1 6 0', 'm14 8 2-2a4 4 0 0 1 6 6l-4 4a4 4 0 0 1-6 0'],
77
45
  };
46
+ function Icon({ name = 'file', size = 20, ...props }) {
47
+ return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.75, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, focusable: false, ...props },
48
+ (paths[name] || paths.file).map((d, index) => h('path', { key: index, d })));
49
+ }
50
+ function Button({ children, icon, variant, className, ...props }) {
51
+ return h('button', { type: 'button', ...props, className: cx('w-button', variant && 'w-' + variant, className) }, icon ? h(Icon, { name: icon, size: 18 }) : null, children);
52
+ }
53
+ function IconButton({ label, icon, ...props }) {
54
+ return h(Button, { ...props, icon, className: cx('w-icon-button', props.className), 'aria-label': label, title: label });
55
+ }
56
+ function Page({ title, subtitle, actions, children, workbench = false, className, rootRef, ...props }) {
57
+ return h('section', { ...props, ref: rootRef, className: cx('dshw', 'w-page', className), 'data-main': workbench ? 'true' : 'false' },
58
+ h('style', null, styles),
59
+ h('header', { className: 'w-page-header' }, h('div', { className: 'w-heading' }, h('h1', null, title), subtitle ? h('p', { className: 'w-subtitle' }, subtitle) : null), actions ? h('div', { className: 'w-header-actions' }, actions) : null),
60
+ h('div', { className: 'w-body' }, children));
61
+ }
62
+ function Tabs({ items, value, onChange, label, children }) {
63
+ const id = useId();
64
+ const active = items.some(item => item.id === value) ? value : items[0]?.id;
65
+ function keys(event, index) {
66
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
67
+ event.preventDefault();
68
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? items.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : -1) + items.length) % items.length;
69
+ const node = event.currentTarget.parentElement?.querySelectorAll('[role=tab]')[next];
70
+ if (node) { onChange(items[next].id); node.focus(); }
71
+ }
72
+ return h('div', { className: 'w-tabs-layout' },
73
+ h('div', { className: 'w-tabs', role: 'tablist', 'aria-label': label }, items.map((item, index) => h('button', {
74
+ type: 'button', role: 'tab', key: item.id, id: id + '-' + item.id, 'aria-controls': id + '-panel', 'aria-selected': active === item.id, tabIndex: active === item.id ? 0 : -1,
75
+ onClick: () => onChange(item.id), onKeyDown: event => keys(event, index),
76
+ }, item.label, item.count !== undefined ? h('span', { className: 'w-count' }, item.count) : null))),
77
+ h('div', { className: 'w-tab-panel', id: id + '-panel', role: 'tabpanel', 'aria-labelledby': id + '-' + active }, children));
78
+ }
79
+ function Status({ children, tone = 'info', className }) {
80
+ if (!children) return null;
81
+ return h('div', { className: cx('w-status', 'w-status-' + tone, className), role: tone === 'error' ? 'alert' : 'status', 'aria-live': tone === 'error' ? 'assertive' : 'polite' }, h(Icon, { name: tone === 'success' ? 'check' : 'info', size: 18 }), h('div', null, children));
82
+ }
83
+ function Empty({ title, children, action, icon = 'file' }) {
84
+ return h('div', { className: 'w-empty' }, h(Icon, { name: icon, size: 32 }), h('h2', null, title), children ? h('div', { className: 'w-muted' }, children) : null, action ? h('div', { className: 'w-toolbar' }, action) : null);
85
+ }
86
+ function Split({ list, detail, selected, onBack, backLabel, className, listWidth = 360 }) {
87
+ const ref = useRef(null);
88
+ useEffect(() => {
89
+ if (!selected || !ref.current || ref.current.clientWidth > 760) return;
90
+ const heading = ref.current.querySelector('.w-detail h2');
91
+ if (heading) { heading.tabIndex = -1; heading.focus({ preventScroll: true }); }
92
+ }, [selected]);
93
+ return h('div', { ref, className: cx('w-split', className), 'data-selected': selected ? 'true' : 'false', style: { '--w-list-width': listWidth + 'px' } },
94
+ h('div', { className: 'w-master' }, list),
95
+ h('div', { className: 'w-detail' }, selected ? h(Button, { className: 'w-back', icon: 'left', variant: 'ghost', onClick: onBack }, backLabel) : null, detail));
96
+ }
97
+ function Row({ title, meta, description, active, onClick, children, status, className, disabled }) {
98
+ return h('div', { className: cx('w-row', active && 'w-selected', className) },
99
+ children ? h('div', { className: 'w-row-select' }, children) : null,
100
+ h('button', { type: 'button', className: 'w-row-button', onClick, disabled, 'aria-pressed': !!active },
101
+ h('span', { className: 'w-row-head' }, h('strong', null, title), status ? h('span', { className: 'w-tag' }, status) : null),
102
+ meta ? h('span', { className: 'w-row-meta' }, meta) : null,
103
+ description ? h('span', { className: 'w-row-description' }, description) : null));
104
+ }
105
+ function Search({ label, value, onChange, ...props }) {
106
+ const id = useId();
107
+ return h('div', { className: 'w-search' }, h(Icon, { name: 'search', size: 18 }), h('input', { type: 'search', id, 'aria-label': label, placeholder: label, value, onChange, ...props }));
108
+ }
109
+ function Switch({ label, checked, onChange, disabled }) {
110
+ return h('label', { className: 'w-switch-label' }, h('span', null, label), h('input', { type: 'checkbox', role: 'switch', checked, disabled, onChange, 'aria-label': label }), h('span', { className: 'w-switch-track', 'aria-hidden': true }));
111
+ }
112
+ function Dialog({ title, children, onClose, closeLabel, className, busy = false }) {
113
+ const id = useId(), panel = useRef(null);
114
+ useEffect(() => {
115
+ const previous = document.activeElement;
116
+ panel.current?.querySelector('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex="0"]')?.focus();
117
+ return () => { if (previous?.isConnected) previous.focus({ preventScroll: true }); };
118
+ }, []);
119
+ function keydown(event) {
120
+ if (event.key === 'Escape' && !event.isComposing) { event.preventDefault(); event.stopPropagation(); if (!busy) onClose(); return; }
121
+ if (event.key !== 'Tab') return;
122
+ const controls = [...panel.current.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter(node => node.getClientRects().length);
123
+ const first = controls[0], last = controls.at(-1);
124
+ if (!controls.length) { event.preventDefault(); panel.current.focus(); }
125
+ else if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
126
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
127
+ }
128
+ return h('div', { className: 'w-overlay', onClick: event => { if (!busy && event.target === event.currentTarget) onClose(); } },
129
+ h('section', { ref: panel, className: cx('w-dialog', className), role: 'dialog', 'aria-modal': true, 'aria-labelledby': id, tabIndex: -1, onKeyDown: keydown },
130
+ h('header', { className: 'w-dialog-header' }, h('h2', { id }, title), h(IconButton, { icon: 'close', label: closeLabel, disabled: busy, onClick: onClose })), h('div', { className: 'w-dialog-body' }, children)));
131
+ }
132
+ function register(ctx, { id, label, icon, component, inject, order = 50 }) {
133
+ // The two slots are optional. Existing settings and manual tools still load
134
+ // in hosts without a workbench, while RC.3 owns navigation/pinning itself.
135
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: id, inject: () => ({ ...(inject?.() || {}), workbench: true }) }, component));
136
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({ name: 'sidebar.panellist', id, order, label }, function WorkbenchIcon({ size }) { return h(Icon, { name: icon, size }); }));
137
+ }
138
+ const styles = `
139
+ .dshw{--w-bg:var(--dsw-alias-bg-layer-1,#fff);--w-soft:var(--dsw-alias-bg-layer-2,#f7f8fa);--w-text:var(--dsw-alias-label-primary,#18202c);--w-muted:var(--dsw-alias-label-secondary,#667085);--w-border:var(--dsw-alias-border-l3,#e7e9ef);--w-accent:var(--dsh-plugin-workbench-accent,#4f6bdb);--w-selected:color-mix(in srgb,var(--w-accent) 10%,var(--w-bg));--w-primary:var(--w-text);--w-on-primary:var(--w-bg);container-type:inline-size;container-name:dsh-workbench;color:var(--w-text);background:var(--w-bg);font:14px/1.65 var(--dsh-font-family-content,system-ui,-apple-system,"Segoe UI","Microsoft YaHei",sans-serif);min-width:0;max-width:100%;box-sizing:border-box;text-align:start;color-scheme:inherit}
140
+ .dshw *,.dshw *:before,.dshw *:after{box-sizing:border-box}.dshw h1,.dshw h2,.dshw h3,.dshw h4,.dshw p{margin:0}.dshw h1{font-size:30px;line-height:1.25;letter-spacing:-.025em;font-weight:650}.dshw h2{font-size:24px;line-height:1.35;font-weight:650;letter-spacing:-.015em;overflow-wrap:anywhere}.dshw h3,.dshw h4{font-size:16px;line-height:1.4;font-weight:600}.dshw a{color:var(--w-accent);text-underline-offset:3px;overflow-wrap:anywhere}.dshw button,.dshw input,.dshw select,.dshw textarea{font:inherit;color:inherit;max-width:100%}.dshw input:not([type=checkbox]):not([type=radio]):not([type=file]),.dshw select,.dshw textarea{background:var(--w-bg);border:1px solid var(--w-border);border-radius:8px;padding:8px 11px;min-width:0;line-height:1.5}.dshw input:not([type=checkbox]):not([type=radio]):not([type=file]),.dshw select{min-height:38px}.dshw textarea{resize:vertical}.dshw input[type=checkbox],.dshw input[type=radio]{width:16px;height:16px;flex-shrink:0;accent-color:var(--w-accent)}.dshw :focus-visible{outline:2px solid var(--w-accent);outline-offset:3px}.dshw button:disabled,.dshw input:disabled,.dshw select:disabled,.dshw textarea:disabled{opacity:.5;cursor:not-allowed}.dshw label{font-size:13px}.dshw fieldset{min-width:0;border:1px solid var(--w-border);border-radius:8px}.dshw summary{cursor:pointer;font-weight:550;list-style:none;display:flex;align-items:center;gap:8px}.dshw summary::-webkit-details-marker{display:none}.dshw summary:after{content:'';display:block;margin-inline-start:auto;width:7px;height:7px;border-inline-end:1.75px solid currentColor;border-bottom:1.75px solid currentColor;transform:rotate(45deg);flex-shrink:0}.dshw details[open]>summary:after{transform:rotate(225deg)}.dshw details>summary+*{margin-top:12px}.dshw pre{white-space:pre-wrap;overflow-wrap:anywhere;font:12px/1.7 ui-monospace,SFMono-Regular,Consolas,monospace;max-width:100%;background:var(--w-soft);border-radius:6px;padding:14px}.dshw img,.dshw video,.dshw iframe{max-width:100%}
141
+ .w-page{display:flex;flex-direction:column;position:relative;padding:0;min-height:540px;gap:0}.w-page[data-main=true]{height:100%;min-height:0;padding:calc(24px + var(--dsh-frame-top-clearance,0px)) 28px 0 max(28px,var(--dsh-frame-leading-clearance,0px));overflow:auto}.w-page-header{display:flex;justify-content:space-between;gap:24px;align-items:flex-start;padding-bottom:22px;flex-shrink:0}.w-heading{min-width:0}.w-subtitle{margin-top:8px!important;font-size:14px;color:var(--w-muted);line-height:1.6}.w-header-actions,.w-toolbar,.w-actions{display:flex;align-items:center;flex-wrap:wrap;gap:8px;min-width:0}.w-header-actions{justify-content:flex-end}.w-body,.w-tabs-layout{display:flex;flex-direction:column;flex:1;min-height:0;min-width:0}.w-body{overflow:auto}.w-tab-panel{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:auto}.w-tabs{display:flex;align-items:stretch;gap:20px;border-bottom:1px solid var(--w-border);flex-shrink:0;overflow-x:auto;scrollbar-width:thin}.dshw .w-tabs>button{border:0;border-bottom:2px solid transparent;background:transparent;padding:11px 8px 13px;white-space:nowrap;font-size:14px;font-weight:550;cursor:pointer;color:var(--w-muted);display:flex;align-items:center;gap:7px}.dshw .w-tabs>button[aria-selected=true]{border-bottom-color:var(--w-accent);color:var(--w-accent)}.w-count,.w-tag{font-size:12px;line-height:1.5;display:inline-flex;align-items:center;flex-shrink:0;background:var(--w-soft);border-radius:5px;padding:1px 6px;color:var(--w-muted)}.w-tabs [aria-selected=true] .w-count,.w-selected .w-tag{color:var(--w-accent);background:var(--w-selected)}
142
+ .dshw .w-button{display:inline-flex;justify-content:center;align-items:center;gap:7px;background:var(--w-bg);border:1px solid var(--w-border);border-radius:8px;padding:8px 12px;min-height:36px;line-height:1.4;font-size:14px;font-weight:500;cursor:pointer;text-decoration:none;white-space:normal}.dshw .w-button:not(:disabled):hover{background:var(--w-soft)}.dshw .w-primary{background:var(--w-primary);border-color:var(--w-primary);color:var(--w-on-primary)}.dshw .w-primary:not(:disabled):hover{background:var(--w-primary);opacity:.9}.dshw .w-ghost{background:transparent;border-color:transparent}.dshw .w-danger{color:var(--dsw-alias-state-error-primary,#b43c3c)}.dshw .w-icon-button{width:36px;min-width:36px;padding:8px}.dshw .w-button svg{flex-shrink:0}.w-muted{color:var(--w-muted);font-size:12px;line-height:1.6}.w-section{padding:24px 0;border-bottom:1px solid var(--w-border);min-width:0}.w-section>h3{margin-bottom:12px}.w-section>p+p{margin-top:8px}.w-fields{display:grid;gap:16px;min-width:0}.w-field{display:grid;gap:6px;min-width:0}.w-field>input,.w-field>select,.w-field>textarea{width:100%}.w-status{display:flex;align-items:flex-start;gap:8px;padding:11px 13px;margin:12px 0;border:1px solid var(--w-border);border-radius:8px;background:var(--w-soft);font-size:13px;overflow-wrap:anywhere;flex-shrink:0}.w-status>svg{flex-shrink:0;margin-top:2px}.w-status-error{color:var(--dsw-alias-state-error-primary,#ad3636)}.w-status-success{color:var(--dsw-alias-state-success-primary,#24794a)}.w-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;gap:14px;max-width:580px;padding:48px 24px;margin:auto;min-height:280px;overflow-wrap:anywhere}.w-empty>svg{color:var(--w-muted)}.w-empty h2{font-size:20px}.w-empty .w-muted{font-size:14px}.w-empty .w-toolbar{justify-content:center}
143
+ .w-split{display:grid;grid-template-columns:minmax(240px,var(--w-list-width)) minmax(0,1fr);min-height:460px;flex:1;min-width:0}.w-master{min-width:0;border-inline-end:1px solid var(--w-border);overflow:auto;padding-bottom:24px}.w-detail{min-width:0;padding:26px 28px;overflow:auto;overflow-wrap:anywhere;display:flex;flex-direction:column}.w-master-toolbar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:20px 16px}.w-search{display:flex;align-items:center;gap:8px;border:1px solid var(--w-border);border-radius:8px;padding:0 10px;min-width:0;flex:1;background:var(--w-bg)}.w-search>svg{color:var(--w-muted);flex-shrink:0}.dshw .w-search>input{border:0!important;background:transparent!important;padding:8px 0!important;width:100%;outline-offset:0}.w-row{display:flex;gap:0;min-width:0;position:relative;border-bottom:1px solid var(--w-border);border-inline-start:3px solid transparent}.w-row-select{display:flex;align-items:flex-start;padding:21px 0 0 14px}.dshw .w-row-button{display:flex;flex-direction:column;align-items:stretch;gap:7px;text-align:start;width:100%;padding:18px 18px 18px 16px;border:0;background:transparent;color:inherit;min-width:0;cursor:pointer;line-height:1.5}.dshw .w-row-button:hover{background:var(--w-soft)}.w-row-head{display:flex;align-items:flex-start;gap:10px;justify-content:space-between;min-width:0}.w-row-head>strong{font-size:14px;line-height:1.5;font-weight:600;overflow-wrap:anywhere}.w-row-meta,.w-row-description{color:var(--w-muted);font-size:12px;line-height:1.6;overflow-wrap:anywhere}.w-row-description{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.w-selected{background:var(--w-selected);border-inline-start-color:var(--w-accent)}.w-back{display:none!important}.w-detail-title{margin-bottom:12px!important}.w-detail-meta{color:var(--w-muted);font-size:13px;display:flex;align-items:center;gap:8px;flex-wrap:wrap}.w-detail-footer{padding:24px 0;display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:auto;border-top:1px solid var(--w-border)}.w-detail-footer .w-muted{flex:1;min-width:160px}.w-definition{display:grid;grid-template-columns:minmax(80px,120px) minmax(0,1fr);gap:8px 16px;font-size:14px;margin:20px 0}.w-definition dt{color:var(--w-muted)}.w-definition dd{margin:0;min-width:0;overflow-wrap:anywhere}
144
+ .w-switch-label{display:inline-flex;align-items:center;gap:8px;font-size:13px;position:relative;cursor:pointer}.w-switch-label>input{position:absolute;opacity:0;inset-inline-end:0;width:36px!important;height:22px!important;margin:0;cursor:pointer}.w-switch-track{width:36px;height:22px;border-radius:12px;display:block;background:var(--w-border);border:1px solid var(--w-border);pointer-events:none;padding:2px;transition:background .15s}.w-switch-track:before{content:'';display:block;width:16px;height:16px;border-radius:50%;background:#fff;box-shadow:0 1px 2px #0002;transition:transform .15s}.w-switch-label>input:checked+.w-switch-track{background:var(--w-accent);border-color:var(--w-accent)}.w-switch-label>input:checked+.w-switch-track:before{transform:translateX(14px)}.w-switch-label>input:focus-visible+.w-switch-track{outline:2px solid var(--w-accent);outline-offset:3px}.w-switch-label:has(>input:disabled){opacity:.5;cursor:not-allowed}
145
+ .w-overlay{position:fixed;inset:0;background:#0005;display:flex;justify-content:flex-end;z-index:1000;padding:12px;overflow:auto}.w-dialog{width:min(620px,100%);max-height:100%;display:flex;flex-direction:column;min-height:0;background:var(--w-bg);color:var(--w-text);border:1px solid var(--w-border);border-radius:12px;box-shadow:0 18px 70px #0003}.w-dialog-header{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:20px 24px;border-bottom:1px solid var(--w-border);flex-shrink:0}.w-dialog-header>h2{font-size:20px}.w-dialog-body{overflow:auto;padding:20px 24px;min-height:0}.w-editor-grid{display:grid;grid-template-columns:210px minmax(0,1fr) 300px;min-height:500px;flex:1}.w-editor-list{padding:20px 12px;border-inline-end:1px solid var(--w-border);min-width:0}.w-editor-canvas{background:var(--w-soft);padding:20px;min-width:0;display:flex;flex-direction:column;gap:14px}.w-editor-inspector{padding:24px;border-inline-start:1px solid var(--w-border);min-width:0;overflow:auto}.w-editor-inspector h3{margin-bottom:18px}.w-preview-empty{display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center;gap:12px;aspect-ratio:16/9;min-height:180px;background:var(--w-soft);border:1px solid var(--w-border);border-radius:8px;padding:24px;color:var(--w-muted)}.w-content-pad{padding:24px 0}.w-stack{display:flex;flex-direction:column;gap:16px;min-width:0}.w-scroll-x{overflow:auto;max-width:100%}
146
+ @container dsh-workbench (max-width:1000px){.w-editor-grid{grid-template-columns:160px minmax(0,1fr)}.w-editor-inspector{grid-column:1/-1;border-inline-start:0;border-top:1px solid var(--w-border)}.w-header-actions{max-width:60%}.w-split{grid-template-columns:minmax(240px,32%) minmax(0,1fr)}}
147
+ @container dsh-workbench (max-width:760px){.w-page-header{gap:14px;flex-wrap:wrap;padding-bottom:18px}.w-heading{flex:1;min-width:170px}.dshw h1{font-size:24px}.w-header-actions{max-width:100%;justify-content:flex-start}.w-subtitle{font-size:13px}.w-tabs{gap:12px}.dshw .w-tabs>button{padding:10px 4px 12px}.w-split{display:block;min-height:360px}.w-split[data-selected=false]>.w-detail{display:none}.w-split[data-selected=true]>.w-master{display:none}.w-master{border-inline-end:0}.w-detail{padding:20px 0}.w-back{display:inline-flex!important;align-self:flex-start;margin:0 0 16px!important}.w-detail h2{font-size:22px}.w-master-toolbar{padding:16px 0}.dshw .w-row-button{padding:16px 10px}.w-detail-footer{position:static}.w-detail-footer .w-muted{flex-basis:100%}.w-editor-grid{display:flex;flex-direction:column}.w-editor-list{border-inline-end:0;border-bottom:1px solid var(--w-border);padding:16px 0}.w-editor-canvas{padding:16px 0;background:var(--w-bg)}.w-editor-inspector{padding:20px 0}.w-dialog-header,.w-dialog-body{padding:16px}.w-button{min-height:40px}.w-definition{grid-template-columns:80px minmax(0,1fr)}}
148
+ @media(max-width:700px){.w-page[data-main=true]{padding:calc(16px + var(--dsh-frame-top-clearance,0px)) 16px 0 max(16px,var(--dsh-frame-leading-clearance,0px))}.w-overlay{padding:8px}.w-dialog{width:100%}}
149
+ @media(prefers-reduced-motion:reduce){.dshw *,.dshw *:before{scroll-behavior:auto!important;transition:none!important;animation:none!important}}
150
+ `;
151
+ return { Icon, Button, IconButton, Page, Tabs, Status, Empty, Split, Row, Search, Switch, Dialog, register, styles };
78
152
  }
79
- // ---- end first-run guide ----
80
153
 
81
- const { useState, useEffect, useRef, useMemo } = React;
82
- const h = React.createElement;
154
+ // Editable browser entry. Build with node scripts/build-client.mjs.
155
+ // Browser source, distributed directly. tsc deliberately does not rewrite this file.
156
+ window.__ModuleLoader__.load({ id: 'dsh-ppt', factory: require => {
157
+ const React = require('react');
158
+ const W = createWorkbenchUI(React);
159
+ function pptText(zh, en) { return languageOf() === 'en' ? en : zh; }
83
160
 
84
- // Interface language follows DSH; user content and stored records keep their original text.
85
- let localeService;
86
- const EN = Object.freeze({
87
- "标题": "Title",
88
- "副标题": "Subtitle",
89
- "眉题": "Kicker",
90
- "正文": "Body text",
91
- "要点(每行一条)": "Bullets (one per line)",
92
- "演讲备注": "Speaker notes",
93
- "无法读取服务响应,请检查插件是否加载": "Could not read the server response. Check that the plugin is loaded.",
94
- "操作未完成": "The operation did not complete.",
95
- "正在处理,请稍候…": "Working, please wait…",
96
- "操作失败": "Operation failed.",
97
- "已定位到": "Focused ",
98
- ",在字段中修改后保存。": ". Edit this field, then save.",
99
- "点击预览里的文字,或在下方修改字段。": "Click text in the preview, or edit the fields below.",
100
- "当前页已被删除,输入仍保留,请复制需要的内容后取消修改。": "This slide was deleted. Your input is preserved; copy anything you need before cancelling your edits.",
101
- "已载入最新版本并保留你的修改,请核对后再保存。": "Latest version loaded with your edits preserved. Review before saving.",
102
- "内容没有变化。": "No changes to save.",
103
- "已保存,HTML、PPTX 和工程文件已同步更新。": "Saved. HTML, PPTX and project files were updated together.",
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.",
109
- "已撤销上次修改。": "Last change undone.",
110
- "当前 PPTX 已生成逐页图片,请查看画面。": "Slide images were rendered from the current PPTX. Review each slide.",
111
- "正在渲染最终 PPTX,较大文件可能需要几分钟…": "Rendering the final PPTX. Large files may take a few minutes…",
112
- "已请求下载,请查看浏览器的下载列表。": "Download requested. Check your browser’s downloads.",
113
- "请选择 5 MiB 以内的 PNG 或 JPEG 图片。": "Choose a PNG or JPEG image up to 5 MiB.",
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.",
120
- "演示文稿编辑": "Presentation editor",
121
- "修改本插件生成的成品,保存时同步更新 HTML、可编辑 PPTX 和工程文件。": "Edit presentations generated by this plugin. Saving updates the HTML, editable PPTX and project file together.",
122
- "载入最新版本,保留我的输入": "Load latest and keep my input",
123
- "刷新项目": "Refresh projects",
124
- "还没有可以编辑的项目": "No editable projects yet",
125
- "先在对话中让助手生成演示文稿。已有项目可以让助手调用 ppt_check 检查一次,它会出现在这里。": "Ask the assistant to generate a presentation in chat. For an existing project, ask it to run ppt_check; the project will appear here.",
126
- "示例:请把这份材料制作成可直接交付的演示文稿,生成 HTML、PPTX 和工程文件。": "Example: Turn this material into a presentation ready to deliver, including HTML, PPTX and project files.",
127
- "返回项目": "Back to projects",
128
- " 页 · 修订 ": " slides · Revision ",
129
- "页面": "Slides",
130
- "未命名页": "Untitled slide",
131
- "上移": "Move up",
132
- "下移": "Move down",
133
- "HTML 预览": "HTML preview",
134
- "最终 PPTX 预览": "Final PPTX preview",
135
- "渲染当前 PPTX": "Render current PPTX",
136
- "演示文稿 HTML 预览": "Presentation HTML preview",
137
- "此项目尚无 HTML,请保存一次生成预览。": "This project has no HTML yet. Save to generate a preview.",
138
- "最终 PPTX 第 ": "Final PPTX slide ",
139
- " 页渲染结果": " rendered image",
140
- "正在载入当前页渲染…": "Loading the rendered slide…",
141
- "这是 HTML 放映预览。最终 PPTX 的字体和排版请用上方渲染检查。点击文字可定位编辑字段。": "This is the HTML playback preview. Use the render controls above to check fonts and layout in the final PPTX. Click text to focus its editing field.",
142
- "这是当前 PPTX 文件的实际渲染图片,仍需检查每页画面;PowerPoint / WPS 可能因字体环境而不同。": "This image is rendered from the current PPTX. Review every slide; PowerPoint / WPS may display it differently depending on installed fonts.",
143
- "渲染引擎报告缺失字体:": "The renderer reported missing fonts: ",
144
- "。请替换为目标电脑可用字体后重新渲染。": ". Choose fonts available on the target computer and render again.",
145
- "编辑第 ": "Edit slide ",
146
- " 页": "",
147
- "有未保存修改,请先保存或取消,再切换页面。": "You have unsaved edits. Save or cancel before switching slides.",
148
- "这些字段也被修改过,请比较后决定是否保存:": "These fields were changed elsewhere. Compare them before saving:",
149
- "最新版本:": "Latest version: ",
150
- "你的修改:": "Your edits: ",
151
- "替换图片(PNG / JPEG)": "Replace image (PNG / JPEG)",
152
- "添加图片(会改为图文布局)": "Add image (changes to an image-and-text layout)",
153
- "当前图片": "Current image",
154
- "已选择:": "Selected: ",
155
- "图片说明": "Image description",
156
- "图片适应方式": "Image fit",
157
- "完整显示": "Show complete image",
158
- "填满并裁切": "Fill and crop",
159
- "保存此页": "Save slide",
160
- "取消修改": "Cancel edits",
161
- "撤销上次修改": "Undo last change",
162
- "质量提醒(": "Quality findings (",
163
- "第 ": "Slide ",
164
- " 页:": ": ",
165
- "下载最新 PPTX": "Download latest PPTX",
166
- "下载成品包 ZIP": "Download delivery ZIP",
167
- "成品包包含 PPTX、HTML 和工程文件。请先保存修改,再下载最新版本。": "The bundle includes the PPTX, HTML and project file. Save your edits before downloading the latest version.",
168
- "下载 HTML": "Download HTML",
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",
178
- "演示文稿": "Presentations"
179
- });
180
- function languageOf(locale = localeService) {
181
- try { return String(locale?.getSnapshot?.().active || '').startsWith('en') ? 'en' : 'zh'; } catch { return 'zh'; }
182
- }
183
- function t(zh) { return languageOf() === 'en' ? (EN[zh] ?? zh) : zh; }
184
- function englishError(message, status) {
185
- if (status === 401) return 'Your session has expired. Reopen DSH and try again.';
186
- if (status === 404) return 'The presentation workbench is unavailable. Check that the plugin is loaded and restart DSH.';
187
- if (status === 409) return 'The project changed. Load the latest version and review your edits before saving.';
188
- return /[\u3400-\u9fff]/.test(message || '') ? 'The operation failed. Check the project files and DSH logs, then retry.' : message;
189
- }
190
- function useLanguage(locale) {
191
- const [, rerender] = useState(0);
192
- useEffect(() => { const update = () => rerender(n => n + 1); update(); return locale?.subscribe?.(update); }, [locale]);
161
+ function PptPages({ project, selected, busy, imagePending, onChoose, onDuplicate, dirty, dataDirty }) {
162
+ return h('aside', { className: 'ppt-page-rail', 'aria-label': pptText('幻灯片目录', 'Slide outline') },
163
+ h('h3', null, pptText('幻灯片', 'Slides')),
164
+ h('div', { className: 'ppt-page-buttons' }, project.slides.map((row, index) => h('button', {
165
+ type: 'button', key: row.id, 'aria-current': row.id === selected ? 'true' : undefined, disabled: busy || imagePending, onClick: () => onChoose(row),
166
+ }, h('span', { className: 'ppt-page-number' }, String(index + 1).padStart(2, '0')), h('span', null, row.title || t('未命名页'))))),
167
+ h(W.Button, { icon: 'copy', className: 'ppt-duplicate', disabled: busy || dirty || imagePending || dataDirty || project.slides.length >= 120, onClick: onDuplicate }, t('复制本页')));
193
168
  }
194
169
 
195
- const ROUTE = 'api/dsh-ppt/workbench';
196
- const fields = [['title', '标题'], ['subtitle', '副标题'], ['kicker', '眉题'], ['text', '正文'], ['bullets', '要点(每行一条)'], ['notes', '演讲备注']];
197
- const css = `
170
+ const PPT_WORKBENCH_CSS = `
171
+ .ppt-workbench.pptw{--fg:var(--w-text);--fg-muted:var(--w-muted);--bg:var(--w-bg);--bg-surface:var(--w-bg);--border:var(--w-border);max-width:none;margin:0;padding:0}.ppt-workbench.pptw[data-main=true]{padding:calc(24px + var(--dsh-frame-top-clearance,0px)) 28px 0 max(28px,var(--dsh-frame-leading-clearance,0px))}.ppt-workbench .ppt-editor{--ppt-inspector:320px;display:grid;grid-template-columns:190px minmax(0,1fr) var(--ppt-inspector);flex:1;min-height:520px}.ppt-workbench .ppt-editor[data-view=visual],.ppt-workbench .ppt-editor[data-view=rehearsal],.ppt-workbench .ppt-editor[data-view=data]{--ppt-inspector:400px}.ppt-workbench .ppt-page-rail{padding:24px 14px 24px 0;border-inline-end:1px solid var(--w-border);min-width:0;display:flex;flex-direction:column;gap:18px}.ppt-workbench .ppt-page-rail h3{margin:0;font-size:16px}.ppt-workbench .ppt-page-buttons{display:flex;flex-direction:column;gap:4px;max-height:calc(100dvh - 340px);overflow:auto;min-width:0}.ppt-workbench .ppt-page-buttons>button{border:0;border-inline-start:3px solid transparent;border-radius:6px;padding:12px 8px;display:flex;align-items:flex-start;gap:10px;background:transparent;min-width:0;font-size:13px;line-height:1.6;text-align:start;overflow-wrap:anywhere}.ppt-workbench .ppt-page-buttons>button[aria-current=true]{border-inline-start-color:var(--w-accent);background:var(--w-selected);color:var(--w-text)}.ppt-workbench .ppt-page-number{font-variant-numeric:tabular-nums;color:var(--w-muted);font-size:12px;flex-shrink:0}.ppt-workbench .ppt-duplicate{margin-top:auto;font-size:13px}.ppt-workbench .ppt-canvas-region{display:flex;flex-direction:column;gap:14px;padding:24px;background:var(--w-soft);min-width:0}.ppt-workbench .ppt-preview-tools{display:flex;align-items:center;gap:6px;flex-wrap:wrap}.ppt-workbench .ppt-preview-tools .w-button{font-size:12px;min-height:32px;padding:7px 9px}.ppt-workbench .ppt-preview-tools [aria-pressed=true]{background:var(--w-bg);border-color:var(--w-accent);color:var(--w-accent)}.ppt-workbench .ppt-preview-tools .w-icon-button{margin-inline-start:auto}.ppt-workbench .preview{width:100%;aspect-ratio:16/9;border:1px solid var(--w-border);border-radius:4px;background:var(--w-bg);box-shadow:0 6px 20px #0001;overflow:hidden;min-height:0;margin:auto 0}.ppt-workbench .preview{position:relative}.ppt-workbench .preview>.ppt-fullscreen-exit{display:none}.ppt-workbench .preview:fullscreen>.ppt-fullscreen-exit{display:inline-flex;position:absolute;inset:16px 16px auto auto;z-index:10;background:#14171c;color:#fff;border:1px solid #ffffff66}.ppt-workbench .preview:fullscreen{width:100vw;height:100vh;aspect-ratio:auto;border:0;border-radius:0;margin:0;background:#14171c;box-shadow:none}.ppt-workbench .preview:fullscreen iframe{background:#14171c}.ppt-workbench .preview .render-page{width:100%;height:100%;object-fit:contain}.ppt-workbench .ppt-preview-help{font-size:12px;color:var(--w-muted);line-height:1.7}.ppt-workbench .ppt-preview-help+details{background:transparent;border:0;border-top:1px solid var(--w-border);border-radius:0;padding:14px 0}.ppt-workbench .ppt-preview-help+details summary{font-size:12px}.ppt-workbench .ppt-inspector{padding:24px 0 24px 22px;border-inline-start:1px solid var(--w-border);min-width:0;overflow-wrap:anywhere}.ppt-workbench .ppt-inspector-panel[hidden]{display:none!important}.ppt-workbench .ppt-inspector .card{border:0;border-bottom:1px solid var(--w-border);border-radius:0;padding:0 0 20px;margin:0 0 20px;background:transparent;box-shadow:none}.ppt-workbench .ppt-inspector h3{font-size:17px;margin:0 0 18px}.ppt-workbench .ppt-inspector .card>div>label,.ppt-workbench .ppt-inspector .card>label{font-size:13px;margin:16px 0 6px;color:var(--w-muted)}.ppt-workbench .ppt-inspector input,.ppt-workbench .ppt-inspector textarea,.ppt-workbench .ppt-inspector select{font-size:14px}.ppt-workbench .ppt-inspector textarea{min-height:72px}.ppt-workbench .ppt-inspector .tools{gap:8px;margin-top:18px}.ppt-workbench .ppt-inspector .tools button{font-size:13px;min-height:34px;padding:7px 9px}.ppt-workbench .ppt-inspector .coaching-grid{grid-template-columns:1fr}.ppt-workbench .ppt-inspector .before-after,.ppt-workbench .ppt-inspector .data-before-after{grid-template-columns:1fr}.ppt-workbench .ppt-inspector .coaching{margin-top:0}.ppt-workbench .ppt-inspector .coaching p,.ppt-workbench .ppt-inspector .data-workbench p{font-size:13px;line-height:1.7}.ppt-workbench .ppt-inspector .coaching blockquote{margin:12px 0;padding-inline-start:12px}.ppt-workbench .ppt-inspector .muted{font-size:12px;color:var(--w-muted)}.ppt-workbench .ppt-inspector .data-workbench .data-controls{grid-template-columns:1fr}.ppt-workbench .ppt-structure{border-top:1px solid var(--w-border);padding-top:16px;margin-top:16px}.ppt-workbench .ppt-structure .w-button{font-size:12px}.ppt-workbench.pptw button.primary{background:var(--w-primary);color:var(--w-on-primary);border-color:var(--w-primary)}.ppt-workbench .ppt-library{max-width:1000px;padding:12px 0 24px}.ppt-workbench .ppt-library .w-row-button{padding:20px 16px;border:0;border-radius:0;background:transparent}.ppt-workbench .notice{border:1px solid var(--w-border);border-radius:8px;background:var(--w-soft);color:var(--w-text)}.ppt-workbench .notice.error{color:var(--dsw-alias-state-error-primary,#ad3636)}.ppt-workbench .ppt-data-warning{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.ppt-workbench .ppt-downloads{display:flex;flex-direction:column;gap:16px}.ppt-workbench .ppt-downloads .tools{display:flex;flex-direction:column;align-items:stretch}.ppt-workbench .ppt-downloads button{font-size:14px;min-height:38px}.ppt-workbench .ppt-image-section{border-block:1px solid var(--w-border);margin:20px 0;padding:16px 0}.ppt-workbench .ppt-image-section>summary{font-size:14px}.ppt-workbench .ppt-image-section input,.ppt-workbench .ppt-image-section select{width:100%;margin-bottom:14px}.ppt-workbench .ppt-image-section input[type=file]{font-size:12px}.ppt-workbench :focus-visible{outline:2px solid var(--w-accent);outline-offset:3px}.ppt-workbench .w-dialog{max-width:700px}.ppt-workbench .ppt-inspector .image-preview{max-height:180px;object-fit:contain;background:var(--w-soft)}
172
+ @container dsh-workbench (max-width:1100px){.ppt-workbench .ppt-editor{grid-template-columns:160px minmax(0,1fr)}.ppt-workbench .ppt-inspector{grid-column:1/-1;border-inline-start:0;border-top:1px solid var(--w-border);padding:24px 0}.ppt-workbench .ppt-inspector .coaching-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.ppt-workbench .ppt-canvas-region{padding-inline-end:0}.ppt-workbench .ppt-page-buttons{max-height:400px}}
173
+ @container dsh-workbench (max-width:760px){.ppt-workbench .ppt-editor{display:flex;flex-direction:column;min-height:0}.ppt-workbench .ppt-page-rail{border-inline-end:0;border-bottom:1px solid var(--w-border);padding:16px 0}.ppt-workbench .ppt-page-buttons{display:flex;flex-direction:row;max-height:150px;overflow:auto;gap:8px}.ppt-workbench .ppt-page-buttons>button{min-width:150px;max-width:200px;flex-shrink:0}.ppt-workbench .ppt-duplicate{align-self:flex-start}.ppt-workbench .ppt-canvas-region{padding:18px 0;background:var(--w-bg)}.ppt-workbench .preview{margin:0;min-height:0}.ppt-workbench .ppt-preview-tools .w-icon-button{margin-inline-start:0}.ppt-workbench .ppt-inspector .coaching-grid{grid-template-columns:1fr}.ppt-workbench .ppt-preview-tools .w-button{font-size:12px}.ppt-workbench .ppt-inspector{padding:20px 0}}
174
+ @media(max-width:700px){.ppt-workbench.pptw[data-main=true]{padding:calc(16px + var(--dsh-frame-top-clearance,0px)) 16px 0 max(16px,var(--dsh-frame-leading-clearance,0px))}}
175
+ `;
176
+
177
+ const { useState, useEffect, useRef, useMemo } = React;
178
+ const h = React.createElement;
179
+ // Interface language follows DSH; user content and stored records keep their original text.
180
+ let localeService;
181
+ const EN = Object.freeze({
182
+ "标题": "Title",
183
+ "副标题": "Subtitle",
184
+ "眉题": "Kicker",
185
+ "正文": "Body text",
186
+ "要点(每行一条)": "Bullets (one per line)",
187
+ "演讲备注": "Speaker notes",
188
+ "无法读取服务响应,请检查插件是否加载": "Could not read the server response. Check that the plugin is loaded.",
189
+ "操作未完成": "The operation did not complete.",
190
+ "正在处理,请稍候…": "Working, please wait…",
191
+ "操作失败": "Operation failed.",
192
+ "已定位到": "Focused ",
193
+ ",在字段中修改后保存。": ". Edit this field, then save.",
194
+ "点击预览里的文字,或在下方修改字段。": "Click text in the preview, or edit the fields below.",
195
+ "当前页已被删除,输入仍保留,请复制需要的内容后取消修改。": "This slide was deleted. Your input is preserved; copy anything you need before cancelling your edits.",
196
+ "已载入最新版本并保留你的修改,请核对后再保存。": "Latest version loaded with your edits preserved. Review before saving.",
197
+ "内容没有变化。": "No changes to save.",
198
+ "已保存,HTML、PPTX 和工程文件已同步更新。": "Saved. HTML, PPTX and project files were updated together.",
199
+ "页面顺序已更新,可撤销。": "Slides reordered. You can undo this change.",
200
+ "复制本页": "Duplicate slide",
201
+ "删除本页": "Delete slide",
202
+ "页面已复制,图片、图表和备注一并保留,可撤销。": "Slide duplicated with its images, charts and notes. You can undo this change.",
203
+ "页面已删除,可撤销。": "Slide deleted. You can undo this change.",
204
+ "已撤销上次修改。": "Last change undone.",
205
+ "当前 PPTX 已生成逐页图片,请查看画面。": "Slide images were rendered from the current PPTX. Review each slide.",
206
+ "正在渲染最终 PPTX,较大文件可能需要几分钟…": "Rendering the final PPTX. Large files may take a few minutes…",
207
+ "已请求下载,请查看浏览器的下载列表。": "Download requested. Check your browser’s downloads.",
208
+ "请选择 5 MiB 以内的 PNG 或 JPEG 图片。": "Choose a PNG or JPEG image up to 5 MiB.",
209
+ "无法读取图片,请重试。": "Could not read the image. Try again.",
210
+ "正在读取图片,切换页面会取消本次读取。": "Reading the image. Switching slides cancels this upload.",
211
+ "图片已载入,保存后生效。": "Image loaded. Save this slide to apply it.",
212
+ "下载讲稿 Markdown": "Download speaker notes",
213
+ "另存副本": "Save a copy",
214
+ "副本已保存,原文件保留。副本从工程生成,不包含 Office 手工修改。": "Copy saved. Original files are preserved. The copy is rebuilt from the project and does not include external Office edits.",
215
+ "演示文稿编辑": "Presentation editor",
216
+ "修改本插件生成的成品,保存时同步更新 HTML、可编辑 PPTX 和工程文件。": "Edit presentations generated by this plugin. Saving updates the HTML, editable PPTX and project file together.",
217
+ "载入最新版本,保留我的输入": "Load latest and keep my input",
218
+ "刷新项目": "Refresh projects",
219
+ "还没有可以编辑的项目": "No editable projects yet",
220
+ "先在对话中让助手生成演示文稿。已有项目可以让助手调用 ppt_check 检查一次,它会出现在这里。": "Ask the assistant to generate a presentation in chat. For an existing project, ask it to run ppt_check; the project will appear here.",
221
+ "示例:请把这份材料制作成可直接交付的演示文稿,生成 HTML、PPTX 和工程文件。": "Example: Turn this material into a presentation ready to deliver, including HTML, PPTX and project files.",
222
+ "返回项目": "Back to projects",
223
+ " 页 · 修订 ": " slides · Revision ",
224
+ "页面": "Slides",
225
+ "未命名页": "Untitled slide",
226
+ "上移": "Move up",
227
+ "下移": "Move down",
228
+ "HTML 预览": "HTML preview",
229
+ "最终 PPTX 预览": "Final PPTX preview",
230
+ "渲染当前 PPTX": "Render current PPTX",
231
+ "演示文稿 HTML 预览": "Presentation HTML preview",
232
+ "此项目尚无 HTML,请保存一次生成预览。": "This project has no HTML yet. Save to generate a preview.",
233
+ "最终 PPTX 第 ": "Final PPTX slide ",
234
+ " 页渲染结果": " rendered image",
235
+ "正在载入当前页渲染…": "Loading the rendered slide…",
236
+ "这是 HTML 放映预览。最终 PPTX 的字体和排版请用上方渲染检查。点击文字可定位编辑字段。": "This is the HTML playback preview. Use the render controls above to check fonts and layout in the final PPTX. Click text to focus its editing field.",
237
+ "这是当前 PPTX 文件的实际渲染图片,仍需检查每页画面;PowerPoint / WPS 可能因字体环境而不同。": "This image is rendered from the current PPTX. Review every slide; PowerPoint / WPS may display it differently depending on installed fonts.",
238
+ "渲染引擎报告缺失字体:": "The renderer reported missing fonts: ",
239
+ "。请替换为目标电脑可用字体后重新渲染。": ". Choose fonts available on the target computer and render again.",
240
+ "编辑第 ": "Edit slide ",
241
+ " 页": "",
242
+ "有未保存修改,请先保存或取消,再切换页面。": "You have unsaved edits. Save or cancel before switching slides.",
243
+ "这些字段也被修改过,请比较后决定是否保存:": "These fields were changed elsewhere. Compare them before saving:",
244
+ "最新版本:": "Latest version: ",
245
+ "你的修改:": "Your edits: ",
246
+ "替换图片(PNG / JPEG)": "Replace image (PNG / JPEG)",
247
+ "添加图片(会改为图文布局)": "Add image (changes to an image-and-text layout)",
248
+ "当前图片": "Current image",
249
+ "已选择:": "Selected: ",
250
+ "图片说明": "Image description",
251
+ "图片适应方式": "Image fit",
252
+ "完整显示": "Show complete image",
253
+ "填满并裁切": "Fill and crop",
254
+ "保存此页": "Save slide",
255
+ "取消修改": "Cancel edits",
256
+ "撤销上次修改": "Undo last change",
257
+ "质量提醒(": "Quality findings (",
258
+ "第 ": "Slide ",
259
+ " 页:": ": ",
260
+ "下载最新 PPTX": "Download latest PPTX",
261
+ "下载成品包 ZIP": "Download delivery ZIP",
262
+ "成品包包含 PPTX、HTML 和工程文件。请先保存修改,再下载最新版本。": "The bundle includes the PPTX, HTML and project file. Save your edits before downloading the latest version.",
263
+ "下载 HTML": "Download HTML",
264
+ "备份工程": "Back up project",
265
+ "快捷键:Ctrl/⌘+S 保存 · Esc 取消或返回 · Alt+←/→ 切换页面": "Shortcuts: Ctrl/⌘+S save · Esc cancel or go back · Alt+←/→ switch slides",
266
+ "未保存": "Unsaved",
267
+ "有未保存修改,确定取消吗?": "Discard unsaved changes?",
268
+ "已取消未保存的修改。": "Unsaved changes discarded.",
269
+ "有未保存修改,离开页面会丢失。": "You have unsaved changes that will be lost.",
270
+ "重试": "Retry",
271
+ "复制示例": "Copy example",
272
+ "已复制示例": "Example copied",
273
+ "演示文稿": "Presentations"
274
+ });
275
+ function languageOf(locale = localeService) {
276
+ try {
277
+ return String(locale?.getSnapshot?.().active || '').startsWith('en') ? 'en' : 'zh';
278
+ }
279
+ catch {
280
+ return 'zh';
281
+ }
282
+ }
283
+ function t(zh) { return languageOf() === 'en' ? (EN[zh] ?? zh) : zh; }
284
+ function englishError(message, status) {
285
+ if (status === 401)
286
+ return 'Your session has expired. Reopen DSH and try again.';
287
+ if (status === 404)
288
+ return 'The presentation workbench is unavailable. Check that the plugin is loaded and restart DSH.';
289
+ if (status === 409)
290
+ return 'The project changed. Load the latest version and review your edits before saving.';
291
+ return /[\u3400-\u9fff]/.test(message || '') ? 'The operation failed. Check the project files and DSH logs, then retry.' : message;
292
+ }
293
+ function useLanguage(locale) {
294
+ const [, rerender] = useState(0);
295
+ useEffect(() => { const update = () => rerender(n => n + 1); update(); return locale?.subscribe?.(update); }, [locale]);
296
+ }
297
+ const ROUTE = 'api/dsh-ppt/workbench';
298
+ const fields = [['title', '标题'], ['subtitle', '副标题'], ['kicker', '眉题'], ['text', '正文'], ['bullets', '要点(每行一条)'], ['notes', '演讲备注']];
299
+ const css = `
198
300
  .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
301
  .pptw *{box-sizing:border-box}.pptw h2{font-size:22px;margin:0}.pptw h3{font-size:16px;margin:12px 0 6px}
200
302
  .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}
@@ -225,22 +327,32 @@ function useLanguage(locale) {
225
327
  [role=dialog]:has(.pptw) nav{width:100%!important;flex-basis:auto!important;border-right:0;max-height:170px;overflow:auto}
226
328
  [role=dialog]:has(.pptw) nav>div:has(>button){display:flex;flex-direction:row!important;flex-wrap:wrap;flex-shrink:0;gap:4px}
227
329
  }`;
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
- const source={...slide,...slide.dataTemplate};
239
- return { title: source.title || '', subtitle: source.subtitle || '', kicker: source.kicker || '', text: source.text || '',
240
- bullets: (source.bullets || []).join('\n'), notes: source.notes || '' };
241
- }
242
- function editorHtml(html, nonce) {
243
- const bridge = `<style>#hud,#delivery-bar,#review-panel,#progress,#notes-panel,#help-panel,#toast,#blank{display:none!important}.slide-frame{pointer-events:none!important}.slide-frame .slide{pointer-events:auto!important}</style><script>(function(){const nonce=${JSON.stringify(nonce)};
330
+ async function action(body, signal) {
331
+ const response = await fetch(new URL(ROUTE, document.baseURI), { method: 'POST', credentials: 'same-origin', signal,
332
+ headers: { 'content-type': 'application/json', 'x-dsh-ppt-action': '1' }, body: JSON.stringify(body) });
333
+ let value;
334
+ try {
335
+ value = await response.json();
336
+ }
337
+ catch {
338
+ throw new Error(t("无法读取服务响应,请检查插件是否加载"));
339
+ }
340
+ if (!response.ok || value.ok === false) {
341
+ const localized = languageOf() === 'en' ? value.messageEn || englishError(value.message, response.status) : value.message;
342
+ const hint = languageOf() === 'en' ? value.installationHintEn : value.installationHint;
343
+ const error = new Error((localized || t("操作未完成")) + (hint ? '\n' + hint : ''));
344
+ error.status = response.status;
345
+ throw error;
346
+ }
347
+ return value;
348
+ }
349
+ function draftFor(slide) {
350
+ const source = { ...slide, ...slide.dataTemplate };
351
+ return { title: source.title || '', subtitle: source.subtitle || '', kicker: source.kicker || '', text: source.text || '',
352
+ bullets: (source.bullets || []).join('\n'), notes: source.notes || '' };
353
+ }
354
+ function editorHtml(html, nonce) {
355
+ 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)};
244
356
  function tell(field){parent.postMessage({type:'dsh-ppt-select',nonce:nonce,field:field},'*')}
245
357
  document.addEventListener('keydown',function(e){
246
358
  if(e.target.closest('#data-panel'))return;
@@ -258,625 +370,856 @@ function useLanguage(locale) {
258
370
  window.addEventListener('message',function(e){if(e.source!==parent||e.data?.nonce!==nonce)return;if(e.data.type==='dsh-ppt-jump')window.__dshPpt?.jump(e.data.page);if(e.data.type==='dsh-ppt-data-set'&&window.__dshData){window.__dshData.setParameters(e.data.parameters);const state=window.__dshData.getState();parent.postMessage({type:'dsh-ppt-data',nonce,parameters:e.data.parameters,valid:state.valid,command:e.data.command},'*')}});
259
371
  if(window.__dshData)window.__dshData.onChange=function(parameters,dirty,valid){parent.postMessage({type:'dsh-ppt-data',nonce,parameters,dirty,valid},'*')};
260
372
  })();<\/script>`;
261
- const policy = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; font-src data:; connect-src 'none'; form-action 'none'">`;
262
- // Presenter code contains a quoted </body>; only append at the document end.
263
- return html.replace(/<head>/i, '<head>' + policy).replace(/<\/body>(\s*<\/html>\s*)$/i, bridge + '</body>$1');
264
- }
265
- function createImageLoader() {
266
- let current = null;
267
- function cancel() {
268
- const reader = current; current = null;
269
- if (reader?.readyState === 1) reader.abort();
270
- }
271
- return {
272
- cancel,
273
- get pending() { return current !== null; },
274
- read(file, success, failure) {
275
- cancel(); const reader = new FileReader(); current = reader;
276
- const settle = callback => { if (current !== reader) return; current = null; callback(); };
277
- reader.onload = () => settle(() => success(String(reader.result)));
278
- reader.onerror = () => settle(failure);
279
- reader.onabort = () => { if (current === reader) current = null; };
280
- try { reader.readAsDataURL(file); } catch { settle(failure); }
281
- },
282
- };
283
- }
284
- function modelRouteKey(model) { return JSON.stringify([model.provider, model.model]); }
285
- function findModelRoute(models, key) { return key ? models.find(model => modelRouteKey(model) === key) : undefined; }
286
- function reconcileModelRoute(models, selected, preferred) {
287
- if (selected) return findModelRoute(models, selected) ? selected : '';
288
- const key = preferred ? modelRouteKey(preferred) : '';
289
- return findModelRoute(models, key) ? key : '';
290
- }
291
- function CoachingPanel({ project, selected, blocked, onAdopt, onChoose }) {
292
- const L = (zh, en) => languageOf() === 'en' ? en : zh;
293
- const [mode, setMode] = useState(''), [routes, setRoutes] = useState([]), [route, setRoute] = useState('');
294
- const [difficulty, setDifficulty] = useState('normal'), [audience, setAudience] = useState('general'), [limit, setLimit] = useState(1);
295
- const [scope, setScope] = useState('all'), [material, setMaterial] = useState(''), [run, setRun] = useState(null), [history, setHistory] = useState([]);
296
- const [answer, setAnswer] = useState(''), [patches, setPatches] = useState([]), [backups, setBackups] = useState([]);
297
- const [busy, setBusy] = useState(false), [error, setError] = useState(''), [notice, setNotice] = useState('');
298
- const active = useRef(null), alive = useRef(true), current = useRef(null), runRef = useRef(null), reading = useRef(0), routeInitialized = useRef(false);
299
- current.current = { project, selected, blocked }; runRef.current = run;
300
- const stale = !!run && (run.stale || run.revision !== project.revision);
301
- const maxCalls = mode === 'review' ? limit : limit + 1;
302
- const modeName = value => value === 'review' ? L('AI 预审', 'AI review') : L('模拟答辩', 'Rehearsal');
303
- const statusName = value => ({ ready: L('等待下一步', 'Ready'), busy: L('正在调用模型', 'Calling model'), paused: L('已暂停', 'Paused'), complete: L('已结束', 'Finished') })[value] || value;
304
- const kindName = value => ({ expression: L('表达建议', 'Expression'), logic: L('逻辑问题', 'Logic'), evidence: L('证据缺口', 'Missing evidence') })[value];
305
- function accept(value) { if (alive.current) { runRef.current = value; setRun(value); } }
306
- const request = (operation, data = {}, signal) => action({ operation: 'coach-' + operation, id: current.current.project.id, expectedRevision: current.current.project.revision, ...data }, signal);
307
- async function refresh(signal) { const value = await request('list', {}, signal); if (alive.current) setHistory(value.runs); }
308
- useEffect(() => {
309
- alive.current = true;
310
- return () => {
311
- alive.current = false; reading.current++;
312
- if (active.current) {
313
- active.current.abort();
314
- const item = runRef.current;
315
- if (item) void request('stop', { runId: item.id }).catch(() => {});
373
+ 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'">`;
374
+ // Presenter code contains a quoted </body>; only append at the document end.
375
+ return html.replace(/<head>/i, '<head>' + policy).replace(/<\/body>(\s*<\/html>\s*)$/i, bridge + '</body>$1');
316
376
  }
317
- };
318
- }, []);
319
- useEffect(() => {
320
- if (!run || run.status !== 'busy' || busy) return;
321
- const controller = new AbortController();
322
- const timer = setInterval(() => { void request('get', { runId: run.id }, controller.signal).then(value => { if (!controller.signal.aborted) accept(value.run); }).catch(() => {}); }, 750);
323
- return () => { clearInterval(timer); controller.abort(); };
324
- }, [run?.id, run?.status, busy]);
325
- async function task(work) {
326
- if (active.current) return;
327
- const controller = new AbortController(); active.current = controller;
328
- setBusy(true); setError(''); setNotice('');
329
- try { await work(controller.signal); }
330
- catch (e) {
331
- if (!alive.current) return;
332
- if (!controller.signal.aborted) setError(e.message || L('操作失败', 'Operation failed'));
333
- const item = runRef.current;
334
- if (item) { try { accept((await request('get', { runId: item.id })).run); } catch { /* Keep visible results. */ } }
335
- } finally {
336
- if (active.current === controller) active.current = null;
337
- if (alive.current) setBusy(false);
338
- }
339
- }
340
- function configure(value) {
341
- if (active.current || !canLeave()) return;
342
- setMode(value); setLimit(value === 'review' ? 1 : 3); accept(null); setPatches([]); setBackups([]); setAnswer('');
343
- return task(async signal => {
344
- const results = await Promise.allSettled([request('options', {}, signal), refresh(signal)]);
345
- if (signal.aborted || !alive.current) return;
346
- const available = results[0];
347
- if (available.status === 'rejected') throw available.reason;
348
- const models = available.value.routes;
349
- setRoutes(models);
350
- const preferred = routeInitialized.current ? undefined : project.modelRoute;
351
- routeInitialized.current = true;
352
- setRoute(value => reconcileModelRoute(models, value, preferred));
353
- if (!models.length) setNotice(L('先在 DSH 的模型设置中配置可用模型,再点“刷新模型”。成品仍可直接下载。', 'Configure a model in DSH, then refresh models. Your finished files remain available.'));
354
- if (results[1].status === 'rejected') throw results[1].reason;
355
- });
356
- }
357
- function canLeave() {
358
- const item = runRef.current, question = item?.questions.at(-1);
359
- 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?'));
360
- }
361
- async function advance(item, signal, response) {
362
- let next = (await request('step', { runId: item.id, confirmed: true, ...(response === undefined ? {} : { answer: response }) }, signal)).run;
363
- accept(next);
364
- // Only this explicit Start click authorizes the configured review rounds.
365
- while (next.mode === 'review' && next.status === 'ready' && !next.stale && !signal.aborted && current.current.project.revision === next.revision) {
366
- next = (await request('step', { runId: next.id, confirmed: true }, signal)).run; accept(next);
367
- }
368
- await refresh(signal);
369
- if (alive.current && response !== undefined) setAnswer('');
370
- }
371
- function start() {
372
- if (current.current.blocked) return;
373
- return task(async signal => {
374
- const model = findModelRoute(routes, route); if (!model) throw new Error(L('请选择模型', 'Choose a model'));
375
- reading.current++;
376
- const item = (await request('create', { confirmed: true, mode, ...model, difficulty, audience, limit, material,
377
- language: languageOf(), ...(scope === 'current' ? { slideId: current.current.selected } : {}) }, signal)).run;
378
- accept(item); await advance(item, signal);
379
- });
380
- }
381
- function stop() {
382
- active.current?.abort();
383
- if (runRef.current) void request('stop', { runId: runRef.current.id }).then(value => accept(value.run)).catch(e => { if (alive.current) setError(e.message); });
384
- setNotice(L('已请求停止。已完成的结果保留,本次调用仍可能计费。', 'Stop requested. Completed results are kept; the current call may still be billed.'));
385
- }
386
- function finish() { return task(async signal => { accept((await request('finish', { runId: run.id }, signal)).run); await refresh(signal); }); }
387
- 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([]); }); }
388
- function removeReport() {
389
- if (!window.confirm(L('删除这次本地演练记录?幻灯片成品不受影响。', 'Delete this local rehearsal record? Presentation files are kept.'))) return;
390
- return task(async signal => { await request('delete', { runId: run.id }, signal); accept(null); await refresh(signal); });
391
- }
392
- function exportReport() {
393
- const url = new URL('api/dsh-ppt/download', document.baseURI);
394
- for (const [key, value] of Object.entries({ id: project.id, kind: 'coaching', revision: project.revision, run: run.id })) url.searchParams.set(key, String(value));
395
- const link = document.createElement('a'); link.href = url.href; link.download = ''; link.hidden = true; document.body.append(link); link.click(); link.remove();
396
- }
397
- function applySelected() {
398
- if (current.current.blocked || stale) return;
399
- return task(async signal => {
400
- const value = await request('apply', { runId: run.id, confirmed: true, selected: patches, backup: backups }, signal);
401
- if (alive.current) onAdopt(value.project);
402
- });
403
- }
404
- async function uploadMaterial(event) {
405
- const file = event.target.files?.[0]; event.target.value = ''; if (!file) return;
406
- const ticket = ++reading.current;
407
- 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; }
408
- try {
409
- const value = await file.text();
410
- if (!alive.current || ticket !== reading.current) return;
411
- if (value.length > 20000) throw new Error(L('补充材料最多 20000 字符。', 'Supporting material: up to 20,000 characters.'));
412
- setMaterial(value); setError('');
413
- } catch (e) { if (alive.current && ticket === reading.current) setError(e.message); }
414
- }
415
- function toggle(set, values, id) { set(values.includes(id) ? values.filter(v => v !== id) : [...values, id]); }
416
- function pageButton(id) {
417
- const index = project.slides.findIndex(s => s.id === id);
418
- return h('button', { disabled: blocked || index < 0, onClick: () => onChoose(id) }, L('查看第 ' + (index + 1) + ' 页', 'View slide ' + (index + 1)));
419
- }
420
- 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.')); }
421
- const last = run?.questions.at(-1);
422
- useEffect(() => {
423
- if (!last || last.feedback || !answer.trim() || answer.trim() === (last.answer || '')) return;
424
- const warn = event => { event.preventDefault(); event.returnValue = ''; };
425
- window.addEventListener('beforeunload', warn); return () => window.removeEventListener('beforeunload', warn);
426
- }, [run?.id, last?.id, last?.feedback, last?.answer, answer]);
427
- 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(); } } },
428
- h('h3', null, L('想再准备充分一点?', 'Want to prepare further?')),
429
- h('p', { className: 'muted' }, L('成品已可下载。以下两项按需开启,不影响直接交付。', 'Your files are ready to download. Both options below are optional.')),
430
- 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')),
431
- mode && h('button', { disabled: busy, onClick: () => { if (canLeave()) { setMode(''); accept(null); setAnswer(''); } } }, L('收起', 'Collapse'))),
432
- mode && h(React.Fragment, null,
433
- error && h('div', { role: 'alert', className: 'notice error' }, error),
434
- notice && h('div', { role: 'status', className: 'notice' }, notice),
435
- busy && h('div', { role: 'status', className: 'tools' }, L('正在处理…可以继续预览或下载成品。', 'Working… You can still preview or download your presentation.'), h('button', { onClick: stop }, L('停止', 'Stop'))),
436
- !run && h(React.Fragment, null,
437
- 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.')),
438
- h('div', { className: 'coaching-grid' },
439
- h('label', null, L('模型', 'Model'), h('select', { 'aria-label': L('演练模型', 'Rehearsal model'), value: route, disabled: busy, onChange: e => setRoute(e.target.value) }, h('option', { value: '' }, routes.length ? L('请选择模型', 'Choose a model') : L('暂无可用模型', 'No configured model')), routes.map(r => h('option', { key: modelRouteKey(r), value: modelRouteKey(r) }, r.label)))),
440
- 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)))),
441
- 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)))),
442
- 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))))),
443
- 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'))))),
444
- h('label', { htmlFor: 'ppt-coach-material' }, L('补充材料(可选)', 'Supporting material (optional)')),
445
- h('textarea', { id: 'ppt-coach-material', rows: 3, maxLength: 20000, value: material, disabled: busy, onChange: e => { reading.current++; setMaterial(e.target.value); } }),
446
- 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 })),
447
- 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.')),
448
- h('div', { className: 'tools' }, h('button', { disabled: busy || blocked || !findModelRoute(routes, route), onClick: start }, mode === 'review' ? L('开始 AI 预审', 'Start AI review') : L('开始模拟答辩', 'Start rehearsal')), h('button', { disabled: busy, onClick: () => configure(mode) }, L('刷新模型', 'Refresh models'))),
449
- blocked && h('p', { className: 'muted' }, L('请先保存或取消幻灯片修改。', 'Save or cancel slide edits first.'))),
450
- run && h(React.Fragment, null,
451
- h('h3', null, modeName(run.mode) + ' · ' + statusName(run.status)),
452
- h('p', { className: 'muted' }, L('修订 ', 'Revision ') + run.revision + ' · ' + run.route.provider + ' / ' + run.route.model + ' · ' + L('调用 ', 'Calls ') + run.usedCalls + '/' + run.maxCalls),
453
- h('p', { className: 'muted' }, L('AI 意见不等于事实核验,也不代表真实听众的评价。请先看原文与改动,再决定是否采纳。', 'AI suggestions are not fact checks or predictions of audience feedback. Compare sources and edits before adopting them.')),
454
- 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.')),
455
- run.error && h('p', { className: 'muted' }, languageOf() === 'en' ? run.error.split(' / ').at(-1) : run.error.split(' / ')[0]),
456
- run.findings.map(f => {
457
- const slide = project.slides.find(s => s.id === f.slideId);
458
- return h('article', { key: f.id, className: 'card' }, h('strong', null, kindName(f.kind) + ' · ' + f.issue), h('div', { className: 'tools' }, pageButton(f.slideId)),
459
- h('p', null, f.question), h('p', null, f.answer), h('p', null, f.suggestion), source(f),
460
- 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)))))),
461
- 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'))),
462
- 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')));
463
- }),
464
- 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.')),
465
- 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),
466
- 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')))),
467
- run.mode === 'practice' && last && !last.feedback && run.status !== 'complete' && !stale && h(React.Fragment, null,
468
- 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) }),
469
- h('button', { disabled: busy || blocked || !answer.trim() || run.usedCalls >= run.maxCalls, onClick: () => task(signal => advance(run, signal, answer)) }, L('提交回答,继续', 'Submit answer and continue'))),
470
- h('div', { className: 'tools' }, h('button', { disabled: busy, onClick: exportReport }, L('下载问答与材料清单', 'Download Q&A and evidence checklist')),
471
- h('button', { disabled: busy || blocked || stale || !(patches.length + backups.length), onClick: applySelected }, L('将所选内容保存为副本', 'Save selected changes as a copy')),
472
- run.status !== 'complete' && h('button', { disabled: busy || run.status === 'busy', onClick: finish }, L('结束并整理已有结果', 'Finish with current results')),
473
- h('button', { disabled: busy, onClick: () => configure(run.mode) }, L('重新开始', 'Start again')),
474
- h('button', { disabled: busy || run.status === 'busy', onClick: removeReport }, L('删除本次记录', 'Delete this record'))),
475
- 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.'))),
476
- 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')))))));
477
- }
478
- const dataCss=`.pptw .data-workbench{margin-top:18px}.pptw .data-workbench details{margin:12px 0}.pptw .data-workbench summary{cursor:pointer;font-weight:600}.pptw .data-workbench pre,.pptw .data-workbench code{white-space:pre-wrap;overflow-wrap:anywhere;font-size:13px;max-height:220px;overflow:auto}.pptw .data-input-row{margin:15px 0}.pptw .data-input-controls{display:grid;grid-template-columns:minmax(0,1fr) 115px;gap:12px;align-items:center}.pptw .data-input-controls input[type=range]{accent-color:var(--dsw-alias-brand-primary,#2563eb)}.pptw .data-before-after{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:10px}.pptw .data-before-after pre{padding:10px;border:1px solid var(--dsw-alias-divider-default,#b8c0cc);border-radius:8px}.pptw .data-copy{display:flex;gap:8px;align-items:center}.pptw .data-copy input{width:auto}@media(max-width:640px){.pptw .data-before-after{grid-template-columns:minmax(0,1fr)}.pptw .data-input-controls{grid-template-columns:minmax(0,1fr) 100px}}`;
479
- function VisualPanel({ project, selected, blocked, onBusy, onAdopt }) {
480
- const L = (zh,en) => languageOf() === 'en' ? en : zh;
481
- const [expanded,setExpanded] = useState(false), [routes,setRoutes] = useState([]), [route,setRoute] = useState('');
482
- const [scope,setScope] = useState(project.slides.length > 12 ? 'current' : 'all'), [repairs,setRepairs] = useState(1);
483
- const [run,setRun] = useState(null), [history,setHistory] = useState([]), [busy,setBusy] = useState(false), [error,setError] = useState('');
484
- const [compare,setCompare] = useState(''), [pictures,setPictures] = useState({}), [loading,setLoading] = useState(false);
485
- const active=useRef(null), alive=useRef(true), current=useRef(null), runRef=useRef(null), progressVersion=useRef(0), routeInitialized=useRef(false);
486
- current.current={project,selected,blocked};runRef.current=run;
487
- const request=(op,data={},signal) => action({operation:'visual-'+op,id:current.current.project.id,expectedRevision:current.current.project.revision,...data},signal);
488
- const accept=value => {if(alive.current){progressVersion.current++;runRef.current=value;setRun(value);}};
489
- const phaseName=value => ({render:L('正在渲染实际 PPTX','Rendering the actual PPTX'),inspect:L('正在看图检查','Inspecting rendered slides'),repair:L('正在生成排版副本','Creating a formatting copy'),done:L('检查已结束','Review finished')})[value]||value;
490
- const failureText=value=>{const split=value.lastIndexOf(' / ');return split<0?value:L(value.slice(0,split),value.slice(split+3));};
491
- const actionName=a => ({'title-size':L('标题字号','Title size'),'body-size':L('正文字号','Body size'),'chart-label-size':L('图表字号','Chart label size'),'chart-horizontal':L('改为横向条形图','Use horizontal bars'),'image-contain':L('完整显示图片','Show the complete image'),'split-bullets':L('拆分要点页','Split bullet slide'),'split-table':L('拆分表格页','Split table slide')})[a.type]+(a.value!==undefined?' · '+a.value:'');
492
- useEffect(()=>{alive.current=true;return()=>{alive.current=false;active.current?.abort();if(runRef.current&&active.current)void request('stop',{runId:runRef.current.id}).catch(()=>{});};},[]);
493
- useEffect(()=>{if(!run||['complete','paused'].includes(run.status)||!busy&&run.status!=='busy')return;const abort=new AbortController(),timer=setInterval(()=>{const version=progressVersion.current;void request('get',{runId:run.id},abort.signal).then(v=>{if(!abort.signal.aborted&&version===progressVersion.current)accept(v.run);}).catch(()=>{});},1000);return()=>{clearInterval(timer);abort.abort();};},[run?.id,run?.status,busy]);
494
- async function refresh(signal){const value=await request('list',{},signal);if(alive.current)setHistory(value.runs);}
495
- async function task(work,lock=false){
496
- if(active.current)return;
497
- const controller=new AbortController();active.current=controller;setBusy(true);setError('');if(lock)onBusy(true);
498
- try{await work(controller.signal);}
499
- catch(e){if(alive.current){if(!controller.signal.aborted)setError(e.message||L('视觉检查失败','Visual review failed'));if(runRef.current)try{accept((await request('get',{runId:runRef.current.id})).run);}catch{/* Keep the last checkpoint. */}}}
500
- finally{if(active.current===controller)active.current=null;if(alive.current)setBusy(false);if(lock)onBusy(false);}
501
- }
502
- function configure(){setExpanded(true);return task(async signal=>{
503
- const results=await Promise.allSettled([request('options',{},signal),refresh(signal)]);
504
- if(results[0].status==='rejected')throw results[0].reason;
505
- if(signal.aborted||!alive.current)return;
506
- const models=results[0].value.routes;setRoutes(models);
507
- const preferred=routeInitialized.current?undefined:project.modelRoute;routeInitialized.current=true;
508
- setRoute(value=>reconcileModelRoute(models,value,preferred));
509
- if(results[1].status==='rejected')throw results[1].reason;
510
- });}
511
- function start(){if(current.current.blocked)return;return task(async signal=>{
512
- const model=findModelRoute(routes,route);if(!model)throw new Error(L('请选择支持图片输入的模型','Choose an image-capable model'));
513
- let value=(await request('create',{confirmed:true,...model,repairs,language:languageOf(),...(scope==='current'?{slideId:current.current.selected}:{})},signal)).run;
514
- accept(value);setPictures({});setCompare('');
515
- while(value.status==='ready'&&!signal.aborted){value=(await request('step',{runId:value.id,confirmed:true},signal)).run;accept(value);}
516
- await refresh(signal);
517
- const last=value.rounds.at(-1);if(alive.current&&last?.rendered)setCompare(last.ids[0]);
518
- },true);}
519
- function stop(){active.current?.abort();if(runRef.current)void request('stop',{runId:runRef.current.id}).then(value=>accept(value.run)).catch(e=>{if(alive.current)setError(e.message);});}
520
- function open(id){return task(async signal=>{const value=(await request('get',{runId:id},signal)).run;accept(value);setCompare(value.rounds.at(-1)?.rendered?value.rounds.at(-1).ids[0]:'');});}
521
- function adopt(){if(blocked||!run?.canAdopt)return;return task(async signal=>{const value=await request('adopt',{runId:run.id,confirmed:true},signal);if(alive.current)onAdopt(value.project);},true);}
522
- function remove(){if(!window.confirm(L('删除这次检查记录和预览图片?生成的 PPT 副本会保留。','Delete this review and its preview images? Presentation copies are kept.')))return;return task(async signal=>{await request('delete',{runId:run.id},signal);accept(null);setPictures({});setCompare('');await refresh(signal);});}
523
- function download(){const url=new URL('api/dsh-ppt/download',document.baseURI);for(const[k,v]of Object.entries({id:project.id,kind:'visual',revision:project.revision,run:run.id}))url.searchParams.set(k,String(v));const a=document.createElement('a');a.href=url.href;a.download='';document.body.append(a);a.click();a.remove();}
524
- useEffect(()=>{
525
- if(!compare||!run)return;
526
- const abort=new AbortController(),last=run.rounds.length-1;setPictures({});setLoading(true);
527
- const initial=run.rounds[0].ids.includes(compare);
528
- Promise.allSettled([initial?request('page',{runId:run.id,round:0,slideId:compare},abort.signal):Promise.resolve(null),request('page',{runId:run.id,round:last,slideId:compare},abort.signal)]).then(values=>{
529
- if(abort.signal.aborted||!alive.current)return;
530
- setPictures({before:values[0].status==='fulfilled'?values[0].value?.data:null,after:values[1].status==='fulfilled'?values[1].value?.data:null});
531
- const failed=values.find(v=>v.status==='rejected');if(failed)setError(failed.reason.message);setLoading(false);
532
- });return()=>abort.abort();
533
- },[run?.id,run?.rounds.length,compare]);
534
- useEffect(()=>{const last=run?.rounds.at(-1);if(!busy&&!compare&&last?.rendered)setCompare(last.ids[0]);},[run?.id,run?.rounds.length,run?.rounds.at(-1)?.rendered,busy,compare]);
535
- const first=run?.rounds[0],last=run?.rounds.at(-1),stale=run&&(run.stale||run.revision!==project.revision),count=scope==='all'?project.slides.length:1;
536
- const callCap=Array.from({length:repairs+1},(_,i)=>Math.ceil(count*2**i/2)).reduce((a,b)=>a+b,0);
537
- function image(src,round,label){return h('figure',{style:{margin:0,minWidth:0}},h('figcaption',null,label),src?h('div',{style:{position:'relative',lineHeight:0}},h('img',{src,alt:label,style:{width:'100%',height:'auto',display:'block'}}),(round?.findings||[]).filter(f=>f.slideId===compare).map((f,i)=>h('span',{key:i,title:f.issue,style:{position:'absolute',pointerEvents:'none',border:'2px solid #f97316',boxSizing:'border-box',left:f.box[0]*100+'%',top:f.box[1]*100+'%',width:f.box[2]*100+'%',height:f.box[3]*100+'%'}}))):h('p',{className:'muted'},round===first&&!first.ids.includes(compare)?L('此页由拆分生成,没有对应的原页画面。','This page was created by a split and has no original counterpart.'):L('画面尚未载入,请重新选择页面。','Image not loaded; select the slide again.')));}
538
- return h('section',{className:'card coaching','aria-label':L('视觉检查与修复','Visual review and repair')},
539
- h('h3',null,L('让 AI 看完成品,再修排版','Let AI inspect the finished slides and repair formatting')),
540
- h('p',{className:'muted'},L('可选功能。检查实际 PPTX 画面,另存修复副本,再渲染复查。原稿保留。','Optional. Inspect actual PPTX images, save a repaired copy, and render it again for rechecking. The original is kept.')),
541
- !expanded?h('button',{disabled:busy||blocked,onClick:configure},L('视觉检查与修复','Visual review and repair')):h(React.Fragment,null,
542
- error&&h('div',{role:'alert',className:'notice error'},error),
543
- !run&&h(React.Fragment,null,
544
- h('div',{className:'coaching-grid'},
545
- h('label',null,L('视觉模型','Vision model'),h('select',{'aria-label':L('视觉模型','Vision model'),value:route,disabled:busy,onChange:e=>setRoute(e.target.value)},h('option',{value:''},L('请选择','Choose a model')),routes.map(m=>h('option',{key:modelRouteKey(m),value:modelRouteKey(m)},m.label)))),
546
- h('label',null,L('检查范围','Review scope'),h('select',{'aria-label':L('视觉检查范围','Visual review scope'),value:scope,disabled:busy,onChange:e=>setScope(e.target.value)},h('option',{value:'all',disabled:project.slides.length>12},L('全部页面(最多 12 页)','All slides (up to 12)')),h('option',{value:'current'},L('当前页','Current slide')))),
547
- h('label',null,L('自动修复上限','Repair limit'),h('select',{'aria-label':L('自动修复上限','Repair limit'),value:repairs,disabled:busy,onChange:e=>setRepairs(Number(e.target.value))},h('option',{value:0},L('仅看图检查','Inspect only')),h('option',{value:1},L('最多修复 1 轮(推荐)','Up to 1 repair round (recommended)')),h('option',{value:2},L('最多修复 2 轮','Up to 2 repair rounds'))))),
548
- !routes.length&&h('p',{className:'notice'},L('未找到声明支持图片输入的模型。请在 DSH 模型设置中检查图片输入配置;普通生成和下载仍可使用。','No model declares image input. Check the image-input configuration in DSH model settings; normal creation and downloads remain available.')),
549
- h('p',null,L('会向所选模型发送 '+count+' 页的渲染图片和页面文字;拆页后会重新检查新增页面,最多 '+callCap+' 次模型调用。','Sends rendered images and text from '+count+' slides to the selected model. New split pages are rechecked, with up to '+callCap+' model calls.')),
550
- h('p',{className:'muted'},L('只调整字号、拆页、图表方向和图片裁切,不改写原文、数字或公式。可随时停止;服务商仍可能收取已发起调用的费用。','Changes font sizes, pagination, chart orientation and image cropping. Original text, numbers and formulas are preserved. You can stop at any time; calls already sent may still be billed.')),
551
- h('div',{className:'tools'},h('button',{className:'primary',disabled:busy||blocked||!findModelRoute(routes,route)||count>12,onClick:start},L('开始看图检查','Start visual review')),h('button',{disabled:busy,onClick:configure},L('刷新视觉模型','Refresh vision models')))),
552
- run&&h(React.Fragment,null,
553
- h('p',{role:'status'},(run.status==='paused'?L('检查已停止','Review stopped'):run.status==='ready'&&!busy?L('等待检查','Review ready'):phaseName(run.phase))+' · '+L('已调用 ','Calls ')+run.usedCalls+'/'+run.maxCalls+' · '+L('本轮已检查 ','Slides checked this pass ')+(last?.cursor||0)+'/'+(last?.ids.length||0)),
554
- busy&&h('button',{onClick:stop},L('停止视觉检查','Stop visual review')),
555
- run.error&&h('p',{role:'alert',className:'notice error'},failureText(run.error)),
556
- stale&&h('p',{className:'notice'},L('工程或成品已变化,旧记录可查看,但不能继续或采纳。','The project or output changed. This old record is readable, but cannot be continued or adopted.')),
557
- run.status==='complete'&&h('p',{className:'notice'},last.findings.length?L('复查仍有 '+last.findings.length+' 个问题,请查看标记和说明。','Recheck still found '+last.findings.length+' issues. Review the highlighted regions and notes.'):L('AI 在本次范围内未发现明显视觉问题;这是一份模型检查记录。','AI found no obvious visual issues in this scope. This is a model review record.')),
558
- (last?.missingFonts||[]).length>0&&h('p',{className:'notice error'},L('渲染引擎报告缺失字体:','Renderer reported missing fonts: ')+last.missingFonts.join(', ')),
559
- run.rounds.map((r,i)=>h('details',{key:i,open:i===run.rounds.length-1},h('summary',null,L('检查轮次 ','Inspection pass ')+i+' · '+r.cursor+'/'+r.ids.length),r.findings.map((f,j)=>h('p',{key:j},h('strong',null,(project.slides.findIndex(s=>s.id===f.slideId)>=0?L('原第 '+(project.slides.findIndex(s=>s.id===f.slideId)+1)+' 页','Original slide '+(project.slides.findIndex(s=>s.id===f.slideId)+1)):L('拆分页','Split page'))+' · '),f.issue,h('br'),h('small',{className:'muted'},f.action?actionName(f.action):L('需要人工判断','Needs manual review')))),r.applied.length>0&&h('ul',null,r.applied.map((a,j)=>h('li',{key:j},L('已应用:','Applied: ')+actionName(a)))))),
560
- !busy&&last?.rendered&&h(React.Fragment,null,
561
- h('label',null,L('查看前后画面(橙框为 AI 定位区域)','Compare images (orange boxes mark AI findings)'),h('select',{'aria-label':L('对比页面','Comparison slide'),value:compare,onChange:e=>setCompare(e.target.value)},last.ids.map((id,i)=>h('option',{value:id,key:id},String(i+1)+'. '+(project.slides.find(s=>s.id===id)?.title||L('拆分页','Split page')))))),
562
- loading?h('p',{role:'status'},L('正在载入画面…','Loading images…')):h('div',{className:'before-after'},image(pictures.before,first,L('原稿 · 实际 PPTX','Original · actual PPTX')),image(pictures.after,last,run.rounds.length>1?L('修复后 · 实际 PPTX','Repaired · actual PPTX'):L('本次检查画面','Reviewed image')))),
563
- h('div',{className:'tools'},h('button',{className:'primary',disabled:busy||blocked||!run.canAdopt||stale,onClick:adopt},last?.findings.length?L('打开修复副本(仍有待处理问题)','Open repaired copy (issues remain)'):L('采用修复副本','Use repaired copy')),h('button',{disabled:busy,onClick:download},L('下载视觉检查记录','Download visual review')),h('button',{disabled:busy||run.status==='busy',onClick:remove},L('删除检查记录','Delete review')),h('button',{disabled:busy,onClick:()=>{accept(null);setCompare('');setPictures({});configure();}},L('新建视觉检查','New visual review')))),
564
- !busy&&history.length>0&&h('details',null,h('summary',null,L('本机视觉检查历史','Local visual review history')),h('div',{className:'project-list'},history.map(item=>h('button',{key:item.id,onClick:()=>open(item.id)},L('修订 ','Revision ')+item.revision+' · '+new Date(item.createdAt).toLocaleString(languageOf()==='en'?'en-US':'zh-CN'))))),
565
- h('button',{disabled:busy,onClick:()=>setExpanded(false)},L('收起视觉检查','Collapse visual review'))));
566
- }
567
- function DataPanel({project,blocked,incoming,onParameters,onDirty,onBusy,onAdopt,onChoose,onDownload}) {
568
- const L=(zh,en)=>languageOf()==='en'?en:zh,model=project.dataModel;
569
- const baseline=Object.fromEntries(model.metrics.filter(m=>m.kind==='input').map(m=>[m.id,String(m.value)]));
570
- const [parameters,setParameters]=useState(baseline),[updates,setUpdates]=useState({}),[sourceId,setSourceId]=useState(model.sources[0]?.id||'');
571
- const [metricId,setMetricId]=useState(model.metrics[0]?.id||''),[preview,setPreview]=useState(null),[error,setError]=useState(''),[busy,setBusy]=useState(false),[valid,setValid]=useState(true),[saveAs,setSaveAs]=useState(true),[readingFile,setReadingFile]=useState(false);
572
- const pending=useRef(null),alive=useRef(true),reading=useRef(0),latest=useRef(''),guard=useRef(false);
573
- const numeric=Object.fromEntries(Object.entries(parameters).map(([id,value])=>[id,value.trim()===''?null:Number(value)]));
574
- const inputsValid=model.metrics.filter(m=>m.kind==='input').every(m=>typeof numeric[m.id]==='number'&&Number.isFinite(numeric[m.id])&&numeric[m.id]>=m.min&&numeric[m.id]<=m.max&&Math.abs((numeric[m.id]-m.min)/m.step-Math.round((numeric[m.id]-m.min)/m.step))<=1e-6);
575
- const body={parameters:numeric,sourceUpdates:Object.values(updates)},signature=JSON.stringify(body);latest.current=signature;
576
- const changed=readingFile||!valid||Object.entries(baseline).some(([id,value])=>Number(parameters[id])!==Number(value)||parameters[id].trim()==='')||Object.keys(updates).length>0;
577
- useEffect(()=>{onDirty(changed);return()=>onDirty(false);},[changed]);
578
- useEffect(()=>{setPreview(null);},[signature]);
579
- useEffect(()=>{if(incoming){setParameters(Object.fromEntries(Object.entries(incoming.parameters).map(([id,value])=>[id,Number.isFinite(value)?String(value):''])));setValid(incoming.valid!==false);}},[incoming]);
580
- useEffect(()=>{alive.current=true;return()=>{alive.current=false;reading.current++;pending.current?.abort();onBusy(false);};},[]);
581
- function changeParameter(id,value){const next={...parameters,[id]:value};setParameters(next);setValid(true);setPreview(null);setError('');onParameters(Object.fromEntries(Object.entries(next).map(([key,raw])=>[key,raw.trim()===''?NaN:Number(raw)])));}
582
- function reset(){reading.current++;setParameters(baseline);setUpdates({});setPreview(null);setError('');setValid(true);onParameters(Object.fromEntries(Object.entries(baseline).map(([id,value])=>[id,Number(value)])));}
583
- async function task(work){
584
- if(guard.current||blocked||readingFile)return;guard.current=true;setBusy(true);onBusy(true);setError('');
585
- const controller=new AbortController();pending.current=controller;
586
- try{await work(controller.signal);}catch(reason){if(alive.current&&!controller.signal.aborted)setError(reason.message||L('操作失败','Operation failed'));}
587
- finally{pending.current=null;guard.current=false;if(alive.current){setBusy(false);onBusy(false);}}
588
- }
589
- function inspect(){const sent=signature;return task(async signal=>{const value=await action({operation:'data-preview',id:project.id,expectedRevision:project.revision,...body},signal);if(alive.current&&latest.current===sent)setPreview({...value,signature:sent});});}
590
- function apply(){if(!preview||preview.signature!==signature)return;const sent=signature;return task(async signal=>{const value=await action({operation:'data-apply',id:project.id,expectedRevision:project.revision,...body,confirmed:true,previewToken:preview.token,saveAs},signal);if(alive.current&&latest.current===sent){onDirty(false);onAdopt(value.project);}});}
591
- async function importSource(event){
592
- const file=event.target.files?.[0];event.target.value='';if(!file)return;const stamp=++reading.current,target=sourceId;
593
- if(file.size>1024*1024||!['csv','tsv','txt','md'].includes(file.name.split('.').at(-1)?.toLowerCase())){setError(L('请选择 1 MiB 内的 CSV、TSV、TXT 或 Markdown。','Choose CSV, TSV, TXT or Markdown up to 1 MiB.'));return;}
594
- setReadingFile(true);try{const content=await file.text();if(!alive.current||stamp!==reading.current)return;const ext=file.name.split('.').at(-1).toLowerCase();setUpdates(old=>({...old,[target]:{id:target,format:ext==='csv'||ext==='tsv'?ext:'text',content}}));setPreview(null);setError('');}catch{if(alive.current)setError(L('无法读取材料,请重试。','Could not read source. Try again.'));}finally{if(alive.current)setReadingFile(false);}
595
- }
596
- async function importScenario(event){
597
- const file=event.target.files?.[0];event.target.value='';if(!file)return;const stamp=++reading.current;
598
- setReadingFile(true);
599
- try{
600
- if(file.size>32000)throw new Error(L('推演参数文件过大。','Scenario parameter file is too large.'));
601
- const packet=JSON.parse(await file.text());if(!alive.current||stamp!==reading.current)return;
602
- if(packet.schemaVersion!==1||packet.deckId!==project.deckId||packet.revision!==project.revision||packet.fingerprint!==model.fingerprint||!packet.parameters||typeof packet.parameters!=='object'||Array.isArray(packet.parameters)||Object.keys(packet.parameters).some(id=>!Object.hasOwn(baseline,id))||Object.values(packet.parameters).some(value=>typeof value!=='number'||!Number.isFinite(value)))throw new Error(L('参数来自其他工程、旧版本或格式无效,请重新导出。','Scenario is stale, belongs to another project, or is invalid. Export it again.'));
603
- const next={...baseline,...Object.fromEntries(Object.entries(packet.parameters).map(([id,value])=>[id,String(value)]))};setParameters(next);setValid(true);setPreview(null);onParameters(Object.fromEntries(Object.entries(next).map(([id,value])=>[id,Number(value)])));setError('');
604
- }catch(reason){if(alive.current)setError(reason.message);}finally{if(alive.current)setReadingFile(false);}
605
- }
606
- const metric=model.metrics.find(m=>m.id===metricId),source=model.sources.find(s=>s.id===sourceId),replacement=updates[sourceId];
607
- const format=(value,m)=>new Intl.NumberFormat(languageOf()==='en'?'en-US':'zh-CN',{style:m.format.style==='percent'?'percent':'decimal',minimumFractionDigits:m.format.digits,maximumFractionDigits:m.format.digits}).format(value)+(m.format.unit||'');
608
- const display=value=>typeof value==='string'?value:JSON.stringify(value,null,2),disabled=busy||blocked||readingFile;
609
- return h('section',{className:'card data-workbench','aria-label':L('数据溯源与现场推演','Data lineage and what-if')},
610
- h('style',null,dataCss),
611
- h('h3',null,L('数据溯源与现场推演','Data lineage and what-if')),
612
- h('p',{className:'muted'},L('点预览中的数字可追问来源。只有明确声明的假设可调;来源不等于事实已核验。','Click numbers in the preview to inspect their lineage. Only declared assumptions are adjustable. Lineage is not factual verification.')),
613
- h('details',null,h('summary',null,L('数字来自哪里','Where the numbers come from')),
614
- h('label',null,L('指标','Metric'),h('select',{value:metricId,disabled,onChange:event=>setMetricId(event.target.value)},model.metrics.map(m=>h('option',{key:m.id,value:m.id},m.label+' ['+m.id+']')))),
615
- metric&&h('div',{className:'data-evidence'},h('strong',null,metric.label+' = '+format(model.values[metric.id],metric)),
616
- metric.kind==='source'?h(React.Fragment,null,h('p',null,metric.evidence.name+' · '+metric.evidence.locator),h('pre',null,metric.evidence.excerpt),h('details',null,h('summary',null,L('来源快照校验值','Source snapshot checksum')),h('code',null,metric.evidence.sha256))):metric.kind==='input'?h('p',null,L('用户假设','User assumption')+(metric.note?' · '+metric.note:'')):h(React.Fragment,null,h('pre',null,'= '+metric.formula),h('div',{className:'tools'},metric.dependencies.map(id=>h('button',{key:id,disabled,onClick:()=>setMetricId(id)},model.metrics.find(m=>m.id===id).label))))),
617
- h('button',{disabled:disabled||changed,onClick:()=>onDownload('data')},L('下载溯源与假设报告','Download lineage and assumptions'))),
618
- model.metrics.some(m=>m.kind==='input')&&h('details',{open:true},h('summary',null,L('现场推演参数','What-if assumptions')),
619
- model.metrics.filter(m=>m.kind==='input').map(m=>h('div',{key:m.id,className:'data-input-row'},h('label',{htmlFor:'ppt-data-'+m.id},m.label,h('small',{className:'muted'},' · '+L('假设','Assumption')+(m.note?' · '+m.note:''))),h('div',{className:'data-input-controls'},h('input',{type:'range',min:m.min,max:m.max,step:m.step,value:Number(parameters[m.id]),disabled,'aria-label':m.label+' '+L('滑杆','slider'),onChange:event=>changeParameter(m.id,event.target.value)}),h('input',{id:'ppt-data-'+m.id,type:'number',min:m.min,max:m.max,step:m.step,value:parameters[m.id],disabled,onChange:event=>changeParameter(m.id,event.target.value)})))),
620
- h('label',null,L('导入离线 HTML 保存的推演参数','Import scenario parameters saved in offline HTML'),h('input',{type:'file',accept:'.json,application/json',disabled,onChange:importScenario}))),
621
- model.sources.length>0&&h('details',null,h('summary',null,L('更新来源材料','Update source material')),
622
- h('p',{className:'muted'},L('先导入或粘贴新材料,预览影响后再确认;不会自动监视或修改原文件。表格可从 Excel 导出 CSV。','Import or paste new material, then preview the impact before confirming. Original source files are not watched or modified. Export Excel tables as CSV.')),
623
- h('label',null,L('替换来源','Replace source'),h('select',{value:sourceId,disabled,onChange:event=>setSourceId(event.target.value)},model.sources.map(s=>h('option',{key:s.id,value:s.id},s.name)))),
624
- h('label',null,L('导入替换材料','Import replacement material'),h('input',{type:'file',accept:source?.kind==='table'?'.csv,.tsv':'.txt,.md',disabled,onChange:importSource})),
625
- source?.kind==='table'&&h('label',null,L('分隔格式','Delimiter format'),h('select',{value:replacement?.format||'csv',disabled,onChange:event=>{setUpdates(old=>({...old,[sourceId]:{id:sourceId,format:event.target.value,content:replacement?.content||''}}));setPreview(null);}},h('option',{value:'csv'},'CSV'),h('option',{value:'tsv'},'TSV'))),
626
- h('label',null,L('或粘贴内容','Or paste content'),h('textarea',{rows:4,maxLength:1048576,value:replacement?.content??'',disabled,onChange:event=>{setUpdates(old=>({...old,[sourceId]:{id:sourceId,format:source.kind==='table'?replacement?.format||'csv':'text',content:event.target.value}}));setPreview(null);setError('');}})),
627
- replacement&&h('button',{disabled,onClick:()=>{setUpdates(old=>{const next={...old};delete next[sourceId];return next;});setPreview(null);}},L('取消此来源更新','Cancel this source update'))),
628
- changed&&h('p',{className:'dirty',role:'status'},L('推演或材料尚未保存,当前 PPTX 仍是已保存版本。先预览差异并确认,或恢复参数后下载。','Unsaved scenario or source changes. The PPTX still contains saved values. Preview and confirm, or reset before downloading.')),
629
- (!valid||!inputsValid)&&h('p',{className:'notice error',role:'alert'},L('参数无法计算,请检查范围、步长或除零,再恢复或修改。','Cannot calculate these parameters. Check ranges, steps or division by zero; adjust or reset.')),
630
- error&&h('p',{className:'notice error',role:'alert'},error),
631
- h('div',{className:'tools'},h('button',{disabled:disabled||!changed||!valid||!inputsValid,onClick:inspect},L('预览差异','Preview changes')),h('button',{disabled:disabled||!changed,onClick:reset},L('恢复已保存数据','Reset to saved data'))),
632
- preview&&preview.signature===signature&&h('div',{className:'data-diff'},h('h4',null,L('确认前核对','Review before confirming')),
633
- !preview.changed?h('p',null,L('内容没有变化。','No content changes.')):h(React.Fragment,null,
634
- h('ul',null,preview.changes.map(change=>h('li',{key:change.id},h('strong',null,change.label+': '),change.beforeText+' → '+change.afterText,change.before===change.after&&' · '+L('来源已更新','Source updated')))),
635
- h('h4',null,L('受影响页面','Affected slides')),
636
- !preview.affectedSlides.length&&h('p',{className:'muted'},L('指标尚未绑定到页面,只更新数据模型。','Metrics are not bound to slides; only the data model changes.')),
637
- preview.affectedSlides.map(slide=>h('details',{key:slide.id},h('summary',null,(slide.page)+'. '+slide.title),h('button',{disabled,onClick:()=>onChoose(slide.id)},L('查看页面','View slide')),slide.evidenceChanged&&h('p',null,L('关联的来源快照有变化。','A linked source snapshot changed.')),slide.fields.map(field=>h('div',{key:field.field},h('strong',null,t(fields.find(([key])=>key===field.field)?.[1]||field.field)),h('div',{className:'data-before-after'},h('pre',null,L('之前:','Before: ')+display(field.before)),h('pre',null,L('之后:','After: ')+display(field.after))))))),
638
- h('label',{className:'data-copy'},h('input',{type:'checkbox',checked:saveAs,disabled,onChange:event=>setSaveAs(event.target.checked)}),L('保存为新副本,保留原稿(推荐)','Save a new copy and keep the original (recommended)')),
639
- h('p',{className:'muted'},L('PPTX 保存确认后的静态结果,并附公式、来源和假设;HTML 保留交互。JSON 工程包含导入的完整材料,分享前请检查。','PPTX saves confirmed static results with formulas, sources and assumptions; HTML retains interaction. The JSON project contains full imported material; review it before sharing.')),
640
- h('button',{className:'primary',disabled:disabled||!valid||!inputsValid,onClick:apply},saveAs?L('确认并保存推演副本','Confirm and save scenario copy'):L('确认并更新当前工程','Confirm and update this project')))));
641
- }
642
- function Workbench({ locale } = {}) {
643
- useLanguage(locale);
644
- const [projects, setProjects] = useState([]), [project, setProject] = useState(null), [selected, setSelected] = useState('');
645
- const [draft, setDraft] = useState({}), [image, setImage] = useState(null), [dirty, setDirty] = useState(false);
646
- const [dataDirty,setDataDirty]=useState(false),[incomingData,setIncomingData]=useState(null);
647
- const [busy, setBusy] = useState(false), [job, setJob] = useState(''), [message, setMessage] = useState(''), [error, setError] = useState('');
648
- const [mode, setMode] = useState('html'), [raster, setRaster] = useState('');
649
- const [conflict, setConflict] = useState(false), [overlaps, setOverlaps] = useState([]);
650
- const frame = useRef(null), previewBox = useRef(null), fieldRefs = useRef({}), alive = useRef(true), operations = useRef(new Set());
651
- const imageLoader = useRef(null);
652
- if (!imageLoader.current) imageLoader.current = createImageLoader();
653
- const imagePending = imageLoader.current.pending;
654
- const nonce = useRef(crypto.randomUUID());
655
- const dataCommand=useRef(0);
656
- const previewDocument = useMemo(() => project?.html ? editorHtml(project.html, nonce.current) : '', [project?.html]);
657
- const index = project ? Math.max(0, project.slides.findIndex(s => s.id === selected)) : 0;
658
- const slide = project?.slides[index];
659
- function adopt(next, preferred) {
660
- imageLoader.current.cancel();
661
- nonce.current=crypto.randomUUID();setDataDirty(false);setIncomingData(null);
662
- setProject(next);
663
- const row = next.slides.find(s => s.id === preferred) || next.slides[0];
664
- setSelected(row.id); setDraft(draftFor(row)); setImage(null); setDirty(false); setRaster(''); setOverlaps([]);
665
- if (!next.render) setMode('html');
666
- }
667
- async function perform(work, success, label = t("正在处理,请稍候…")) {
668
- setBusy(true); setJob(label); setError(''); setMessage(''); setConflict(false);
669
- const controller = new AbortController(); operations.current.add(controller);
670
- try { const result = await work(controller.signal); if (alive.current && success) success(result); }
671
- catch (e) { if (alive.current) { setError(e.message || t("操作失败")); setConflict(e.status === 409); } }
672
- finally { operations.current.delete(controller); if (alive.current) setBusy(false); }
673
- }
674
- function refreshList() { return perform(signal => action({ operation: 'list' }, signal), value => setProjects(value.projects)); }
675
- useEffect(() => {
676
- alive.current = true; const abort = new AbortController();
677
- action({ operation: 'list' }, abort.signal).then(value => { if (alive.current) setProjects(value.projects) }).catch(e => { if (!abort.signal.aborted) setError(e.message) });
678
- return () => { alive.current = false; abort.abort(); imageLoader.current.cancel(); for (const operation of operations.current) operation.abort(); };
679
- }, []);
680
- useEffect(() => {
681
- function receive(event) {
682
- if (event.source !== frame.current?.contentWindow || event.data?.nonce !== nonce.current || mode !== 'html') return;
683
- if(event.data.type==='dsh-ppt-data'){if(typeof event.data.command==='number'&&event.data.command!==dataCommand.current)return;setIncomingData({parameters:event.data.parameters,valid:event.data.valid});return;}
684
- if (event.data.type === 'dsh-ppt-shortcut') { handleShortcut(event.data.key); return; }
685
- if (event.data.type !== 'dsh-ppt-select') return;
686
- const key = event.data.field;
687
- const field = fields.find(([field]) => field === key);
688
- if (field) { fieldRefs.current[key]?.focus(); fieldRefs.current[key]?.scrollIntoView({ block: 'nearest' }); setMessage(t("已定位到") + t(field[1]) + t(",在字段中修改后保存。")); }
689
- }
690
- window.addEventListener('message', receive); return () => window.removeEventListener('message', receive);
691
- }, [mode, project, dirty, busy, imagePending, index, selected, draft, image, dataDirty]);
692
- useEffect(() => {
693
- if (mode !== 'html' || !project || !previewBox.current) return;
694
- // Align iframe edges/dimensions when the host uses fractional text metrics.
695
- const box = previewBox.current;
696
- function align() {
697
- const target = frame.current; if (!target) return;
698
- const r = box.getBoundingClientRect(), x = r.x + box.clientLeft, y = r.y + box.clientTop;
699
- target.style.width = box.clientWidth + 'px'; target.style.height = box.clientHeight + 'px';
700
- target.style.transform = 'translate(' + (Math.ceil(x) - x) + 'px,' + (Math.ceil(y) - y) + 'px)';
701
- }
702
- align(); const observer = new ResizeObserver(align); observer.observe(box);
703
- window.addEventListener('scroll', align, true);
704
- return () => { observer.disconnect(); window.removeEventListener('scroll', align, true); };
705
- }, [mode, !!project]);
706
- function jump() { frame.current?.contentWindow?.postMessage({ type: 'dsh-ppt-jump', nonce: nonce.current, page: index }, '*'); }
707
- useEffect(() => { jump(); }, [index, project?.revision, mode]);
708
- useEffect(() => {
709
- if (mode !== 'pptx' || !project?.render) return;
710
- const abort = new AbortController(); setRaster('');
711
- 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) });
712
- return () => abort.abort();
713
- }, [mode, index, project?.revision]);
714
- function handleShortcut(key) {
715
- if(dataDirty)return;
716
- if (key === 'save') { if (project && dirty && !busy && !imagePending) save(); return; }
717
- if (key === 'escape') {
718
- if (!project || busy || imagePending) return;
719
- if (dirty) {
720
- if (!window.confirm(t("有未保存修改,确定取消吗?"))) return;
721
- setDraft(draftFor(slide)); setImage(null); setDirty(false); setError(''); setMessage(t("已取消未保存的修改。"));
722
- } else {
723
- imageLoader.current.cancel(); setProject(null); refreshList();
377
+ function createImageLoader() {
378
+ let current = null;
379
+ function cancel() {
380
+ const reader = current;
381
+ current = null;
382
+ if (reader?.readyState === 1)
383
+ reader.abort();
384
+ }
385
+ return {
386
+ cancel,
387
+ get pending() { return current !== null; },
388
+ read(file, success, failure) {
389
+ cancel();
390
+ const reader = new FileReader();
391
+ current = reader;
392
+ const settle = callback => { if (current !== reader)
393
+ return; current = null; callback(); };
394
+ reader.onload = () => settle(() => success(String(reader.result)));
395
+ reader.onerror = () => settle(failure);
396
+ reader.onabort = () => { if (current === reader)
397
+ current = null; };
398
+ try {
399
+ reader.readAsDataURL(file);
400
+ }
401
+ catch {
402
+ settle(failure);
403
+ }
404
+ },
405
+ };
724
406
  }
725
- return;
726
- }
727
- if (key === 'prev' || key === 'next') {
728
- if (!project || busy || dirty || imagePending) return;
729
- const next = index + (key === 'next' ? 1 : -1);
730
- if (next >= 0 && next < project.slides.length) choose(project.slides[next]);
731
- }
732
- }
733
- useEffect(() => {
734
- function onKey(event) {
735
- if (event.isComposing || event.defaultPrevented) return;
736
- if (event.key === 'Escape' && event.target && event.target.tagName === 'SELECT') return;
737
- const mod = event.ctrlKey || event.metaKey;
738
- if (mod && (event.key === 's' || event.key === 'S')) {
739
- if (!project) return;
740
- event.preventDefault(); handleShortcut('save'); return;
407
+ function modelRouteKey(model) { return JSON.stringify([model.provider, model.model]); }
408
+ function findModelRoute(models, key) { return key ? models.find(model => modelRouteKey(model) === key) : undefined; }
409
+ function reconcileModelRoute(models, selected, preferred) {
410
+ if (selected)
411
+ return findModelRoute(models, selected) ? selected : '';
412
+ const key = preferred ? modelRouteKey(preferred) : '';
413
+ return findModelRoute(models, key) ? key : '';
741
414
  }
742
- if (event.key === 'Escape') {
743
- if (!project || busy || imagePending) return;
744
- event.preventDefault(); handleShortcut('escape'); return;
415
+ function CoachingPanel({ project, selected, blocked, onAdopt, onChoose }) {
416
+ const fieldId=React.useId();
417
+ const L = (zh, en) => languageOf() === 'en' ? en : zh;
418
+ const [mode, setMode] = useState(''), [routes, setRoutes] = useState([]), [route, setRoute] = useState('');
419
+ const [difficulty, setDifficulty] = useState('normal'), [audience, setAudience] = useState('general'), [limit, setLimit] = useState(1);
420
+ const [scope, setScope] = useState('all'), [material, setMaterial] = useState(''), [run, setRun] = useState(null), [history, setHistory] = useState([]);
421
+ const [answer, setAnswer] = useState(''), [patches, setPatches] = useState([]), [backups, setBackups] = useState([]);
422
+ const [busy, setBusy] = useState(false), [error, setError] = useState(''), [notice, setNotice] = useState('');
423
+ const active = useRef(null), alive = useRef(true), current = useRef(null), runRef = useRef(null), reading = useRef(0), routeInitialized = useRef(false);
424
+ current.current = { project, selected, blocked };
425
+ runRef.current = run;
426
+ const stale = !!run && (run.stale || run.revision !== project.revision);
427
+ const maxCalls = mode === 'review' ? limit : limit + 1;
428
+ const modeName = value => value === 'review' ? L('AI 预审', 'AI review') : L('模拟答辩', 'Rehearsal');
429
+ const statusName = value => ({ ready: L('等待下一步', 'Ready'), busy: L('正在调用模型', 'Calling model'), paused: L('已暂停', 'Paused'), complete: L('已结束', 'Finished') })[value] || value;
430
+ const kindName = value => ({ expression: L('表达建议', 'Expression'), logic: L('逻辑问题', 'Logic'), evidence: L('证据缺口', 'Missing evidence') })[value];
431
+ function accept(value) { if (alive.current) {
432
+ runRef.current = value;
433
+ setRun(value);
434
+ } }
435
+ const request = (operation, data = {}, signal) => action({ operation: 'coach-' + operation, id: current.current.project.id, expectedRevision: current.current.project.revision, ...data }, signal);
436
+ async function refresh(signal) { const value = await request('list', {}, signal); if (alive.current)
437
+ setHistory(value.runs); }
438
+ useEffect(() => {
439
+ alive.current = true;
440
+ return () => {
441
+ alive.current = false;
442
+ reading.current++;
443
+ if (active.current) {
444
+ active.current.abort();
445
+ const item = runRef.current;
446
+ if (item)
447
+ void request('stop', { runId: item.id }).catch(() => { });
448
+ }
449
+ };
450
+ }, []);
451
+ useEffect(() => {
452
+ if (!run || run.status !== 'busy' || busy)
453
+ return;
454
+ const controller = new AbortController();
455
+ const timer = setInterval(() => { void request('get', { runId: run.id }, controller.signal).then(value => { if (!controller.signal.aborted)
456
+ accept(value.run); }).catch(() => { }); }, 750);
457
+ return () => { clearInterval(timer); controller.abort(); };
458
+ }, [run?.id, run?.status, busy]);
459
+ async function task(work) {
460
+ if (active.current)
461
+ return;
462
+ const controller = new AbortController();
463
+ active.current = controller;
464
+ setBusy(true);
465
+ setError('');
466
+ setNotice('');
467
+ try {
468
+ await work(controller.signal);
469
+ }
470
+ catch (e) {
471
+ if (!alive.current)
472
+ return;
473
+ if (!controller.signal.aborted)
474
+ setError(e.message || L('操作失败', 'Operation failed'));
475
+ const item = runRef.current;
476
+ if (item) {
477
+ try {
478
+ accept((await request('get', { runId: item.id })).run);
479
+ }
480
+ catch { /* Keep visible results. */ }
481
+ }
482
+ }
483
+ finally {
484
+ if (active.current === controller)
485
+ active.current = null;
486
+ if (alive.current)
487
+ setBusy(false);
488
+ }
489
+ }
490
+ function configure(value) {
491
+ if (active.current || !canLeave())
492
+ return;
493
+ setMode(value);
494
+ setLimit(value === 'review' ? 1 : 3);
495
+ accept(null);
496
+ setPatches([]);
497
+ setBackups([]);
498
+ setAnswer('');
499
+ return task(async (signal) => {
500
+ const results = await Promise.allSettled([request('options', {}, signal), refresh(signal)]);
501
+ if (signal.aborted || !alive.current)
502
+ return;
503
+ const available = results[0];
504
+ if (available.status === 'rejected')
505
+ throw available.reason;
506
+ const models = available.value.routes;
507
+ setRoutes(models);
508
+ const preferred = routeInitialized.current ? undefined : project.modelRoute;
509
+ routeInitialized.current = true;
510
+ setRoute(value => reconcileModelRoute(models, value, preferred));
511
+ if (!models.length)
512
+ setNotice(L('先在 DSH 的模型设置中配置可用模型,再点“刷新模型”。成品仍可直接下载。', 'Configure a model in DSH, then refresh models. Your finished files remain available.'));
513
+ if (results[1].status === 'rejected')
514
+ throw results[1].reason;
515
+ });
516
+ }
517
+ function canLeave() {
518
+ const item = runRef.current, question = item?.questions.at(-1);
519
+ 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?'));
520
+ }
521
+ async function advance(item, signal, response) {
522
+ let next = (await request('step', { runId: item.id, confirmed: true, ...(response === undefined ? {} : { answer: response }) }, signal)).run;
523
+ accept(next);
524
+ // Only this explicit Start click authorizes the configured review rounds.
525
+ while (next.mode === 'review' && next.status === 'ready' && !next.stale && !signal.aborted && current.current.project.revision === next.revision) {
526
+ next = (await request('step', { runId: next.id, confirmed: true }, signal)).run;
527
+ accept(next);
528
+ }
529
+ await refresh(signal);
530
+ if (alive.current && response !== undefined)
531
+ setAnswer('');
532
+ }
533
+ function start() {
534
+ if (current.current.blocked)
535
+ return;
536
+ return task(async (signal) => {
537
+ const model = findModelRoute(routes, route);
538
+ if (!model)
539
+ throw new Error(L('请选择模型', 'Choose a model'));
540
+ reading.current++;
541
+ const item = (await request('create', { confirmed: true, mode, ...model, difficulty, audience, limit, material,
542
+ language: languageOf(), ...(scope === 'current' ? { slideId: current.current.selected } : {}) }, signal)).run;
543
+ accept(item);
544
+ await advance(item, signal);
545
+ });
546
+ }
547
+ function stop() {
548
+ active.current?.abort();
549
+ if (runRef.current)
550
+ void request('stop', { runId: runRef.current.id }).then(value => accept(value.run)).catch(e => { if (alive.current)
551
+ setError(e.message); });
552
+ setNotice(L('已请求停止。已完成的结果保留,本次调用仍可能计费。', 'Stop requested. Completed results are kept; the current call may still be billed.'));
553
+ }
554
+ function finish() { return task(async (signal) => { accept((await request('finish', { runId: run.id }, signal)).run); await refresh(signal); }); }
555
+ function openReport(id) { if (!canLeave())
556
+ 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([]); }); }
557
+ function removeReport() {
558
+ if (!window.confirm(L('删除这次本地演练记录?幻灯片成品不受影响。', 'Delete this local rehearsal record? Presentation files are kept.')))
559
+ return;
560
+ return task(async (signal) => { await request('delete', { runId: run.id }, signal); accept(null); await refresh(signal); });
561
+ }
562
+ function exportReport() {
563
+ const url = new URL('api/dsh-ppt/download', document.baseURI);
564
+ for (const [key, value] of Object.entries({ id: project.id, kind: 'coaching', revision: project.revision, run: run.id }))
565
+ url.searchParams.set(key, String(value));
566
+ const link = document.createElement('a');
567
+ link.href = url.href;
568
+ link.download = '';
569
+ link.hidden = true;
570
+ document.body.append(link);
571
+ link.click();
572
+ link.remove();
573
+ }
574
+ function applySelected() {
575
+ if (current.current.blocked || stale)
576
+ return;
577
+ return task(async (signal) => {
578
+ const value = await request('apply', { runId: run.id, confirmed: true, selected: patches, backup: backups }, signal);
579
+ if (alive.current)
580
+ onAdopt(value.project);
581
+ });
582
+ }
583
+ async function uploadMaterial(event) {
584
+ const file = event.target.files?.[0];
585
+ event.target.value = '';
586
+ if (!file)
587
+ return;
588
+ const ticket = ++reading.current;
589
+ if (!/\.(txt|md)$/i.test(file.name) || file.size > 100000) {
590
+ setError(L('请选择 100 KB 以内的 TXT / Markdown 文件。', 'Choose a TXT / Markdown file up to 100 KB.'));
591
+ return;
592
+ }
593
+ try {
594
+ const value = await file.text();
595
+ if (!alive.current || ticket !== reading.current)
596
+ return;
597
+ if (value.length > 20000)
598
+ throw new Error(L('补充材料最多 20000 字符。', 'Supporting material: up to 20,000 characters.'));
599
+ setMaterial(value);
600
+ setError('');
601
+ }
602
+ catch (e) {
603
+ if (alive.current && ticket === reading.current)
604
+ setError(e.message);
605
+ }
606
+ }
607
+ function toggle(set, values, id) { set(values.includes(id) ? values.filter(v => v !== id) : [...values, id]); }
608
+ function pageButton(id) {
609
+ const index = project.slides.findIndex(s => s.id === id);
610
+ return h('button', { disabled: blocked || index < 0, onClick: () => onChoose(id) }, L('查看第 ' + (index + 1) + ' 页', 'View slide ' + (index + 1)));
611
+ }
612
+ 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.')); }
613
+ const last = run?.questions.at(-1);
614
+ useEffect(() => {
615
+ if (!last || last.feedback || !answer.trim() || answer.trim() === (last.answer || ''))
616
+ return;
617
+ const warn = event => { event.preventDefault(); event.returnValue = ''; };
618
+ window.addEventListener('beforeunload', warn);
619
+ return () => window.removeEventListener('beforeunload', warn);
620
+ }, [run?.id, last?.id, last?.feedback, last?.answer, answer]);
621
+ 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') {
622
+ e.stopPropagation();
623
+ if (e.key.toLowerCase() === 's')
624
+ e.preventDefault();
625
+ } } }, h('h3', null, L('想再准备充分一点?', 'Want to prepare further?')), h('p', { className: 'muted' }, L('成品已可下载。以下两项按需开启,不影响直接交付。', 'Your files are ready to download. Both options below are optional.')), 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')), mode && h('button', { disabled: busy, onClick: () => { if (canLeave()) {
626
+ setMode('');
627
+ accept(null);
628
+ setAnswer('');
629
+ } } }, L('收起', 'Collapse'))), mode && h(React.Fragment, null, error && h('div', { role: 'alert', className: 'notice error' }, error), notice && h('div', { role: 'status', className: 'notice' }, notice), busy && h('div', { role: 'status', className: 'tools' }, L('正在处理…可以继续预览或下载成品。', 'Working… You can still preview or download your presentation.'), h('button', { onClick: stop }, L('停止', 'Stop'))), !run && h(React.Fragment, null, 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.')), h('div', { className: 'coaching-grid' }, h('label', null, L('模型', 'Model'), h('select', { 'aria-label': L('演练模型', 'Rehearsal model'), value: route, disabled: busy, onChange: e => setRoute(e.target.value) }, h('option', { value: '' }, routes.length ? L('请选择模型', 'Choose a model') : L('暂无可用模型', 'No configured model')), routes.map(r => h('option', { key: modelRouteKey(r), value: modelRouteKey(r) }, r.label)))), 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)))), 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)))), 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))))), 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'))))), h('label', { htmlFor: fieldId + '-ppt-coach-material' }, L('补充材料(可选)', 'Supporting material (optional)')), h('textarea', { id: fieldId + '-ppt-coach-material', rows: 3, maxLength: 20000, value: material, disabled: busy, onChange: e => { reading.current++; setMaterial(e.target.value); } }), 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 })), 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.')), h('div', { className: 'tools' }, h('button', { disabled: busy || blocked || !findModelRoute(routes, route), onClick: start }, mode === 'review' ? L('开始 AI 预审', 'Start AI review') : L('开始模拟答辩', 'Start rehearsal')), h('button', { disabled: busy, onClick: () => configure(mode) }, L('刷新模型', 'Refresh models'))), blocked && h('p', { className: 'muted' }, L('请先保存或取消幻灯片修改。', 'Save or cancel slide edits first.'))), run && h(React.Fragment, null, h('h3', null, modeName(run.mode) + ' · ' + statusName(run.status)), h('p', { className: 'muted' }, L('修订 ', 'Revision ') + run.revision + ' · ' + run.route.provider + ' / ' + run.route.model + ' · ' + L('调用 ', 'Calls ') + run.usedCalls + '/' + run.maxCalls), h('p', { className: 'muted' }, L('AI 意见不等于事实核验,也不代表真实听众的评价。请先看原文与改动,再决定是否采纳。', 'AI suggestions are not fact checks or predictions of audience feedback. Compare sources and edits before adopting them.')), 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.')), run.error && h('p', { className: 'muted' }, languageOf() === 'en' ? run.error.split(' / ').at(-1) : run.error.split(' / ')[0]), run.findings.map(f => {
630
+ const slide = project.slides.find(s => s.id === f.slideId);
631
+ return h('article', { key: f.id, className: 'card' }, h('strong', null, kindName(f.kind) + ' · ' + f.issue), h('div', { className: 'tools' }, pageButton(f.slideId)), h('p', null, f.question), h('p', null, f.answer), h('p', null, f.suggestion), source(f), 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)))))), 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'))), 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')));
632
+ }), 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.')), 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), 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')))), run.mode === 'practice' && last && !last.feedback && run.status !== 'complete' && !stale && h(React.Fragment, null, 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) }), h('button', { disabled: busy || blocked || !answer.trim() || run.usedCalls >= run.maxCalls, onClick: () => task(signal => advance(run, signal, answer)) }, L('提交回答,继续', 'Submit answer and continue'))), h('div', { className: 'tools' }, h('button', { disabled: busy, onClick: exportReport }, L('下载问答与材料清单', 'Download Q&A and evidence checklist')), h('button', { disabled: busy || blocked || stale || !(patches.length + backups.length), onClick: applySelected }, L('将所选内容保存为副本', 'Save selected changes as a copy')), run.status !== 'complete' && h('button', { disabled: busy || run.status === 'busy', onClick: finish }, L('结束并整理已有结果', 'Finish with current results')), h('button', { disabled: busy, onClick: () => configure(run.mode) }, L('重新开始', 'Start again')), h('button', { disabled: busy || run.status === 'busy', onClick: removeReport }, L('删除本次记录', 'Delete this record'))), 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.'))), 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')))))));
745
633
  }
746
- if (event.altKey && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
747
- if (!project || busy || dirty || imagePending) return;
748
- event.preventDefault(); handleShortcut(event.key === 'ArrowRight' ? 'next' : 'prev');
634
+ const dataCss = `.pptw .data-workbench{margin-top:18px}.pptw .data-workbench details{margin:12px 0}.pptw .data-workbench summary{cursor:pointer;font-weight:600}.pptw .data-workbench pre,.pptw .data-workbench code{white-space:pre-wrap;overflow-wrap:anywhere;font-size:13px;max-height:220px;overflow:auto}.pptw .data-input-row{margin:15px 0}.pptw .data-input-controls{display:grid;grid-template-columns:minmax(0,1fr) 115px;gap:12px;align-items:center}.pptw .data-input-controls input[type=range]{accent-color:var(--dsw-alias-brand-primary,#2563eb)}.pptw .data-before-after{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:10px}.pptw .data-before-after pre{padding:10px;border:1px solid var(--dsw-alias-divider-default,#b8c0cc);border-radius:8px}.pptw .data-copy{display:flex;gap:8px;align-items:center}.pptw .data-copy input{width:auto}@media(max-width:640px){.pptw .data-before-after{grid-template-columns:minmax(0,1fr)}.pptw .data-input-controls{grid-template-columns:minmax(0,1fr) 100px}}`;
635
+ function VisualPanel({ project, selected, blocked, onBusy, onAdopt }) {
636
+ const L = (zh, en) => languageOf() === 'en' ? en : zh;
637
+ const [expanded, setExpanded] = useState(false), [routes, setRoutes] = useState([]), [route, setRoute] = useState('');
638
+ const [scope, setScope] = useState(project.slides.length > 12 ? 'current' : 'all'), [repairs, setRepairs] = useState(1);
639
+ const [run, setRun] = useState(null), [history, setHistory] = useState([]), [busy, setBusy] = useState(false), [error, setError] = useState('');
640
+ const [compare, setCompare] = useState(''), [pictures, setPictures] = useState({}), [loading, setLoading] = useState(false);
641
+ const active = useRef(null), alive = useRef(true), current = useRef(null), runRef = useRef(null), progressVersion = useRef(0), routeInitialized = useRef(false);
642
+ current.current = { project, selected, blocked };
643
+ runRef.current = run;
644
+ const request = (op, data = {}, signal) => action({ operation: 'visual-' + op, id: current.current.project.id, expectedRevision: current.current.project.revision, ...data }, signal);
645
+ const accept = value => { if (alive.current) {
646
+ progressVersion.current++;
647
+ runRef.current = value;
648
+ setRun(value);
649
+ } };
650
+ const phaseName = value => ({ render: L('正在渲染实际 PPTX', 'Rendering the actual PPTX'), inspect: L('正在看图检查', 'Inspecting rendered slides'), repair: L('正在生成排版副本', 'Creating a formatting copy'), done: L('检查已结束', 'Review finished') })[value] || value;
651
+ const failureText = value => { const split = value.lastIndexOf(' / '); return split < 0 ? value : L(value.slice(0, split), value.slice(split + 3)); };
652
+ const actionName = a => ({ 'title-size': L('标题字号', 'Title size'), 'body-size': L('正文字号', 'Body size'), 'chart-label-size': L('图表字号', 'Chart label size'), 'chart-horizontal': L('改为横向条形图', 'Use horizontal bars'), 'image-contain': L('完整显示图片', 'Show the complete image'), 'split-bullets': L('拆分要点页', 'Split bullet slide'), 'split-table': L('拆分表格页', 'Split table slide') })[a.type] + (a.value !== undefined ? ' · ' + a.value : '');
653
+ useEffect(() => { alive.current = true; return () => { alive.current = false; active.current?.abort(); if (runRef.current && active.current)
654
+ void request('stop', { runId: runRef.current.id }).catch(() => { }); }; }, []);
655
+ useEffect(() => { if (!run || ['complete', 'paused'].includes(run.status) || !busy && run.status !== 'busy')
656
+ return; const abort = new AbortController(), timer = setInterval(() => { const version = progressVersion.current; void request('get', { runId: run.id }, abort.signal).then(v => { if (!abort.signal.aborted && version === progressVersion.current)
657
+ accept(v.run); }).catch(() => { }); }, 1000); return () => { clearInterval(timer); abort.abort(); }; }, [run?.id, run?.status, busy]);
658
+ async function refresh(signal) { const value = await request('list', {}, signal); if (alive.current)
659
+ setHistory(value.runs); }
660
+ async function task(work, lock = false) {
661
+ if (active.current)
662
+ return;
663
+ const controller = new AbortController();
664
+ active.current = controller;
665
+ setBusy(true);
666
+ setError('');
667
+ if (lock)
668
+ onBusy(true);
669
+ try {
670
+ await work(controller.signal);
671
+ }
672
+ catch (e) {
673
+ if (alive.current) {
674
+ if (!controller.signal.aborted)
675
+ setError(e.message || L('视觉检查失败', 'Visual review failed'));
676
+ if (runRef.current)
677
+ try {
678
+ accept((await request('get', { runId: runRef.current.id })).run);
679
+ }
680
+ catch { /* Keep the last checkpoint. */ }
681
+ }
682
+ }
683
+ finally {
684
+ if (active.current === controller)
685
+ active.current = null;
686
+ if (alive.current)
687
+ setBusy(false);
688
+ if (lock)
689
+ onBusy(false);
690
+ }
691
+ }
692
+ function configure() {
693
+ setExpanded(true);
694
+ return task(async (signal) => {
695
+ const results = await Promise.allSettled([request('options', {}, signal), refresh(signal)]);
696
+ if (results[0].status === 'rejected')
697
+ throw results[0].reason;
698
+ if (signal.aborted || !alive.current)
699
+ return;
700
+ const models = results[0].value.routes;
701
+ setRoutes(models);
702
+ const preferred = routeInitialized.current ? undefined : project.modelRoute;
703
+ routeInitialized.current = true;
704
+ setRoute(value => reconcileModelRoute(models, value, preferred));
705
+ if (results[1].status === 'rejected')
706
+ throw results[1].reason;
707
+ });
708
+ }
709
+ function start() {
710
+ if (current.current.blocked)
711
+ return;
712
+ return task(async (signal) => {
713
+ const model = findModelRoute(routes, route);
714
+ if (!model)
715
+ throw new Error(L('请选择支持图片输入的模型', 'Choose an image-capable model'));
716
+ let value = (await request('create', { confirmed: true, ...model, repairs, language: languageOf(), ...(scope === 'current' ? { slideId: current.current.selected } : {}) }, signal)).run;
717
+ accept(value);
718
+ setPictures({});
719
+ setCompare('');
720
+ while (value.status === 'ready' && !signal.aborted) {
721
+ value = (await request('step', { runId: value.id, confirmed: true }, signal)).run;
722
+ accept(value);
723
+ }
724
+ await refresh(signal);
725
+ const last = value.rounds.at(-1);
726
+ if (alive.current && last?.rendered)
727
+ setCompare(last.ids[0]);
728
+ }, true);
729
+ }
730
+ function stop() { active.current?.abort(); if (runRef.current)
731
+ void request('stop', { runId: runRef.current.id }).then(value => accept(value.run)).catch(e => { if (alive.current)
732
+ setError(e.message); }); }
733
+ function open(id) { return task(async (signal) => { const value = (await request('get', { runId: id }, signal)).run; accept(value); setCompare(value.rounds.at(-1)?.rendered ? value.rounds.at(-1).ids[0] : ''); }); }
734
+ function adopt() { if (blocked || !run?.canAdopt)
735
+ return; return task(async (signal) => { const value = await request('adopt', { runId: run.id, confirmed: true }, signal); if (alive.current)
736
+ onAdopt(value.project); }, true); }
737
+ function remove() { if (!window.confirm(L('删除这次检查记录和预览图片?生成的 PPT 副本会保留。', 'Delete this review and its preview images? Presentation copies are kept.')))
738
+ return; return task(async (signal) => { await request('delete', { runId: run.id }, signal); accept(null); setPictures({}); setCompare(''); await refresh(signal); }); }
739
+ function download() { const url = new URL('api/dsh-ppt/download', document.baseURI); for (const [k, v] of Object.entries({ id: project.id, kind: 'visual', revision: project.revision, run: run.id }))
740
+ url.searchParams.set(k, String(v)); const a = document.createElement('a'); a.href = url.href; a.download = ''; document.body.append(a); a.click(); a.remove(); }
741
+ useEffect(() => {
742
+ if (!compare || !run)
743
+ return;
744
+ const abort = new AbortController(), last = run.rounds.length - 1;
745
+ setPictures({});
746
+ setLoading(true);
747
+ const initial = run.rounds[0].ids.includes(compare);
748
+ Promise.allSettled([initial ? request('page', { runId: run.id, round: 0, slideId: compare }, abort.signal) : Promise.resolve(null), request('page', { runId: run.id, round: last, slideId: compare }, abort.signal)]).then(values => {
749
+ if (abort.signal.aborted || !alive.current)
750
+ return;
751
+ setPictures({ before: values[0].status === 'fulfilled' ? values[0].value?.data : null, after: values[1].status === 'fulfilled' ? values[1].value?.data : null });
752
+ const failed = values.find(v => v.status === 'rejected');
753
+ if (failed)
754
+ setError(failed.reason.message);
755
+ setLoading(false);
756
+ });
757
+ return () => abort.abort();
758
+ }, [run?.id, run?.rounds.length, compare]);
759
+ useEffect(() => { const last = run?.rounds.at(-1); if (!busy && !compare && last?.rendered)
760
+ setCompare(last.ids[0]); }, [run?.id, run?.rounds.length, run?.rounds.at(-1)?.rendered, busy, compare]);
761
+ const first = run?.rounds[0], last = run?.rounds.at(-1), stale = run && (run.stale || run.revision !== project.revision), count = scope === 'all' ? project.slides.length : 1;
762
+ const callCap = Array.from({ length: repairs + 1 }, (_, i) => Math.ceil(count * 2 ** i / 2)).reduce((a, b) => a + b, 0);
763
+ function image(src, round, label) { return h('figure', { style: { margin: 0, minWidth: 0 } }, h('figcaption', null, label), src ? h('div', { style: { position: 'relative', lineHeight: 0 } }, h('img', { src, alt: label, style: { width: '100%', height: 'auto', display: 'block' } }), (round?.findings || []).filter(f => f.slideId === compare).map((f, i) => h('span', { key: i, title: f.issue, style: { position: 'absolute', pointerEvents: 'none', border: '2px solid #f97316', boxSizing: 'border-box', left: f.box[0] * 100 + '%', top: f.box[1] * 100 + '%', width: f.box[2] * 100 + '%', height: f.box[3] * 100 + '%' } }))) : h('p', { className: 'muted' }, round === first && !first.ids.includes(compare) ? L('此页由拆分生成,没有对应的原页画面。', 'This page was created by a split and has no original counterpart.') : L('画面尚未载入,请重新选择页面。', 'Image not loaded; select the slide again.'))); }
764
+ return h('section', { className: 'card coaching', 'aria-label': L('视觉检查与修复', 'Visual review and repair') }, h('h3', null, L('让 AI 看完成品,再修排版', 'Let AI inspect the finished slides and repair formatting')), h('p', { className: 'muted' }, L('可选功能。检查实际 PPTX 画面,另存修复副本,再渲染复查。原稿保留。', 'Optional. Inspect actual PPTX images, save a repaired copy, and render it again for rechecking. The original is kept.')), !expanded ? h('button', { disabled: busy || blocked, onClick: configure }, L('视觉检查与修复', 'Visual review and repair')) : h(React.Fragment, null, error && h('div', { role: 'alert', className: 'notice error' }, error), !run && h(React.Fragment, null, h('div', { className: 'coaching-grid' }, h('label', null, L('视觉模型', 'Vision model'), h('select', { 'aria-label': L('视觉模型', 'Vision model'), value: route, disabled: busy, onChange: e => setRoute(e.target.value) }, h('option', { value: '' }, L('请选择', 'Choose a model')), routes.map(m => h('option', { key: modelRouteKey(m), value: modelRouteKey(m) }, m.label)))), h('label', null, L('检查范围', 'Review scope'), h('select', { 'aria-label': L('视觉检查范围', 'Visual review scope'), value: scope, disabled: busy, onChange: e => setScope(e.target.value) }, h('option', { value: 'all', disabled: project.slides.length > 12 }, L('全部页面(最多 12 页)', 'All slides (up to 12)')), h('option', { value: 'current' }, L('当前页', 'Current slide')))), h('label', null, L('自动修复上限', 'Repair limit'), h('select', { 'aria-label': L('自动修复上限', 'Repair limit'), value: repairs, disabled: busy, onChange: e => setRepairs(Number(e.target.value)) }, h('option', { value: 0 }, L('仅看图检查', 'Inspect only')), h('option', { value: 1 }, L('最多修复 1 轮(推荐)', 'Up to 1 repair round (recommended)')), h('option', { value: 2 }, L('最多修复 2 轮', 'Up to 2 repair rounds'))))), !routes.length && h('p', { className: 'notice' }, L('未找到声明支持图片输入的模型。请在 DSH 模型设置中检查图片输入配置;普通生成和下载仍可使用。', 'No model declares image input. Check the image-input configuration in DSH model settings; normal creation and downloads remain available.')), h('p', null, L('会向所选模型发送 ' + count + ' 页的渲染图片和页面文字;拆页后会重新检查新增页面,最多 ' + callCap + ' 次模型调用。', 'Sends rendered images and text from ' + count + ' slides to the selected model. New split pages are rechecked, with up to ' + callCap + ' model calls.')), h('p', { className: 'muted' }, L('只调整字号、拆页、图表方向和图片裁切,不改写原文、数字或公式。可随时停止;服务商仍可能收取已发起调用的费用。', 'Changes font sizes, pagination, chart orientation and image cropping. Original text, numbers and formulas are preserved. You can stop at any time; calls already sent may still be billed.')), h('div', { className: 'tools' }, h('button', { className: 'primary', disabled: busy || blocked || !findModelRoute(routes, route) || count > 12, onClick: start }, L('开始看图检查', 'Start visual review')), h('button', { disabled: busy, onClick: configure }, L('刷新视觉模型', 'Refresh vision models')))), run && h(React.Fragment, null, h('p', { role: 'status' }, (run.status === 'paused' ? L('检查已停止', 'Review stopped') : run.status === 'ready' && !busy ? L('等待检查', 'Review ready') : phaseName(run.phase)) + ' · ' + L('已调用 ', 'Calls ') + run.usedCalls + '/' + run.maxCalls + ' · ' + L('本轮已检查 ', 'Slides checked this pass ') + (last?.cursor || 0) + '/' + (last?.ids.length || 0)), busy && h('button', { onClick: stop }, L('停止视觉检查', 'Stop visual review')), run.error && h('p', { role: 'alert', className: 'notice error' }, failureText(run.error)), stale && h('p', { className: 'notice' }, L('工程或成品已变化,旧记录可查看,但不能继续或采纳。', 'The project or output changed. This old record is readable, but cannot be continued or adopted.')), run.status === 'complete' && h('p', { className: 'notice' }, last.findings.length ? L('复查仍有 ' + last.findings.length + ' 个问题,请查看标记和说明。', 'Recheck still found ' + last.findings.length + ' issues. Review the highlighted regions and notes.') : L('AI 在本次范围内未发现明显视觉问题;这是一份模型检查记录。', 'AI found no obvious visual issues in this scope. This is a model review record.')), (last?.missingFonts || []).length > 0 && h('p', { className: 'notice error' }, L('渲染引擎报告缺失字体:', 'Renderer reported missing fonts: ') + last.missingFonts.join(', ')), run.rounds.map((r, i) => h('details', { key: i, open: i === run.rounds.length - 1 }, h('summary', null, L('检查轮次 ', 'Inspection pass ') + i + ' · ' + r.cursor + '/' + r.ids.length), r.findings.map((f, j) => h('p', { key: j }, h('strong', null, (project.slides.findIndex(s => s.id === f.slideId) >= 0 ? L('原第 ' + (project.slides.findIndex(s => s.id === f.slideId) + 1) + ' 页', 'Original slide ' + (project.slides.findIndex(s => s.id === f.slideId) + 1)) : L('拆分页', 'Split page')) + ' · '), f.issue, h('br'), h('small', { className: 'muted' }, f.action ? actionName(f.action) : L('需要人工判断', 'Needs manual review')))), r.applied.length > 0 && h('ul', null, r.applied.map((a, j) => h('li', { key: j }, L('已应用:', 'Applied: ') + actionName(a)))))), !busy && last?.rendered && h(React.Fragment, null, h('label', null, L('查看前后画面(橙框为 AI 定位区域)', 'Compare images (orange boxes mark AI findings)'), h('select', { 'aria-label': L('对比页面', 'Comparison slide'), value: compare, onChange: e => setCompare(e.target.value) }, last.ids.map((id, i) => h('option', { value: id, key: id }, String(i + 1) + '. ' + (project.slides.find(s => s.id === id)?.title || L('拆分页', 'Split page')))))), loading ? h('p', { role: 'status' }, L('正在载入画面…', 'Loading images…')) : h('div', { className: 'before-after' }, image(pictures.before, first, L('原稿 · 实际 PPTX', 'Original · actual PPTX')), image(pictures.after, last, run.rounds.length > 1 ? L('修复后 · 实际 PPTX', 'Repaired · actual PPTX') : L('本次检查画面', 'Reviewed image')))), h('div', { className: 'tools' }, h('button', { className: 'primary', disabled: busy || blocked || !run.canAdopt || stale, onClick: adopt }, last?.findings.length ? L('打开修复副本(仍有待处理问题)', 'Open repaired copy (issues remain)') : L('采用修复副本', 'Use repaired copy')), h('button', { disabled: busy, onClick: download }, L('下载视觉检查记录', 'Download visual review')), h('button', { disabled: busy || run.status === 'busy', onClick: remove }, L('删除检查记录', 'Delete review')), h('button', { disabled: busy, onClick: () => { accept(null); setCompare(''); setPictures({}); configure(); } }, L('新建视觉检查', 'New visual review')))), !busy && history.length > 0 && h('details', null, h('summary', null, L('本机视觉检查历史', 'Local visual review history')), h('div', { className: 'project-list' }, history.map(item => h('button', { key: item.id, onClick: () => open(item.id) }, L('修订 ', 'Revision ') + item.revision + ' · ' + new Date(item.createdAt).toLocaleString(languageOf() === 'en' ? 'en-US' : 'zh-CN'))))), h('button', { disabled: busy, onClick: () => setExpanded(false) }, L('收起视觉检查', 'Collapse visual review'))));
749
765
  }
750
- }
751
- document.addEventListener('keydown', onKey);
752
- return () => document.removeEventListener('keydown', onKey);
753
- }, [project, dirty, busy, imagePending, index, selected, draft, image, dataDirty]);
754
- useEffect(() => {
755
- if (!dirty && !dataDirty) return;
756
- function warn(event) { event.preventDefault(); event.returnValue = t("有未保存修改,离开页面会丢失。"); }
757
- window.addEventListener('beforeunload', warn);
758
- return () => window.removeEventListener('beforeunload', warn);
759
- }, [dirty,dataDirty]);
760
- function open(id) { return perform(signal => action({ operation: 'open', id }, signal), value => { adopt(value.project); setMessage(t("点击预览里的文字,或在下方修改字段。")); }); }
761
- function keepInputsAndReload() {
762
- const original = draftFor(slide), keys = fields.filter(([key]) => draft[key] !== original[key]).map(([key]) => key), pending = { ...draft }, pendingImage = image;
763
- return perform(signal => action({ operation: 'open', id: project.id }, signal), value => {
764
- const row = value.project.slides.find(s => s.id === selected);
765
- if (!row) { setError(t("当前页已被删除,输入仍保留,请复制需要的内容后取消修改。")); return; }
766
- const latest = draftFor(row), merged = { ...latest }, shared = [];
767
- 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] }); }
768
- adopt(value.project, selected); setDraft(merged); setImage(pendingImage); setDirty(keys.length > 0 || !!pendingImage); setOverlaps(shared);
769
- setMessage(t("已载入最新版本并保留你的修改,请核对后再保存。"));
770
- });
771
- }
772
- function choose(row) { if (dirty || busy) return; imageLoader.current.cancel(); setSelected(row.id); setDraft(draftFor(row)); setImage(null); setMessage(''); }
773
- function save(saveAs = false) {
774
- if(dataDirty)return;
775
- const original = draftFor(slide), patch = {};
776
- 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];
777
- if (image) patch.image = { src: image.src, alt: image.alt, fit: image.fit, caption: image.caption };
778
- return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, slide: slide.id, patch, saveAs }, signal), value => {
779
- adopt(value.project, slide.id); setMessage(saveAs ? t("副本已保存,原文件保留。副本从工程生成,不包含 Office 手工修改。") : value.changed === false ? t("内容没有变化。") : t("已保存,HTML、PPTX 和工程文件已同步更新。"));
780
- });
781
- }
782
- function move(delta) {
783
- if(dataDirty)return;
784
- const order = project.slides.map(s => s.id); [order[index], order[index + delta]] = [order[index + delta], order[index]];
785
- return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, order }, signal), value => { adopt(value.project, slide.id); setMessage(t("页面顺序已更新,可撤销。")); });
786
- }
787
- function structure(operation) {
788
- if(dataDirty)return;
789
- return perform(signal => action({ operation, id: project.id, expectedRevision: project.revision, slide: slide.id }, signal), value => {
790
- adopt(value.project, value.selected);
791
- setMessage(operation === 'duplicate' ? t("页面已复制,图片、图表和备注一并保留,可撤销。") : t("页面已删除,可撤销。"));
792
- });
793
- }
794
- function undo() { if(dataDirty)return;return perform(signal => action({ operation: 'undo', id: project.id, expectedRevision: project.revision }, signal), value => { adopt(value.project, selected); setMessage(t("已撤销上次修改。")); }); }
795
- function render() {
796
- if(dataDirty)return;
797
- 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,较大文件可能需要几分钟…"));
798
- }
799
- function download(kind) {
800
- if(dataDirty)return;
801
- const url = new URL('api/dsh-ppt/download', document.baseURI);
802
- url.searchParams.set('id', project.id); url.searchParams.set('kind', kind); url.searchParams.set('revision', String(project.revision));
803
- // An authenticated attachment response keeps the click's user gesture and
804
- // works in WebViews whose native download handler cannot read blob URLs.
805
- const link = document.createElement('a'); link.href = url.href; link.download = '';
806
- link.hidden = true; document.body.append(link); link.click(); link.remove();
807
- setMessage(t("已请求下载,请查看浏览器的下载列表。"));
808
- }
809
- function copyExample() {
810
- const text = t("示例:请把这份材料制作成可直接交付的演示文稿,生成 HTML、PPTX 和工程文件。");
811
- try { navigator.clipboard?.writeText(text).then(() => setMessage(t("已复制示例"))).catch(() => {}); } catch (_) { /* ignore */ }
812
- }
813
- function upload(event) {
814
- const file = event.target.files?.[0]; event.target.value = ''; if (!file) return;
815
- imageLoader.current.cancel(); setMessage(''); setError('');
816
- if (!['image/png', 'image/jpeg'].includes(file.type) || file.size > 5 * 1024 * 1024) { setError(t("请选择 5 MiB 以内的 PNG 或 JPEG 图片。")); return; }
817
- imageLoader.current.read(file, data => {
818
- if (!alive.current) return;
819
- setImage({ src: data, alt: slide.image?.alt || file.name.replace(/\.[^.]+$/, ''), caption: slide.image?.caption || '', fit: slide.image?.fit || 'contain', name: file.name });
820
- setDirty(true); setError(''); setMessage(t("图片已载入,保存后生效。"));
821
- }, () => { if (alive.current) { setError(t("无法读取图片,请重试。")); setMessage(''); } });
822
- if (imageLoader.current.pending) setMessage(t("正在读取图片,切换页面会取消本次读取。"));
823
- }
824
- const currentImage = image?.src || (slide?.image?.assetId && project.assets[slide.image.assetId]?.data);
825
- return h('div', { className: 'pptw', 'aria-busy': busy ? 'true' : undefined }, h('style', null, css),
826
- h('h2', null, t("演示文稿编辑")), h('p', { className: 'muted' }, t("修改本插件生成的成品,保存时同步更新 HTML、可编辑 PPTX 和工程文件。")),
827
- h('p', { className: 'muted' }, t("快捷键:Ctrl/⌘+S 保存 · Esc 取消或返回 · Alt+←/→ 切换页面")),
828
- error && h('div', { role: 'alert', className: 'notice error' }, error, ' ', h('button', { disabled: busy || dataDirty, onClick: () => project ? open(project.id) : refreshList() }, t("重试"))),
829
- conflict && project && h('button', { disabled: busy || dataDirty, onClick: keepInputsAndReload }, t("载入最新版本,保留我的输入")),
830
- message && h('div', { role: 'status', className: 'notice' }, message),
831
- busy && h('div', { role: 'status', className: 'muted' }, job),
832
- !project ? h(React.Fragment, null,
833
- h('div', { className: 'tools' }, h('button', { onClick: refreshList, disabled: busy }, t("刷新项目"))),
834
- 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)))) :
835
- 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("复制示例"))))
836
- ) : h(React.Fragment, null,
837
- h('div', { className: 'tools' }, h('button', { disabled: busy || dirty || dataDirty, onClick: () => { imageLoader.current.cancel(); setImage(null); setProject(null); refreshList(); } }, t("返回项目")), h('strong', null, project.title), (dirty||dataDirty) && h('span', { className: 'badge-dirty', role: 'status' }, t("未保存")), h('span', { className: 'muted' }, project.slides.length + t(" 页 · 修订 ") + project.revision)),
838
- h('div', { className: 'layout' },
839
- 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("未命名页"))))),
840
- h('div', { className: 'tools' }, h('button', { disabled: busy || dirty || imagePending || dataDirty || index === 0, onClick: () => move(-1) }, t("上移")), h('button', { disabled: busy || dirty || imagePending || dataDirty || index === project.slides.length - 1, onClick: () => move(1) }, t("下移")),
841
- h('button', { disabled: busy || dirty || imagePending || dataDirty || project.slides.length >= 120, onClick: () => structure('duplicate') }, t("复制本页")),
842
- h('button', { disabled: busy || dirty || imagePending || dataDirty || project.slides.length <= 1, onClick: () => structure('remove') }, t("删除本页")))),
843
- h('div', null,
844
- h('div', { className: 'tools' }, h('button', { disabled: busy || dataDirty, 'aria-pressed': mode === 'html', onClick: () => setMode('html') }, t("HTML 预览")),
845
- h('button', { disabled: busy || dataDirty || !project.render, 'aria-pressed': mode === 'pptx', onClick: () => setMode('pptx') }, t("最终 PPTX 预览")),
846
- h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: render }, t("渲染当前 PPTX"))),
847
- 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("正在载入当前页渲染…"))),
848
- h('p', { className: 'muted' }, mode === 'html' ? t("这是 HTML 放映预览。最终 PPTX 的字体和排版请用上方渲染检查。点击文字可定位编辑字段。") : t("这是当前 PPTX 文件的实际渲染图片,仍需检查每页画面;PowerPoint / WPS 可能因字体环境而不同。")),
849
- project.render?.missingFonts?.length ? h('div', { role: 'alert', className: 'notice error' }, t("渲染引擎报告缺失字体:") + project.render.missingFonts.join('、') + t("。请替换为目标电脑可用字体后重新渲染。")) : null,
850
- h('div', { className: 'card' }, h('h3', null, t("编辑第 ") + (index + 1) + t(" 页")),
851
- dirty && h('p', { className: 'dirty' }, t("有未保存修改,请先保存或取消,再切换页面。")),
852
- 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,
853
- fields.filter(([key]) => key === 'title' || key === 'notes' || key === 'bullets' && (slide.layout === 'bullets' || slide.bullets?.length > 0) || key !== 'bullets' && (slide[key] || key === 'subtitle' && ['cover','section','closing','quote'].includes(slide.layout) || key === 'kicker' && ['cover','section','closing'].includes(slide.layout))).map(([key, label]) => h('div', { key }, h('label', { htmlFor: 'pptw-' + key }, t(label)), h(key === 'title' || key === 'kicker' ? 'input' : 'textarea', { id: 'pptw-' + key, ref: el => { fieldRefs.current[key] = el }, disabled: busy || dataDirty, value: draft[key] || '', rows: key === 'bullets' ? 4 : 2, maxLength: 8000, onChange: e => { setDraft({ ...draft, [key]: e.target.value }); setDirty(true); } }))),
854
- h('label', { htmlFor: 'pptw-image' }, slide.image ? t("替换图片(PNG / JPEG)") : t("添加图片(会改为图文布局)")),
855
- h('input', { id: 'pptw-image', type: 'file', accept: 'image/png,image/jpeg', disabled: busy || dataDirty, onChange: upload }),
856
- currentImage && h('img', { className: 'image-preview', src: currentImage, alt: image?.alt || slide.image?.alt || t("当前图片") }),
857
- image && h(React.Fragment, null, h('p', { className: 'muted' }, t("已选择:") + image.name), h('label', { htmlFor: 'pptw-alt' }, t("图片说明")), h('input', { id: 'pptw-alt', value: image.alt, disabled: busy || dataDirty, onChange: e => setImage({ ...image, alt: e.target.value }) }), h('label', { htmlFor: 'pptw-fit' }, t("图片适应方式")), h('select', { id: 'pptw-fit', value: image.fit, disabled: busy || dataDirty, onChange: e => setImage({ ...image, fit: e.target.value }) }, h('option', { value: 'contain' }, t("完整显示")), h('option', { value: 'cover' }, t("填满并裁切")))),
858
- h('div', { className: 'tools' }, h('button', { className: 'primary', 'aria-keyshortcuts': 'Control+S Meta+S', disabled: busy || dataDirty || imagePending || !dirty, onClick: () => save() }, t("保存此页")), h('button', { 'aria-keyshortcuts': 'Control+Shift+S Meta+Shift+S', disabled: busy || dataDirty || imagePending, onClick: () => save(true) }, t("另存副本")), h('button', { 'aria-keyshortcuts': 'Escape', disabled: busy || (!dirty && !imagePending), onClick: () => { imageLoader.current.cancel(); setDraft(draftFor(slide)); setImage(null); setDirty(false); setError(''); setMessage(''); setConflict(false); setOverlaps([]); } }, t("取消修改")), h('button', { disabled: busy || dirty || imagePending || dataDirty || !project.undoAvailable, onClick: undo }, t("撤销上次修改")))),
859
- 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)))),
860
- h('p', { className: 'muted' }, t("成品包包含 PPTX、HTML 和工程文件。请先保存修改,再下载最新版本。")),
861
- h('div', { className: 'tools' }, h('button', { className: 'primary', disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('bundle') }, t("下载成品包 ZIP")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('pptx') }, t("下载最新 PPTX")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('html') }, t("下载 HTML")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('notes') }, t("下载讲稿 Markdown")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('json') }, t("备份工程"))),
862
- project.dataModel&&mode!=='html'&&h('p',{className:'notice'},languageOf()==='en'?'Switch to HTML preview to adjust assumptions and inspect live data.':'切换到 HTML 预览后可调整假设并查看数据联动。'),
863
- project.dataModel&&h(DataPanel,{key:project.id+':'+project.revision,project,blocked:busy||dirty||imagePending||mode!=='html',incoming:incomingData,
864
- onParameters:parameters=>frame.current?.contentWindow?.postMessage({type:'dsh-ppt-data-set',nonce:nonce.current,parameters,command:++dataCommand.current},'*'),onDirty:setDataDirty,onBusy:value=>{setBusy(value);setJob(languageOf()==='en'?'Updating presentation data…':'正在核对并更新数据…');},
865
- onAdopt:next=>{adopt(next,selected);setMessage(languageOf()==='en'?'Saved confirmed data. HTML, PPTX and project are synchronized; undo is available.':'已保存确认后的数据,HTML、PPTX 和工程已同步,可撤销。');},onChoose:id=>choose(project.slides.find(s=>s.id===id)),onDownload:download}),
866
- h(VisualPanel,{key:'visual:'+project.id,project,selected,blocked:busy||dirty||imagePending||dataDirty,
867
- onBusy:value=>{setBusy(value);setJob(languageOf()==='en'?'Reviewing rendered slides…':'正在检查和复查实际 PPTX 画面…');},
868
- onAdopt:next=>{adopt(next,selected);setMode(next.render?'pptx':'html');setMessage(languageOf()==='en'?'Opened the repaired copy. The original is kept, and formatting changes can be undone.':'已打开修复副本,原稿保留,可撤销排版修改。');}}),
869
- h(CoachingPanel, { key: project.id, project, selected, blocked: busy || dirty || imagePending || dataDirty,
870
- onChoose: id => { choose(project.slides.find(s => s.id === id)); previewBox.current?.scrollIntoView({ behavior: 'smooth', block: 'center' }); },
871
- 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.' : '已保存为新副本,原稿保留;可在当前副本中撤销采纳的修改。'); } })
872
- )
873
- )
874
- )
875
- );
876
- }
877
- function apply(ctx) {
878
- try { localeService = ctx.get?.('locale') || ctx.locale; } catch { localeService = ctx.locale; }
879
- ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: 'dsh-ppt', order: 58, label: () => t("演示文稿"), inject: () => ({ locale: localeService }) }, __withFirstRun(Workbench)));
880
- }
881
- return { inject: ['slots', 'locale'], apply, __internals: { draftFor, editorHtml, createImageLoader, modelRouteKey, findModelRoute, reconcileModelRoute } };
882
- } });
766
+ function DataPanel({ project, blocked, incoming, onParameters, onDirty, onBusy, onAdopt, onChoose, onDownload }) {
767
+ const fieldId=React.useId();
768
+ const L = (zh, en) => languageOf() === 'en' ? en : zh, model = project.dataModel;
769
+ const baseline = Object.fromEntries(model.metrics.filter(m => m.kind === 'input').map(m => [m.id, String(m.value)]));
770
+ const [parameters, setParameters] = useState(baseline), [updates, setUpdates] = useState({}), [sourceId, setSourceId] = useState(model.sources[0]?.id || '');
771
+ const [metricId, setMetricId] = useState(model.metrics[0]?.id || ''), [preview, setPreview] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState(false), [valid, setValid] = useState(true), [saveAs, setSaveAs] = useState(true), [readingFile, setReadingFile] = useState(false);
772
+ const pending = useRef(null), alive = useRef(true), reading = useRef(0), latest = useRef(''), guard = useRef(false);
773
+ const numeric = Object.fromEntries(Object.entries(parameters).map(([id, value]) => [id, value.trim() === '' ? null : Number(value)]));
774
+ const inputsValid = model.metrics.filter(m => m.kind === 'input').every(m => typeof numeric[m.id] === 'number' && Number.isFinite(numeric[m.id]) && numeric[m.id] >= m.min && numeric[m.id] <= m.max && Math.abs((numeric[m.id] - m.min) / m.step - Math.round((numeric[m.id] - m.min) / m.step)) <= 1e-6);
775
+ const body = { parameters: numeric, sourceUpdates: Object.values(updates) }, signature = JSON.stringify(body);
776
+ latest.current = signature;
777
+ const changed = readingFile || !valid || Object.entries(baseline).some(([id, value]) => Number(parameters[id]) !== Number(value) || parameters[id].trim() === '') || Object.keys(updates).length > 0;
778
+ useEffect(() => { onDirty(changed); return () => onDirty(false); }, [changed]);
779
+ useEffect(() => { setPreview(null); }, [signature]);
780
+ useEffect(() => { if (incoming) {
781
+ setParameters(Object.fromEntries(Object.entries(incoming.parameters).map(([id, value]) => [id, Number.isFinite(value) ? String(value) : ''])));
782
+ setValid(incoming.valid !== false);
783
+ } }, [incoming]);
784
+ useEffect(() => { alive.current = true; return () => { alive.current = false; reading.current++; pending.current?.abort(); onBusy(false); }; }, []);
785
+ function changeParameter(id, value) { const next = { ...parameters, [id]: value }; setParameters(next); setValid(true); setPreview(null); setError(''); onParameters(Object.fromEntries(Object.entries(next).map(([key, raw]) => [key, raw.trim() === '' ? NaN : Number(raw)]))); }
786
+ function reset() { reading.current++; setParameters(baseline); setUpdates({}); setPreview(null); setError(''); setValid(true); onParameters(Object.fromEntries(Object.entries(baseline).map(([id, value]) => [id, Number(value)]))); }
787
+ async function task(work) {
788
+ if (guard.current || blocked || readingFile)
789
+ return;
790
+ guard.current = true;
791
+ setBusy(true);
792
+ onBusy(true);
793
+ setError('');
794
+ const controller = new AbortController();
795
+ pending.current = controller;
796
+ try {
797
+ await work(controller.signal);
798
+ }
799
+ catch (reason) {
800
+ if (alive.current && !controller.signal.aborted)
801
+ setError(reason.message || L('操作失败', 'Operation failed'));
802
+ }
803
+ finally {
804
+ pending.current = null;
805
+ guard.current = false;
806
+ if (alive.current) {
807
+ setBusy(false);
808
+ onBusy(false);
809
+ }
810
+ }
811
+ }
812
+ function inspect() { const sent = signature; return task(async (signal) => { const value = await action({ operation: 'data-preview', id: project.id, expectedRevision: project.revision, ...body }, signal); if (alive.current && latest.current === sent)
813
+ setPreview({ ...value, signature: sent }); }); }
814
+ function apply() { if (!preview || preview.signature !== signature)
815
+ return; const sent = signature; return task(async (signal) => { const value = await action({ operation: 'data-apply', id: project.id, expectedRevision: project.revision, ...body, confirmed: true, previewToken: preview.token, saveAs }, signal); if (alive.current && latest.current === sent) {
816
+ onDirty(false);
817
+ onAdopt(value.project);
818
+ } }); }
819
+ async function importSource(event) {
820
+ const file = event.target.files?.[0];
821
+ event.target.value = '';
822
+ if (!file)
823
+ return;
824
+ const stamp = ++reading.current, target = sourceId;
825
+ if (file.size > 1024 * 1024 || !['csv', 'tsv', 'txt', 'md'].includes(file.name.split('.').at(-1)?.toLowerCase())) {
826
+ setError(L('请选择 1 MiB 内的 CSV、TSV、TXT 或 Markdown。', 'Choose CSV, TSV, TXT or Markdown up to 1 MiB.'));
827
+ return;
828
+ }
829
+ setReadingFile(true);
830
+ try {
831
+ const content = await file.text();
832
+ if (!alive.current || stamp !== reading.current)
833
+ return;
834
+ const ext = file.name.split('.').at(-1).toLowerCase();
835
+ setUpdates(old => ({ ...old, [target]: { id: target, format: ext === 'csv' || ext === 'tsv' ? ext : 'text', content } }));
836
+ setPreview(null);
837
+ setError('');
838
+ }
839
+ catch {
840
+ if (alive.current)
841
+ setError(L('无法读取材料,请重试。', 'Could not read source. Try again.'));
842
+ }
843
+ finally {
844
+ if (alive.current)
845
+ setReadingFile(false);
846
+ }
847
+ }
848
+ async function importScenario(event) {
849
+ const file = event.target.files?.[0];
850
+ event.target.value = '';
851
+ if (!file)
852
+ return;
853
+ const stamp = ++reading.current;
854
+ setReadingFile(true);
855
+ try {
856
+ if (file.size > 32000)
857
+ throw new Error(L('推演参数文件过大。', 'Scenario parameter file is too large.'));
858
+ const packet = JSON.parse(await file.text());
859
+ if (!alive.current || stamp !== reading.current)
860
+ return;
861
+ if (packet.schemaVersion !== 1 || packet.deckId !== project.deckId || packet.revision !== project.revision || packet.fingerprint !== model.fingerprint || !packet.parameters || typeof packet.parameters !== 'object' || Array.isArray(packet.parameters) || Object.keys(packet.parameters).some(id => !Object.hasOwn(baseline, id)) || Object.values(packet.parameters).some(value => typeof value !== 'number' || !Number.isFinite(value)))
862
+ throw new Error(L('参数来自其他工程、旧版本或格式无效,请重新导出。', 'Scenario is stale, belongs to another project, or is invalid. Export it again.'));
863
+ const next = { ...baseline, ...Object.fromEntries(Object.entries(packet.parameters).map(([id, value]) => [id, String(value)])) };
864
+ setParameters(next);
865
+ setValid(true);
866
+ setPreview(null);
867
+ onParameters(Object.fromEntries(Object.entries(next).map(([id, value]) => [id, Number(value)])));
868
+ setError('');
869
+ }
870
+ catch (reason) {
871
+ if (alive.current)
872
+ setError(reason.message);
873
+ }
874
+ finally {
875
+ if (alive.current)
876
+ setReadingFile(false);
877
+ }
878
+ }
879
+ const metric = model.metrics.find(m => m.id === metricId), source = model.sources.find(s => s.id === sourceId), replacement = updates[sourceId];
880
+ const format = (value, m) => new Intl.NumberFormat(languageOf() === 'en' ? 'en-US' : 'zh-CN', { style: m.format.style === 'percent' ? 'percent' : 'decimal', minimumFractionDigits: m.format.digits, maximumFractionDigits: m.format.digits }).format(value) + (m.format.unit || '');
881
+ const display = value => typeof value === 'string' ? value : JSON.stringify(value, null, 2), disabled = busy || blocked || readingFile;
882
+ return h('section', { className: 'card data-workbench', 'aria-label': L('数据溯源与现场推演', 'Data lineage and what-if') }, h('style', null, dataCss), h('h3', null, L('数据溯源与现场推演', 'Data lineage and what-if')), h('p', { className: 'muted' }, L('点预览中的数字可追问来源。只有明确声明的假设可调;来源不等于事实已核验。', 'Click numbers in the preview to inspect their lineage. Only declared assumptions are adjustable. Lineage is not factual verification.')), h('details', null, h('summary', null, L('数字来自哪里', 'Where the numbers come from')), h('label', null, L('指标', 'Metric'), h('select', { value: metricId, disabled, onChange: event => setMetricId(event.target.value) }, model.metrics.map(m => h('option', { key: m.id, value: m.id }, m.label + ' [' + m.id + ']')))), metric && h('div', { className: 'data-evidence' }, h('strong', null, metric.label + ' = ' + format(model.values[metric.id], metric)), metric.kind === 'source' ? h(React.Fragment, null, h('p', null, metric.evidence.name + ' · ' + metric.evidence.locator), h('pre', null, metric.evidence.excerpt), h('details', null, h('summary', null, L('来源快照校验值', 'Source snapshot checksum')), h('code', null, metric.evidence.sha256))) : metric.kind === 'input' ? h('p', null, L('用户假设', 'User assumption') + (metric.note ? ' · ' + metric.note : '')) : h(React.Fragment, null, h('pre', null, '= ' + metric.formula), h('div', { className: 'tools' }, metric.dependencies.map(id => h('button', { key: id, disabled, onClick: () => setMetricId(id) }, model.metrics.find(m => m.id === id).label))))), h('button', { disabled: disabled || changed, onClick: () => onDownload('data') }, L('下载溯源与假设报告', 'Download lineage and assumptions'))), model.metrics.some(m => m.kind === 'input') && h('details', { open: true }, h('summary', null, L('现场推演参数', 'What-if assumptions')), model.metrics.filter(m => m.kind === 'input').map(m => h('div', { key: m.id, className: 'data-input-row' }, h('label', { htmlFor: fieldId + '-ppt-data-' + m.id }, m.label, h('small', { className: 'muted' }, ' · ' + L('假设', 'Assumption') + (m.note ? ' · ' + m.note : ''))), h('div', { className: 'data-input-controls' }, h('input', { type: 'range', min: m.min, max: m.max, step: m.step, value: Number(parameters[m.id]), disabled, 'aria-label': m.label + ' ' + L('滑杆', 'slider'), onChange: event => changeParameter(m.id, event.target.value) }), h('input', { id: fieldId + '-ppt-data-' + m.id, type: 'number', min: m.min, max: m.max, step: m.step, value: parameters[m.id], disabled, onChange: event => changeParameter(m.id, event.target.value) })))), h('label', null, L('导入离线 HTML 保存的推演参数', 'Import scenario parameters saved in offline HTML'), h('input', { type: 'file', accept: '.json,application/json', disabled, onChange: importScenario }))), model.sources.length > 0 && h('details', null, h('summary', null, L('更新来源材料', 'Update source material')), h('p', { className: 'muted' }, L('先导入或粘贴新材料,预览影响后再确认;不会自动监视或修改原文件。表格可从 Excel 导出 CSV。', 'Import or paste new material, then preview the impact before confirming. Original source files are not watched or modified. Export Excel tables as CSV.')), h('label', null, L('替换来源', 'Replace source'), h('select', { value: sourceId, disabled, onChange: event => setSourceId(event.target.value) }, model.sources.map(s => h('option', { key: s.id, value: s.id }, s.name)))), h('label', null, L('导入替换材料', 'Import replacement material'), h('input', { type: 'file', accept: source?.kind === 'table' ? '.csv,.tsv' : '.txt,.md', disabled, onChange: importSource })), source?.kind === 'table' && h('label', null, L('分隔格式', 'Delimiter format'), h('select', { value: replacement?.format || 'csv', disabled, onChange: event => { setUpdates(old => ({ ...old, [sourceId]: { id: sourceId, format: event.target.value, content: replacement?.content || '' } })); setPreview(null); } }, h('option', { value: 'csv' }, 'CSV'), h('option', { value: 'tsv' }, 'TSV'))), h('label', null, L('或粘贴内容', 'Or paste content'), h('textarea', { rows: 4, maxLength: 1048576, value: replacement?.content ?? '', disabled, onChange: event => { setUpdates(old => ({ ...old, [sourceId]: { id: sourceId, format: source.kind === 'table' ? replacement?.format || 'csv' : 'text', content: event.target.value } })); setPreview(null); setError(''); } })), replacement && h('button', { disabled, onClick: () => { setUpdates(old => { const next = { ...old }; delete next[sourceId]; return next; }); setPreview(null); } }, L('取消此来源更新', 'Cancel this source update'))), changed && h('p', { className: 'dirty', role: 'status' }, L('推演或材料尚未保存,当前 PPTX 仍是已保存版本。先预览差异并确认,或恢复参数后下载。', 'Unsaved scenario or source changes. The PPTX still contains saved values. Preview and confirm, or reset before downloading.')), (!valid || !inputsValid) && h('p', { className: 'notice error', role: 'alert' }, L('参数无法计算,请检查范围、步长或除零,再恢复或修改。', 'Cannot calculate these parameters. Check ranges, steps or division by zero; adjust or reset.')), error && h('p', { className: 'notice error', role: 'alert' }, error), h('div', { className: 'tools' }, h('button', { disabled: disabled || !changed || !valid || !inputsValid, onClick: inspect }, L('预览差异', 'Preview changes')), h('button', { disabled: disabled || !changed, onClick: reset }, L('恢复已保存数据', 'Reset to saved data'))), preview && preview.signature === signature && h('div', { className: 'data-diff' }, h('h4', null, L('确认前核对', 'Review before confirming')), !preview.changed ? h('p', null, L('内容没有变化。', 'No content changes.')) : h(React.Fragment, null, h('ul', null, preview.changes.map(change => h('li', { key: change.id }, h('strong', null, change.label + ': '), change.beforeText + ' → ' + change.afterText, change.before === change.after && ' · ' + L('来源已更新', 'Source updated')))), h('h4', null, L('受影响页面', 'Affected slides')), !preview.affectedSlides.length && h('p', { className: 'muted' }, L('指标尚未绑定到页面,只更新数据模型。', 'Metrics are not bound to slides; only the data model changes.')), preview.affectedSlides.map(slide => h('details', { key: slide.id }, h('summary', null, (slide.page) + '. ' + slide.title), h('button', { disabled, onClick: () => onChoose(slide.id) }, L('查看页面', 'View slide')), slide.evidenceChanged && h('p', null, L('关联的来源快照有变化。', 'A linked source snapshot changed.')), slide.fields.map(field => h('div', { key: field.field }, h('strong', null, t(fields.find(([key]) => key === field.field)?.[1] || field.field)), h('div', { className: 'data-before-after' }, h('pre', null, L('之前:', 'Before: ') + display(field.before)), h('pre', null, L('之后:', 'After: ') + display(field.after))))))), h('label', { className: 'data-copy' }, h('input', { type: 'checkbox', checked: saveAs, disabled, onChange: event => setSaveAs(event.target.checked) }), L('保存为新副本,保留原稿(推荐)', 'Save a new copy and keep the original (recommended)')), h('p', { className: 'muted' }, L('PPTX 保存确认后的静态结果,并附公式、来源和假设;HTML 保留交互。JSON 工程包含导入的完整材料,分享前请检查。', 'PPTX saves confirmed static results with formulas, sources and assumptions; HTML retains interaction. The JSON project contains full imported material; review it before sharing.')), h('button', { className: 'primary', disabled: disabled || !valid || !inputsValid, onClick: apply }, saveAs ? L('确认并保存推演副本', 'Confirm and save scenario copy') : L('确认并更新当前工程', 'Confirm and update this project')))));
883
+ }
884
+ function Workbench({locale,workbench=false}={}) {
885
+ const [activeTab,setActiveTab]=useState('content'),[downloadOpen,setDownloadOpen]=useState(false),[pendingNav,setPendingNav]=useState(null),[deleteOpen,setDeleteOpen]=useState(false);
886
+ const controlId=React.useId(),rootElement=useRef(null),fullscreenBoundary=useRef({was:false,exitedAt:0});
887
+ useEffect(()=>{const changed=()=>{const active=!!document.fullscreenElement;if(fullscreenBoundary.current.was && !active)fullscreenBoundary.current.exitedAt=Date.now();fullscreenBoundary.current.was=active;};document.addEventListener('fullscreenchange',changed);return()=>document.removeEventListener('fullscreenchange',changed);},[]);
888
+ function clearEdits(){imageLoader.current.cancel();setDraft(draftFor(slide));setImage(null);setDirty(false);setError('');setMessage('');setConflict(false);setOverlaps([]);}
889
+ function finishNavigation(target,saved){setPendingNav(null);if(target.kind==='back'){imageLoader.current.cancel();setImage(null);setDirty(false);setProject(null);refreshList();return;}if(target.kind==='slide'){if(saved)adopt(saved,target.id);else choose(project.slides.find(row=>row.id===target.id),true);return;}if(saved)adopt(saved,selected);else clearEdits();}
890
+ function requestNavigation(target){if(busy)return;if(dataDirty){setActiveTab('data');setMessage(pptText('请先确认或恢复数据推演。','Confirm or reset the scenario first.'));return;}if(dirty){setPendingNav(target);return;}finishNavigation(target);}
891
+ useLanguage(locale);
892
+ const [projects, setProjects] = useState([]), [project, setProject] = useState(null), [selected, setSelected] = useState('');
893
+ const [draft, setDraft] = useState({}), [image, setImage] = useState(null), [dirty, setDirty] = useState(false);
894
+ const [dataDirty, setDataDirty] = useState(false), [incomingData, setIncomingData] = useState(null);
895
+ const [busy, setBusy] = useState(false), [job, setJob] = useState(''), [message, setMessage] = useState(''), [error, setError] = useState('');
896
+ const [mode, setMode] = useState('html'), [raster, setRaster] = useState('');
897
+ const [conflict, setConflict] = useState(false), [overlaps, setOverlaps] = useState([]);
898
+ const frame = useRef(null), previewBox = useRef(null), fieldRefs = useRef({}), alive = useRef(true), operations = useRef(new Set());
899
+ const imageLoader = useRef(null);
900
+ if (!imageLoader.current)
901
+ imageLoader.current = createImageLoader();
902
+ const imagePending = imageLoader.current.pending;
903
+ const nonce = useRef(crypto.randomUUID());
904
+ const dataCommand = useRef(0);
905
+ const previewDocument = useMemo(() => project?.html ? editorHtml(project.html, nonce.current) : '', [project?.html]);
906
+ const index = project ? Math.max(0, project.slides.findIndex(s => s.id === selected)) : 0;
907
+ const slide = project?.slides[index];
908
+ function adopt(next, preferred) {
909
+ imageLoader.current.cancel();
910
+ nonce.current = crypto.randomUUID();
911
+ setDataDirty(false);
912
+ setIncomingData(null);
913
+ setProject(next);
914
+ const row = next.slides.find(s => s.id === preferred) || next.slides[0];
915
+ setSelected(row.id);
916
+ setDraft(draftFor(row));
917
+ setImage(null);
918
+ setDirty(false);
919
+ setRaster('');
920
+ setOverlaps([]);
921
+ if (!next.render)
922
+ setMode('html');
923
+ }
924
+ async function perform(work, success, label = t("正在处理,请稍候…")) {
925
+ setBusy(true);
926
+ setJob(label);
927
+ setError('');
928
+ setMessage('');
929
+ setConflict(false);
930
+ const controller = new AbortController();
931
+ operations.current.add(controller);
932
+ try {
933
+ const result = await work(controller.signal);
934
+ if (alive.current && success)
935
+ success(result);
936
+ return result;
937
+ }
938
+ catch (e) {
939
+ if (alive.current) {
940
+ setError(e.message || t("操作失败"));
941
+ setConflict(e.status === 409);
942
+ }
943
+ }
944
+ finally {
945
+ operations.current.delete(controller);
946
+ if (alive.current)
947
+ setBusy(false);
948
+ }
949
+ }
950
+ function refreshList() { return perform(signal => action({ operation: 'list' }, signal), value => setProjects(value.projects)); }
951
+ useEffect(() => {
952
+ alive.current = true;
953
+ const abort = new AbortController();
954
+ action({ operation: 'list' }, abort.signal).then(value => { if (alive.current)
955
+ setProjects(value.projects); }).catch(e => { if (!abort.signal.aborted)
956
+ setError(e.message); });
957
+ return () => { alive.current = false; abort.abort(); imageLoader.current.cancel(); for (const operation of operations.current)
958
+ operation.abort(); };
959
+ }, []);
960
+ useEffect(() => {
961
+ function receive(event) {
962
+ if (event.source !== frame.current?.contentWindow || event.data?.nonce !== nonce.current || mode !== 'html')
963
+ return;
964
+ if (event.data.type === 'dsh-ppt-data') {
965
+ if (typeof event.data.command === 'number' && event.data.command !== dataCommand.current)
966
+ return;
967
+ setIncomingData({ parameters: event.data.parameters, valid: event.data.valid });
968
+ return;
969
+ }
970
+ if (event.data.type === 'dsh-ppt-shortcut') {
971
+ handleShortcut(event.data.key);
972
+ return;
973
+ }
974
+ if (event.data.type !== 'dsh-ppt-select')
975
+ return;
976
+ const key = event.data.field;
977
+ const field = fields.find(([field]) => field === key);
978
+ if (field) {
979
+ if(dataDirty){setActiveTab('data');return;}setActiveTab('content');requestAnimationFrame(()=>fieldRefs.current[key]?.focus());
980
+ fieldRefs.current[key]?.scrollIntoView({ block: 'nearest' });
981
+ setMessage(t("已定位到") + t(field[1]) + t(",在字段中修改后保存。"));
982
+ }
983
+ }
984
+ window.addEventListener('message', receive);
985
+ return () => window.removeEventListener('message', receive);
986
+ }, [mode, project, dirty, busy, imagePending, index, selected, draft, image, dataDirty]);
987
+ useEffect(() => {
988
+ if (mode !== 'html' || !project || !previewBox.current)
989
+ return;
990
+ // Align iframe edges/dimensions when the host uses fractional text metrics.
991
+ const box = previewBox.current;
992
+ function align() {
993
+ const target = frame.current;
994
+ if (!target)
995
+ return;
996
+ const r = box.getBoundingClientRect(), x = r.x + box.clientLeft, y = r.y + box.clientTop;
997
+ target.style.width = box.clientWidth + 'px';
998
+ target.style.height = box.clientHeight + 'px';
999
+ target.style.transform = 'translate(' + (Math.ceil(x) - x) + 'px,' + (Math.ceil(y) - y) + 'px)';
1000
+ }
1001
+ align();
1002
+ const observer = new ResizeObserver(align);
1003
+ observer.observe(box);
1004
+ window.addEventListener('scroll', align, true);
1005
+ return () => { observer.disconnect(); window.removeEventListener('scroll', align, true); };
1006
+ }, [mode, !!project]);
1007
+ function jump() { frame.current?.contentWindow?.postMessage({ type: 'dsh-ppt-jump', nonce: nonce.current, page: index }, '*'); }
1008
+ useEffect(() => { jump(); }, [index, project?.revision, mode]);
1009
+ useEffect(() => {
1010
+ if (mode !== 'pptx' || !project?.render)
1011
+ return;
1012
+ const abort = new AbortController();
1013
+ setRaster('');
1014
+ action({ operation: 'page', id: project.id, page: index + 1 }, abort.signal).then(value => setRaster(value.data)).catch(e => { if (!abort.signal.aborted)
1015
+ setError(e.message); });
1016
+ return () => abort.abort();
1017
+ }, [mode, index, project?.revision]);
1018
+ function handleShortcut(key) {
1019
+ if(key==='escape' && (document.fullscreenElement || Date.now()-fullscreenBoundary.current.exitedAt<300)){if(document.fullscreenElement)void document.exitFullscreen();return;}
1020
+ if(dataDirty){if(key==='escape')setActiveTab('data');return;}
1021
+ if(key==='save'){if(project && dirty && !busy && !imagePending)save();return;}
1022
+ if(key==='escape'){if(!project || busy)return;requestNavigation({kind:dirty || imagePending?'cancel':'back'});return;}
1023
+ if(key==='prev' || key==='next'){if(!project || busy || imagePending)return;const next=index+(key==='next'?1:-1);if(next>=0 && next<project.slides.length)choose(project.slides[next]);}
1024
+ }
1025
+ useEffect(() => {
1026
+ function onKey(event) {
1027
+ if(!rootElement.current?.contains(event.target) || event.target?.closest?.('[role=dialog]'))return;
1028
+ if (event.isComposing || event.defaultPrevented)
1029
+ return;
1030
+ if (event.key === 'Escape' && event.target && event.target.tagName === 'SELECT')
1031
+ return;
1032
+ const mod = event.ctrlKey || event.metaKey;
1033
+ if (mod && (event.key === 's' || event.key === 'S')) {
1034
+ if (!project)
1035
+ return;
1036
+ event.preventDefault();
1037
+ handleShortcut('save');
1038
+ return;
1039
+ }
1040
+ if (event.key === 'Escape') {
1041
+ if (!project || busy || imagePending)
1042
+ return;
1043
+ event.preventDefault();
1044
+ handleShortcut('escape');
1045
+ return;
1046
+ }
1047
+ if (event.altKey && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
1048
+ if (!project || busy || imagePending)
1049
+ return;
1050
+ event.preventDefault();
1051
+ handleShortcut(event.key === 'ArrowRight' ? 'next' : 'prev');
1052
+ }
1053
+ }
1054
+ document.addEventListener('keydown', onKey);
1055
+ return () => document.removeEventListener('keydown', onKey);
1056
+ }, [project, dirty, busy, imagePending, index, selected, draft, image, dataDirty]);
1057
+ useEffect(() => {
1058
+ if (!dirty && !dataDirty)
1059
+ return;
1060
+ function warn(event) { event.preventDefault(); event.returnValue = t("有未保存修改,离开页面会丢失。"); }
1061
+ window.addEventListener('beforeunload', warn);
1062
+ return () => window.removeEventListener('beforeunload', warn);
1063
+ }, [dirty, dataDirty]);
1064
+ function open(id) { return perform(signal => action({ operation: 'open', id }, signal), value => { adopt(value.project); setMessage(t("点击预览里的文字,或在下方修改字段。")); }); }
1065
+ function keepInputsAndReload() {
1066
+ const original = draftFor(slide), keys = fields.filter(([key]) => draft[key] !== original[key]).map(([key]) => key), pending = { ...draft }, pendingImage = image;
1067
+ return perform(signal => action({ operation: 'open', id: project.id }, signal), value => {
1068
+ const row = value.project.slides.find(s => s.id === selected);
1069
+ if (!row) {
1070
+ setError(t("当前页已被删除,输入仍保留,请复制需要的内容后取消修改。"));
1071
+ return;
1072
+ }
1073
+ const latest = draftFor(row), merged = { ...latest }, shared = [];
1074
+ for (const key of keys) {
1075
+ merged[key] = pending[key];
1076
+ if (latest[key] !== original[key] && latest[key] !== pending[key])
1077
+ shared.push({ key, latest: latest[key], yours: pending[key] });
1078
+ }
1079
+ adopt(value.project, selected);
1080
+ setDraft(merged);
1081
+ setImage(pendingImage);
1082
+ setDirty(keys.length > 0 || !!pendingImage);
1083
+ setOverlaps(shared);
1084
+ setMessage(t("已载入最新版本并保留你的修改,请核对后再保存。"));
1085
+ });
1086
+ }
1087
+ function choose(row,discard=false) { if(!row || busy)return; if(dirty && !discard){setPendingNav({kind:'slide',id:row.id});return;} imageLoader.current.cancel(); setSelected(row.id); setDraft(draftFor(row)); setImage(null); setMessage(''); }
1088
+ function save(saveAs = false) {
1089
+ if (dataDirty)
1090
+ return;
1091
+ const original = draftFor(slide), patch = {};
1092
+ for (const [key] of fields)
1093
+ if (draft[key] !== original[key])
1094
+ patch[key] = key === 'bullets' ? draft[key].split('\n').map(v => v.trim()).filter(Boolean) : draft[key];
1095
+ if (image)
1096
+ patch.image = { src: image.src, alt: image.alt, fit: image.fit, caption: image.caption };
1097
+ return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, slide: slide.id, patch, saveAs }, signal), value => {
1098
+ adopt(value.project, slide.id);
1099
+ setMessage(saveAs ? t("副本已保存,原文件保留。副本从工程生成,不包含 Office 手工修改。") : value.changed === false ? t("内容没有变化。") : t("已保存,HTML、PPTX 和工程文件已同步更新。"));
1100
+ });
1101
+ }
1102
+ function move(delta) {
1103
+ if (dataDirty)
1104
+ return;
1105
+ const order = project.slides.map(s => s.id);
1106
+ [order[index], order[index + delta]] = [order[index + delta], order[index]];
1107
+ return perform(signal => action({ operation: 'edit', id: project.id, expectedRevision: project.revision, order }, signal), value => { adopt(value.project, slide.id); setMessage(t("页面顺序已更新,可撤销。")); });
1108
+ }
1109
+ function structure(operation) {
1110
+ if (dataDirty)
1111
+ return;
1112
+ return perform(signal => action({ operation, id: project.id, expectedRevision: project.revision, slide: slide.id }, signal), value => {
1113
+ adopt(value.project, value.selected);
1114
+ setMessage(operation === 'duplicate' ? t("页面已复制,图片、图表和备注一并保留,可撤销。") : t("页面已删除,可撤销。"));
1115
+ });
1116
+ }
1117
+ function undo() { if (dataDirty)
1118
+ return; return perform(signal => action({ operation: 'undo', id: project.id, expectedRevision: project.revision }, signal), value => { adopt(value.project, selected); setMessage(t("已撤销上次修改。")); }); }
1119
+ function render() {
1120
+ if (dataDirty)
1121
+ return;
1122
+ 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,较大文件可能需要几分钟…"));
1123
+ }
1124
+ function download(kind) {
1125
+ if (dataDirty)
1126
+ return;
1127
+ const url = new URL('api/dsh-ppt/download', document.baseURI);
1128
+ url.searchParams.set('id', project.id);
1129
+ url.searchParams.set('kind', kind);
1130
+ url.searchParams.set('revision', String(project.revision));
1131
+ // An authenticated attachment response keeps the click's user gesture and
1132
+ // works in WebViews whose native download handler cannot read blob URLs.
1133
+ const link = document.createElement('a');
1134
+ link.href = url.href;
1135
+ link.download = '';
1136
+ link.hidden = true;
1137
+ document.body.append(link);
1138
+ link.click();
1139
+ link.remove();
1140
+ setMessage(t("已请求下载,请查看浏览器的下载列表。"));
1141
+ }
1142
+ function copyExample() {
1143
+ const text = t("示例:请把这份材料制作成可直接交付的演示文稿,生成 HTML、PPTX 和工程文件。");
1144
+ try {
1145
+ navigator.clipboard?.writeText(text).then(() => setMessage(t("已复制示例"))).catch(() => { });
1146
+ }
1147
+ catch (_) { /* ignore */ }
1148
+ }
1149
+ function upload(event) {
1150
+ const file = event.target.files?.[0];
1151
+ event.target.value = '';
1152
+ if (!file)
1153
+ return;
1154
+ imageLoader.current.cancel();
1155
+ setMessage('');
1156
+ setError('');
1157
+ if (!['image/png', 'image/jpeg'].includes(file.type) || file.size > 5 * 1024 * 1024) {
1158
+ setError(t("请选择 5 MiB 以内的 PNG 或 JPEG 图片。"));
1159
+ return;
1160
+ }
1161
+ imageLoader.current.read(file, data => {
1162
+ if (!alive.current)
1163
+ return;
1164
+ setImage({ src: data, alt: slide.image?.alt || file.name.replace(/\.[^.]+$/, ''), caption: slide.image?.caption || '', fit: slide.image?.fit || 'contain', name: file.name });
1165
+ setDirty(true);
1166
+ setError('');
1167
+ setMessage(t("图片已载入,保存后生效。"));
1168
+ }, () => { if (alive.current) {
1169
+ setError(t("无法读取图片,请重试。"));
1170
+ setMessage('');
1171
+ } });
1172
+ if (imageLoader.current.pending)
1173
+ setMessage(t("正在读取图片,切换页面会取消本次读取。"));
1174
+ }
1175
+ const currentImage = image?.src || (slide?.image?.assetId && project.assets[slide.image.assetId]?.data);
1176
+ return h(W.Page,{workbench,rootRef:rootElement,title:t('演示文稿'),subtitle:project?h(React.Fragment,null,project.title+' · '+project.slides.length+t(' 页 · 修订 ')+project.revision,(dirty || dataDirty)?h('span',{className:'w-tag'},t('未保存')):h('span',null,' · '+pptText('已保存','Saved'))):pptText('管理、预览和编辑已生成的演示文稿。','Manage, preview and edit generated presentations.'),className:'pptw ppt-workbench','aria-busy':busy?'true':undefined,actions:project?h(React.Fragment,null,
1177
+ h(W.Button,{icon:'left',disabled:busy || dataDirty,onClick:()=>requestNavigation({kind:'back'})},t('返回项目')),
1178
+ h(W.Button,{variant:'primary',disabled:busy || dataDirty || imagePending || !dirty,'aria-keyshortcuts':'Control+S Meta+S',onClick:()=>save()},pptText('保存修改','Save changes')),
1179
+ h(W.Button,{icon:'download',disabled:busy || dirty || dataDirty || imagePending,title:dirty || dataDirty?pptText('先保存当前修改','Save changes first'):undefined,onClick:()=>setDownloadOpen(true)},pptText('下载成品','Download output'))) : h(W.IconButton,{icon:'refresh',label:t('刷新项目'),disabled:busy,onClick:refreshList})},
1180
+ h('style',null,css),h('style',null,PPT_WORKBENCH_CSS),error && h('div', { role: 'alert', className: 'notice error' }, error, ' ', h('button', { disabled: busy || dataDirty, onClick: () => project ? open(project.id) : refreshList() }, t("重试"))),conflict && project && h('button', { disabled: busy || dataDirty, onClick: keepInputsAndReload }, t("载入最新版本,保留我的输入")),h(W.Status,{tone:'success'},message),busy?h(W.Status,null,job):null,
1181
+ dataDirty ? h(W.Status,null,h('div',{className:'ppt-data-warning'},pptText('数据推演或材料尚未保存,成品仍是已保存版本。','Scenario or source changes are unsaved. Output still uses saved values.'),h(W.Button,{variant:'ghost',onClick:()=>setActiveTab('data')},pptText('前往数据与推演','Open data and what-if')))) : null,
1182
+ !project ? projects.length ? h('div',{className:'ppt-library'},projects.map(row=>h(W.Row,{key:row.id,title:row.title,description:row.path,disabled:busy,onClick:()=>{setActiveTab('content');open(row.id);}}))) : 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("复制示例")))) :
1183
+ h(W.Tabs,{label:pptText('演示文稿工作台视图','Presentation workbench views'),value:activeTab,onChange:value=>{setActiveTab(value);if(value==='data' && project.dataModel)setMode('html');},items:[{id:'content',label:pptText('内容编辑','Edit content')},{id:'visual',label:pptText('视觉检查','Visual review')},{id:'rehearsal',label:pptText('演练','Rehearsal')},{id:'data',label:pptText('数据与推演','Data and what-if')}]},
1184
+ h('div',{className:'ppt-editor','data-view':activeTab},
1185
+ h(PptPages,{project,selected,busy,imagePending,dirty,dataDirty,onChoose:choose,onDuplicate:()=>structure('duplicate')}),
1186
+ h('section',{className:'ppt-canvas-region','aria-label':pptText('成品预览','Presentation preview')},
1187
+ h('div',{className:'ppt-preview-tools'},h(W.Button,{'aria-pressed':mode==='html',disabled:busy || dataDirty,onClick:()=>setMode('html')},t('HTML 预览')),h(W.Button,{'aria-pressed':mode==='pptx',disabled:busy || dataDirty || !project.render,onClick:()=>setMode('pptx')},t('最终 PPTX 预览')),h(W.Button,{disabled:busy || dirty || imagePending || dataDirty,onClick:render},t('渲染当前 PPTX')),h(W.IconButton,{icon:'external',label:pptText('查看全屏','View fullscreen'),onClick:async()=>{try{await previewBox.current?.requestFullscreen();previewBox.current?.querySelector('.ppt-fullscreen-exit')?.focus();}catch{setError(pptText('当前宿主无法进入全屏,可以继续使用页面预览。','Fullscreen is unavailable in this host. The page preview remains usable.'));}}})),
1188
+ h('div', { className: 'preview', ref: previewBox },h(W.Button,{className:'ppt-fullscreen-exit',onClick:()=>document.exitFullscreen()},pptText('退出全屏','Exit fullscreen')), 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("正在载入当前页渲染…"))),h('div',{className:'ppt-preview-help'},h('p', { className: 'muted' }, mode === 'html' ? t("这是 HTML 放映预览。最终 PPTX 的字体和排版请用上方渲染检查。点击文字可定位编辑字段。") : t("这是当前 PPTX 文件的实际渲染图片,仍需检查每页画面;PowerPoint / WPS 可能因字体环境而不同。"))),project.render?.missingFonts?.length ? h('div', { role: 'alert', className: 'notice error' }, t("渲染引擎报告缺失字体:") + project.render.missingFonts.join('、') + t("。请替换为目标电脑可用字体后重新渲染。")) : null,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)))),h('p',{className:'w-muted'},t('快捷键:Ctrl/⌘+S 保存 · Esc 取消或返回 · Alt+←/→ 切换页面'))),
1189
+ h('aside',{className:'ppt-inspector','aria-label':pptText('页面与辅助工具','Slide properties and tools')},
1190
+ h('section',{className:'ppt-inspector-panel',hidden:activeTab!=='content'},h('div',{className:'card'},h('h3',null,pptText('页面内容','Slide content')),dirty && h('p', { className: 'dirty' }, t("有未保存修改,请先保存或取消,再切换页面。")),
1191
+ 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,
1192
+ 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: controlId+'-'+key }, t(label)), h(key === 'title' || key === 'kicker' ? 'input' : 'textarea', { id: controlId+'-'+key, ref: el => { fieldRefs.current[key] = el; }, disabled: busy || dataDirty, value: draft[key] || '', rows: key === 'bullets' ? 4 : 2, maxLength: 8000, onChange: e => { setDraft({ ...draft, [key]: e.target.value }); setDirty(true); } }))),h('details',{className:'ppt-image-section',open:!!image},h('summary',null,pptText('图片','Image')),h('label', { htmlFor: controlId+'-image' }, slide.image ? t("替换图片(PNG / JPEG)") : t("添加图片(会改为图文布局)")),
1193
+ h('input', { id: controlId+'-image', type: 'file', accept: 'image/png,image/jpeg', disabled: busy || dataDirty, onChange: upload }),
1194
+ currentImage && h('img', { className: 'image-preview', src: currentImage, alt: image?.alt || slide.image?.alt || t("当前图片") }),
1195
+ image && h(React.Fragment, null, h('p', { className: 'muted' }, t("已选择:") + image.name), h('label', { htmlFor: controlId+'-alt' }, t("图片说明")), h('input', { id: controlId+'-alt', value: image.alt, disabled: busy || dataDirty, onChange: e => setImage({ ...image, alt: e.target.value }) }), h('label', { htmlFor: controlId+'-fit' }, t("图片适应方式")), h('select', { id: controlId+'-fit', value: image.fit, disabled: busy || dataDirty, onChange: e => setImage({ ...image, fit: e.target.value }) }, h('option', { value: 'contain' }, t("完整显示")), h('option', { value: 'cover' }, t("填满并裁切"))))),h('div',{className:'tools'},h('button', { 'aria-keyshortcuts': 'Control+Shift+S Meta+Shift+S', disabled: busy || dataDirty || imagePending, onClick: () => save(true) }, t("另存副本")),
1196
+ 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("取消修改")),
1197
+ h('button', { disabled: busy || dirty || imagePending || dataDirty || !project.undoAvailable, onClick: undo }, t("撤销上次修改")))),h('div',{className:'w-toolbar ppt-structure'},h(W.Button,{disabled:busy || dirty || imagePending || dataDirty || index===0,onClick:()=>move(-1)},t('上移')),h(W.Button,{disabled:busy || dirty || imagePending || dataDirty || index===project.slides.length-1,onClick:()=>move(1)},t('下移')),h(W.Button,{icon:'trash',variant:'danger',disabled:busy || dirty || imagePending || dataDirty || project.slides.length<=1,onClick:()=>{setError('');setDeleteOpen(true);}},t('删除本页')))),
1198
+ h('section',{className:'ppt-inspector-panel',hidden:activeTab!=='visual'},h(VisualPanel, { key: 'visual:' + project.id, project, selected, blocked: busy || dirty || imagePending || dataDirty,
1199
+ onBusy: value => { setBusy(value); setJob(languageOf() === 'en' ? 'Reviewing rendered slides…' : '正在检查和复查实际 PPTX 画面…'); },
1200
+ onAdopt: next => { adopt(next, selected); setMode(next.render ? 'pptx' : 'html'); setMessage(languageOf() === 'en' ? 'Opened the repaired copy. The original is kept, and formatting changes can be undone.' : '已打开修复副本,原稿保留,可撤销排版修改。'); } })),
1201
+ h('section',{className:'ppt-inspector-panel',hidden:activeTab!=='rehearsal'},h(CoachingPanel, { key: project.id, project, selected, blocked: busy || dirty || imagePending || dataDirty,
1202
+ onChoose: id => { choose(project.slides.find(s => s.id === id)); previewBox.current?.scrollIntoView({ behavior: 'smooth', block: 'center' }); },
1203
+ 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.' : '已保存为新副本,原稿保留;可在当前副本中撤销采纳的修改。'); } })),
1204
+ h('section',{className:'ppt-inspector-panel',hidden:activeTab!=='data'},project.dataModel?project.dataModel && h(DataPanel, { key: project.id + ':' + project.revision, project, blocked: busy || dirty || imagePending || mode !== 'html', incoming: incomingData,
1205
+ onParameters: parameters => frame.current?.contentWindow?.postMessage({ type: 'dsh-ppt-data-set', nonce: nonce.current, parameters, command: ++dataCommand.current }, '*'), onDirty: setDataDirty, onBusy: value => { setBusy(value); setJob(languageOf() === 'en' ? 'Updating presentation data…' : '正在核对并更新数据…'); },
1206
+ onAdopt: next => { adopt(next, selected); setMessage(languageOf() === 'en' ? 'Saved confirmed data. HTML, PPTX and project are synchronized; undo is available.' : '已保存确认后的数据,HTML、PPTX 和工程已同步,可撤销。'); }, onChoose: id => choose(project.slides.find(s => s.id === id)), onDownload: download }):h(W.Empty,{title:pptText('此工程没有绑定数据模型','This project has no bound data model'),icon:'file'},pptText('生成时提供来源、指标和可调假设后,可在这里核对来源并预览推演影响。普通演示文稿仍可正常编辑和下载。','Provide sources, metrics and adjustable assumptions when generating the deck to inspect lineage and scenario changes here. Normal editing and downloads remain available.')))))),
1207
+ downloadOpen && project ? h(W.Dialog,{title:pptText('下载成品','Download output'),closeLabel:pptText('关闭','Close'),onClose:()=>setDownloadOpen(false)},h('div',{className:'ppt-downloads'},h('p', { className: 'muted' }, t("成品包包含 PPTX、HTML 和工程文件。请先保存修改,再下载最新版本。")),h('div', { className: 'tools' }, h('button', { className: 'primary', disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('bundle') }, t("下载成品包 ZIP")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('pptx') }, t("下载最新 PPTX")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('html') }, t("下载 HTML")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('notes') }, t("下载讲稿 Markdown")), h('button', { disabled: busy || dirty || imagePending || dataDirty, onClick: () => download('json') }, t("备份工程"))))) : null,
1208
+ pendingNav ? h(W.Dialog,{title:pptText('有未保存的修改','Unsaved changes'),closeLabel:pptText('继续编辑','Keep editing'),busy,onClose:()=>setPendingNav(null)},h('p',null,pptText('请选择如何处理当前页的修改。','Choose what to do with the current slide edits.')),h(W.Status,{tone:'error'},error),h('div',{className:'w-toolbar'},h(W.Button,{variant:'primary',disabled:busy || imagePending || dataDirty,onClick:async()=>{const target=pendingNav;const result=await save();if(result?.project && alive.current)finishNavigation(target,result.project);}},pptText('保存后继续','Save and continue')),h(W.Button,{disabled:busy,onClick:()=>finishNavigation(pendingNav)},pptText('放弃修改并继续','Discard and continue')),h(W.Button,{disabled:busy,onClick:()=>setPendingNav(null)},pptText('继续编辑','Keep editing')))) : null,
1209
+ deleteOpen && project ? h(W.Dialog,{title:t('删除本页'),closeLabel:pptText('取消','Cancel'),busy,onClose:()=>setDeleteOpen(false)},h('p',null,pptText('将删除当前页面,之后可以撤销。','Remove the current slide. You can undo this change.')),h(W.Status,{tone:'error'},error),h('div',{className:'w-toolbar'},h(W.Button,{variant:'danger',disabled:busy,onClick:async()=>{const result=await structure('remove');if(result)setDeleteOpen(false);}},pptText('确认删除本页','Confirm remove slide')),h(W.Button,{disabled:busy,onClick:()=>setDeleteOpen(false)},pptText('取消','Cancel')))) : null);
1210
+ }
1211
+ function apply(ctx) {
1212
+ W.register(ctx,{id:'dsh-ppt.workbench',label:()=>t('演示文稿'),icon:'slides',component:Workbench,inject:()=>({locale:localeService}),order:57});
1213
+
1214
+ try {
1215
+ localeService = ctx.get?.('locale') || ctx.locale;
1216
+ }
1217
+ catch {
1218
+ localeService = ctx.locale;
1219
+ }
1220
+ ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: 'dsh-ppt', order: 58, label: () => t("演示文稿"), inject: () => ({ locale: localeService }) }, Workbench));
1221
+ }
1222
+ return { inject: ['slots', 'locale'], apply, __internals: { draftFor, editorHtml, createImageLoader, modelRouteKey, findModelRoute, reconcileModelRoute } };
1223
+ } });
1224
+
1225
+ })();