gbpptx 0.1.1 → 0.2.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.
@@ -1,508 +1,1438 @@
1
- // [文件] gbpptx·SlidesApp —— 演示编辑器装配(画布/页栏/检查器/工具栏/菜单/放映/文件读写)
1
+ // [文件] gbpptx·SlidesApp —— Office 式演示编辑器装配(Ribbon/窗格/画布/放映/文件读写/查找替换)
2
2
 
3
3
  import {
4
- SHAPE_KINDS, SLIDE_H, SLIDE_W, cloneObject, copySlide, createDraft, createImageObject, createLineObject,
5
- createShapeObject, createSlide, createSlideWithLayout, createTableObject, createTextObject, normalizeSnapshot,
6
- objectRect, setObjectFontSize, topZ,
4
+ SLIDE_LAYOUTS, SLIDE_SIZES, THEMES, TRANSITIONS, cloneObject, contrastText, copySlide, createDraft, createImageObject,
5
+ createLineObject, createShapeObject, createSlide, createSlideWithLayout, createTableObject, createTextObject,
6
+ htmlToPlain, normalizeSnapshot, normalizeTransition, objectRect, scaleSnapshotSize, setObjectFontSize,
7
+ sizeOf, themeOf, topZ, transitionOf,
7
8
  } from '../../src/kernel/model.js';
8
9
  import { buildPptxVerified } from '../../src/kernel/roundtrip.js';
9
10
  import { parsePptx } from '../../src/kernel/read.js';
10
11
  import { printSlides } from '../../src/kernel/print.js';
11
- import { buildMenus } from '../../src/kernel/menus.js';
12
+ import { htmlToParas, parasToHTML, sanitizeTextHtml } from '../../src/kernel/text.js';
12
13
  import { notify } from './ui/notify.js';
13
- import { buildMenuBar, openContextMenu } from './ui/menu.js';
14
- import { buildToolbar } from './ui/toolbar.js';
14
+ import { TitleBar } from './ui/titlebar.js';
15
+ import { Ribbon } from './ui/ribbon.js';
16
+ import { SlidePane } from './ui/slide-pane.js';
15
17
  import { Canvas } from './ui/canvas.js';
16
- import { Inspector } from './ui/inspector.js';
17
- import { SlidesBar } from './ui/slides-bar.js';
18
+ import { FormatPane } from './ui/format-pane.js';
19
+ import { StatusBar } from './ui/statusbar.js';
20
+ import { Backstage } from './ui/backstage.js';
18
21
  import { Present } from './ui/present.js';
19
22
  import { renderPage } from './ui/page-view.js';
20
- import { promptText } from './ui/dialogs.js';
21
- import { openPptx, savePptx, savePptxAs, downloadBlob, ensureExt, PPTX_MIME } from './ui/file-io.js';
22
-
23
- const LS_KEY = 'gbpptx.prefs';
24
- const HISTORY_LIMIT = 60;
25
- const EMPTY = { version: 1, title: '', theme: 'clean', slides: [createSlide()] };
23
+ import {
24
+ PPTX_MIME, ensureExt, downloadBlob, isPptxFile, openPptx, pickImageFile, readBytes, savePptx, savePptxAs,
25
+ } from './ui/file-io.js';
26
+ import { openContextMenu } from './ui/menu.js';
27
+ import { confirmDialog, field, numberInput, openModal, promptText } from './ui/dialogs.js';
28
+ import { icon } from './ui/icons.js';
29
+
30
+ const LS_KEY = 'gbpptx.office.prefs';
31
+ const HISTORY_LIMIT = 100;
32
+ const AUTOSAVE_MS = 2600;
33
+ const ZOOM_MIN = 20;
34
+ const ZOOM_MAX = 400;
35
+
36
+ const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
37
+ const stripExt = (name) => String(name || '').replace(/\.[^./\\]+$/, '');
38
+ const escapeHtmlText = (s) => String(s ?? '').replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
39
+ const escapeRegExp = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
40
+
41
+ const el = (tag, cls, text) => {
42
+ const node = document.createElement(tag);
43
+ if (cls) node.className = cls;
44
+ if (text != null) node.textContent = text;
45
+ return node;
46
+ };
26
47
 
27
48
  export class SlidesApp {
28
49
  constructor(mount) {
29
50
  this.mount = mount;
30
- this.doc = { name: '新建演示', handle: null };
51
+ const prefs = loadPrefs();
52
+ this.prefs = prefs;
31
53
  this.snapshot = createDraft();
32
54
  this.index = 0;
33
55
  this.selectedIds = [];
34
- this.zoom = 60;
56
+ this.zoom = clamp(Number(prefs.zoom) || 65, ZOOM_MIN, ZOOM_MAX);
35
57
  this.dirty = false;
36
58
  this.saving = false;
59
+ this.revision = 0;
37
60
  this.history = [];
38
61
  this.future = [];
39
62
  this.clipboard = null;
40
- this.prefs = loadPrefs();
41
- this.autosave = !!this.prefs.autosave;
42
- this.notesVisible = true;
43
- this.presenter = new Present({ getSlides: () => this.snapshot.slides, getTheme: () => this.snapshot.theme });
63
+ this.editing = null;
64
+ this.tableCursor = null;
65
+ this.notesSession = false;
66
+ this.autosave = !!prefs.autosave;
67
+ this.notesVisible = prefs.notesVisible !== false;
68
+ this.gridVisible = !!prefs.grid;
69
+ this.guidesVisible = prefs.guides === true;
70
+ this.ribbonCollapsed = !!prefs.ribbonCollapsed;
71
+ this.formatPaneOpen = !!prefs.formatPaneOpen;
72
+ this.view = 'normal';
73
+ this.presentOptions = { presenter: !!prefs.presenter, loop: !!prefs.loop };
74
+ this.lastBytes = null;
75
+
76
+ const seq = Number(prefs.docSeq) || 1;
77
+ prefs.docSeq = seq + 1;
78
+ savePrefs(prefs);
79
+ this.doc = { name: `演示文稿${seq}`, handle: null, savedAt: 0 };
80
+
44
81
  this.build();
82
+ this.bindGlobal();
83
+ this.presenter = new Present(this);
84
+ this.backstage = new Backstage(this);
45
85
  }
46
86
 
47
87
  /* ===================== 骨架 ===================== */
48
88
 
89
+ get size() {
90
+ return sizeOf(this.snapshot);
91
+ }
92
+
49
93
  build() {
50
- const root = document.createElement('div');
51
- root.className = 'slides-app';
94
+ const root = el('div', 'pp-app');
52
95
  root.innerHTML = `
53
- <div class="sl-menubar-host"></div>
54
- <div class="sl-head">
55
- <span class="sl-head__title"></span>
56
- <span class="sl-head__path"></span>
57
- <span class="sl-head__dirty" hidden>●</span>
58
- <span class="sl-head__spacer"></span>
59
- <label class="sl-head__auto"><input type="checkbox" class="sl-head__autosave" />自动保存</label>
60
- <button type="button" class="gb-btn" data-act="open">打开</button>
61
- <button type="button" class="gb-btn" data-act="save">保存</button>
62
- <button type="button" class="gb-btn" data-act="export">导出 pptx</button>
96
+ <div class="pp-titlebar-host"></div>
97
+ <div class="pp-ribbon-host"></div>
98
+ <div class="pp-main">
99
+ <div class="pp-main__left"></div>
100
+ <div class="pp-center">
101
+ <div class="pp-canvas-host"></div>
102
+ <div class="pp-notes" hidden>
103
+ <div class="pp-notes__head">
104
+ <span class="pp-notes__title">备注</span>
105
+ <button type="button" class="pp-iconbtn" data-act="notes-close" title="关闭备注">${icon('close', 14)}</button>
106
+ </div>
107
+ <textarea class="pp-notes__text" placeholder="单击此处添加演讲者备注"></textarea>
108
+ </div>
109
+ </div>
110
+ <div class="pp-main__right"></div>
63
111
  </div>
64
- <div class="sl-toolbar-host"></div>
65
- <div class="sl-main"></div>
66
- <div class="sl-statusbar">
67
- <span data-k="info">第 1 / 1 页</span>
68
- <span data-k="objects">对象 0</span>
69
- <span class="sl-statusbar__spacer"></span>
70
- <button type="button" class="sl-statusbar__btn" data-act="notes">备注</button>
71
- <button type="button" class="sl-statusbar__btn" data-act="present">放映</button>
72
- <button type="button" class="sl-statusbar__btn" data-act="zoomOut">−</button>
73
- <button type="button" class="sl-statusbar__btn" data-act="zoomReset"><span data-k="zoom">60%</span></button>
74
- <button type="button" class="sl-statusbar__btn" data-act="zoomIn">+</button>
75
- </div>`;
112
+ <div class="pp-statusbar-host"></div>`;
76
113
  this.mount.appendChild(root);
77
114
  this.root = root;
78
- this.titleEl = root.querySelector('.sl-head__title');
79
- this.pathEl = root.querySelector('.sl-head__path');
80
- this.dirtyEl = root.querySelector('.sl-head__dirty');
81
- this.autosaveEl = root.querySelector('.sl-head__autosave');
82
- const main = root.querySelector('.sl-main');
83
-
84
- this.slidesBar = new SlidesBar(this);
115
+ this.left = root.querySelector('.pp-main__left');
116
+ this.center = root.querySelector('.pp-center');
117
+ this.right = root.querySelector('.pp-main__right');
118
+ this.canvasHost = root.querySelector('.pp-canvas-host');
119
+ this.notesEl = root.querySelector('.pp-notes');
120
+ this.notesText = root.querySelector('.pp-notes__text');
121
+
122
+ this.titlebar = new TitleBar(this);
123
+ this.ribbon = new Ribbon(this);
124
+ this.slidePane = new SlidePane(this);
85
125
  this.canvas = new Canvas(this);
86
- this.inspector = new Inspector(this);
87
- this.slidesBar.el.style.display = 'flex';
88
- main.append(this.slidesBar.el, this.canvas.el, this.inspector.el);
89
-
90
- const toolbar = buildToolbar(this);
91
- this.toolbar = toolbar;
92
- root.querySelector('.sl-toolbar-host').appendChild(toolbar.el);
93
-
94
- root.querySelector('.sl-menubar-host').appendChild(buildMenuBar(buildMenus(this.menuCtx())));
126
+ this.formatPane = new FormatPane(this);
127
+ this.statusbar = new StatusBar(this);
128
+
129
+ root.querySelector('.pp-titlebar-host').appendChild(this.titlebar.el);
130
+ root.querySelector('.pp-ribbon-host').appendChild(this.ribbon.el);
131
+ this.left.appendChild(this.slidePane.el);
132
+ this.canvasHost.appendChild(this.canvas.el);
133
+ this.right.appendChild(this.formatPane.el);
134
+ root.querySelector('.pp-statusbar-host').appendChild(this.statusbar.el);
135
+
136
+ this.sorterEl = el('div', 'pp-sorter');
137
+ this.sorterEl.hidden = true;
138
+ this.center.appendChild(this.sorterEl);
139
+ this.readingEl = el('div', 'pp-reading');
140
+ this.readingEl.hidden = true;
141
+ this.center.appendChild(this.readingEl);
142
+ this.buildSorterEvents();
143
+
144
+ this.bindNotes(root.querySelector('[data-act="notes-close"]'));
145
+ }
95
146
 
96
- this.bindHead();
97
- this.bindStatus();
98
- this.bindKeys();
99
- this.canvas.el.addEventListener('contextmenu', (e) => {
100
- e.preventDefault();
101
- this.openObjectMenu(e.clientX, e.clientY);
147
+ bindNotes(closeBtn) {
148
+ this.notesText.addEventListener('focus', () => { this.notesSession = false; });
149
+ this.notesText.addEventListener('input', () => {
150
+ const slide = this.currentSlide();
151
+ if (!slide) return;
152
+ if (!this.notesSession) {
153
+ this.pushHistory();
154
+ this.notesSession = true;
155
+ }
156
+ slide.notes = this.notesText.value;
157
+ this.markDirty();
158
+ this.statusbar.setStatus('正在编辑备注');
102
159
  });
103
- this.autosaveEl.checked = this.autosave;
160
+ this.notesText.addEventListener('blur', () => {
161
+ if (!this.notesSession) return;
162
+ this.notesSession = false;
163
+ this.statusbar.setStatus('');
164
+ this.ribbon.refresh();
165
+ });
166
+ closeBtn.addEventListener('click', () => this.toggleNotes());
104
167
  }
105
168
 
106
- bindHead() {
107
- this.root.querySelector('[data-act="open"]').addEventListener('click', () => this.openFile());
108
- this.root.querySelector('[data-act="save"]').addEventListener('click', () => this.save());
109
- this.root.querySelector('[data-act="export"]').addEventListener('click', () => this.exportPptx());
110
- this.autosaveEl.addEventListener('change', () => {
111
- this.autosave = this.autosaveEl.checked;
112
- this.prefs.autosave = this.autosave;
113
- savePrefs(this.prefs);
169
+ buildSorterEvents() {
170
+ this.sorterEl.addEventListener('click', (e) => {
171
+ const card = e.target.closest('[data-index]');
172
+ if (card) this.selectSlide(Number(card.dataset.index));
173
+ });
174
+ this.sorterEl.addEventListener('dblclick', (e) => {
175
+ const card = e.target.closest('[data-index]');
176
+ if (card) {
177
+ this.selectSlide(Number(card.dataset.index));
178
+ this.setView('normal');
179
+ }
180
+ });
181
+ this.sorterEl.addEventListener('contextmenu', (e) => {
182
+ const card = e.target.closest('[data-index]');
183
+ if (!card) return;
184
+ e.preventDefault();
185
+ const i = Number(card.dataset.index);
186
+ this.selectSlide(i);
187
+ this.openSlideMenu(e.clientX, e.clientY, i);
188
+ });
189
+ this.sorterEl.addEventListener('dragstart', (e) => {
190
+ const card = e.target.closest('[data-index]');
191
+ if (!card) return;
192
+ this.dragIndex = Number(card.dataset.index);
193
+ card.classList.add('is-dragging');
194
+ e.dataTransfer.effectAllowed = 'move';
195
+ e.dataTransfer.setData('text/plain', String(this.dragIndex));
196
+ });
197
+ this.sorterEl.addEventListener('dragend', () => {
198
+ this.dragIndex = null;
199
+ this.sorterEl.querySelectorAll('.is-dragging, .is-drop').forEach((n) => n.classList.remove('is-dragging', 'is-drop'));
200
+ });
201
+ this.sorterEl.addEventListener('dragover', (e) => {
202
+ const card = e.target.closest('[data-index]');
203
+ if (!card || this.dragIndex === null) return;
204
+ e.preventDefault();
205
+ this.sorterEl.querySelectorAll('.is-drop').forEach((n) => n.classList.remove('is-drop'));
206
+ card.classList.add('is-drop');
207
+ });
208
+ this.sorterEl.addEventListener('drop', (e) => {
209
+ const card = e.target.closest('[data-index]');
210
+ if (!card || this.dragIndex === null) return;
211
+ e.preventDefault();
212
+ const to = Number(card.dataset.index);
213
+ if (to !== this.dragIndex) this.moveSlideTo(this.dragIndex, to);
214
+ this.dragIndex = null;
114
215
  });
115
216
  }
116
217
 
117
- bindStatus() {
118
- const r = this.root;
119
- r.querySelector('[data-act="present"]').addEventListener('click', () => this.present());
120
- r.querySelector('[data-act="zoomIn"]').addEventListener('click', () => this.setZoom(this.zoom + 10));
121
- r.querySelector('[data-act="zoomOut"]').addEventListener('click', () => this.setZoom(this.zoom - 10));
122
- r.querySelector('[data-act="zoomReset"]').addEventListener('click', () => this.setZoom(60));
123
- r.querySelector('[data-act="notes"]').addEventListener('click', () => this.toggleNotes());
218
+ /* ===================== 启动/销毁 ===================== */
219
+
220
+ start() {
221
+ this.renderAll();
222
+ notify.info('已就绪:可直接编辑,或用「文件 → 打开」载入 .pptx');
124
223
  }
125
224
 
126
- toggleNotes() {
127
- this.notesVisible = !this.notesVisible;
128
- this.slidesBar.el.querySelector('.sl-notes').style.display = this.notesVisible ? '' : 'none';
129
- }
130
-
131
- bindKeys() {
132
- document.addEventListener('keydown', (e) => {
133
- const typing = e.target instanceof Element && (e.target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(e.target.tagName));
134
- if (typing && e.key !== 'Escape') return;
135
- const mod = e.ctrlKey || e.metaKey;
136
- const k = e.key.toLowerCase();
137
- if (mod && !e.altKey) {
138
- if (k === 's') { e.preventDefault(); e.shiftKey ? this.saveAs() : this.save(); return; }
139
- if (k === 'o') { e.preventDefault(); this.openFile(); return; }
140
- if (k === 'z') { e.preventDefault(); this.undo(); return; }
141
- if (k === 'y') { e.preventDefault(); this.redo(); return; }
142
- if (k === 'd') { e.preventDefault(); this.selectedIds.length ? this.duplicateSelected() : this.dupSlide(); return; }
143
- if (k === 'm') { e.preventDefault(); this.addSlide(); return; }
144
- if (k === 'a') { e.preventDefault(); this.selectObjects(this.currentSlide().objects.map((o) => o.id)); return; }
145
- if (k === 'c') { this.copySelected(); return; }
146
- if (k === 'x') { this.cutSelected(); return; }
147
- if (k === 'v') { this.paste(); return; }
148
- if (k === '=' || k === '+') { e.preventDefault(); this.setZoom(this.zoom + 10); return; }
149
- if (k === '-') { e.preventDefault(); this.setZoom(this.zoom - 10); return; }
150
- if (k === '0') { e.preventDefault(); this.setZoom(60); return; }
151
- if (k === 'n' && e.altKey) { e.preventDefault(); this.newDoc(); return; }
152
- }
153
- if (e.key === 'F5') { e.preventDefault(); this.present(); return; }
154
- if (e.key === 'Delete' || e.key === 'Backspace') {
155
- if (this.selectedIds.length) { e.preventDefault(); this.removeSelected(); }
156
- return;
157
- }
158
- if (e.key === 'Escape') this.clearSelection();
159
- });
225
+ destroy() {
226
+ this.presenter?.close();
227
+ clearTimeout(this.autosaveTimer);
228
+ document.removeEventListener('keydown', this.onKeyBound);
229
+ document.removeEventListener('paste', this.onPasteBound);
230
+ document.removeEventListener('selectionchange', this.onSelectionChangeBound);
231
+ window.removeEventListener('beforeunload', this.onBeforeUnloadBound);
232
+ window.removeEventListener('dragover', this.onDragOverBound);
233
+ window.removeEventListener('drop', this.onDropBound);
234
+ window.removeEventListener('resize', this.onResizeBound);
160
235
  }
161
236
 
162
237
  /* ===================== 渲染 ===================== */
163
238
 
164
- renderAll(opts = {}) {
165
- this.index = Math.max(0, Math.min(this.snapshot.slides.length - 1, this.index));
166
- if (opts.thumbs !== false) {
167
- this.slidesBar.render();
168
- this.slidesBar.scrollToActive();
239
+ currentSlide() {
240
+ return this.snapshot.slides[this.index] || this.snapshot.slides[0] || null;
241
+ }
242
+
243
+ selectedObjects() {
244
+ const slide = this.currentSlide();
245
+ if (!slide) return [];
246
+ return slide.objects.filter((o) => this.selectedIds.includes(o.id));
247
+ }
248
+
249
+ firstSelected() {
250
+ return this.selectedObjects()[0] || null;
251
+ }
252
+
253
+ selectedById(id) {
254
+ return this.currentSlide()?.objects.find((o) => o.id === id) || null;
255
+ }
256
+
257
+ renderAll() {
258
+ if (!this.snapshot.slides.length) this.snapshot.slides.push(createSlide());
259
+ this.index = clamp(this.index, 0, this.snapshot.slides.length - 1);
260
+ this.updateLayout();
261
+ if (this.view === 'normal') {
262
+ this.canvas.render();
263
+ this.renderNotes();
264
+ } else if (this.view === 'sorter') {
265
+ this.renderSorter();
266
+ } else if (this.view === 'reading') {
267
+ this.renderReading();
169
268
  }
170
- this.canvas.render();
171
- this.inspector.render();
172
- this.toolbar.refresh();
173
- this.renderHead();
174
- this.renderStatus();
269
+ this.slidePane.render();
270
+ this.formatPane.render();
271
+ this.ribbon.refresh();
272
+ this.titlebar.refresh();
273
+ this.statusbar.refresh();
175
274
  }
176
275
 
177
- renderHead() {
178
- this.titleEl.textContent = this.doc.name || '新建演示';
179
- this.pathEl.textContent = this.doc.handle ? '(已关联文件)' : '(未关联文件,保存将另存为)';
180
- this.dirtyEl.hidden = !this.dirty;
276
+ updateLayout() {
277
+ const normal = this.view === 'normal';
278
+ this.slidePane.el.hidden = !normal;
279
+ this.canvasHost.hidden = !normal;
280
+ this.canvas.el.hidden = !normal;
281
+ this.notesEl.hidden = !normal || !this.notesVisible;
282
+ this.sorterEl.hidden = this.view !== 'sorter';
283
+ this.readingEl.hidden = this.view !== 'reading';
284
+ this.root.dataset.view = this.view;
285
+ this.root.classList.toggle('has-pane', normal && this.formatPaneOpen);
286
+ this.root.classList.toggle('has-notes', normal && this.notesVisible);
287
+ if (!normal || !this.formatPaneOpen) this.formatPane.el.hidden = true;
288
+ else if (this.formatPaneOpen) this.formatPane.el.hidden = false;
181
289
  }
182
290
 
183
- renderStatus() {
184
- this.root.querySelector('[data-k="info"]').textContent = `第 ${this.index + 1} / ${this.snapshot.slides.length} 页`;
185
- this.root.querySelector('[data-k="objects"]').textContent = `对象 ${this.currentSlide().objects.length}`;
186
- this.root.querySelector('[data-k="zoom"]').textContent = `${this.zoom}%`;
291
+ renderNotes() {
292
+ const slide = this.currentSlide();
293
+ if (this.notesText && document.activeElement !== this.notesText) this.notesText.value = slide?.notes || '';
187
294
  }
188
295
 
189
- /** 文档已变更:置脏 + 排期自动保存 + 重渲染 */
190
- notifyChange(opts) {
191
- this.setDirty(true);
192
- if (this.autosave) this.scheduleAutosave();
193
- this.renderAll(opts);
296
+ renderSorter() {
297
+ const size = this.size;
298
+ const theme = this.snapshot.theme;
299
+ const width = 248;
300
+ this.sorterEl.replaceChildren();
301
+ this.snapshot.slides.forEach((slide, i) => {
302
+ const card = el('div', `pp-sorter-card${i === this.index ? ' is-active' : ''}${slide.hidden ? ' is-hidden' : ''}`);
303
+ card.dataset.index = String(i);
304
+ card.draggable = true;
305
+ const no = el('div', 'pp-sorter-card__no', String(i + 1));
306
+ const box = el('div', 'pp-sorter-card__box');
307
+ box.style.height = `${size.h * (width / size.w)}px`;
308
+ const page = renderPage(slide, theme, { size });
309
+ page.style.transform = `scale(${width / size.w})`;
310
+ page.style.transformOrigin = 'top left';
311
+ box.appendChild(page);
312
+ card.append(no, box);
313
+ if (slide.hidden) {
314
+ const flag = el('span', 'pp-sorter-card__flag');
315
+ flag.innerHTML = icon('hide', 14);
316
+ card.appendChild(flag);
317
+ }
318
+ this.sorterEl.appendChild(card);
319
+ });
194
320
  }
195
321
 
322
+ renderReading() {
323
+ const size = this.size;
324
+ const slide = this.currentSlide();
325
+ this.readingEl.replaceChildren();
326
+ if (!slide) return;
327
+ const availW = Math.max(320, (this.readingEl.clientWidth || window.innerWidth) - 120);
328
+ const availH = Math.max(240, (this.readingEl.clientHeight || window.innerHeight) - 130);
329
+ const scale = Math.min(availW / size.w, availH / size.h);
330
+ const stage = el('div', 'pp-reading__stage');
331
+ stage.style.width = `${size.w * scale}px`;
332
+ stage.style.height = `${size.h * scale}px`;
333
+ const page = renderPage(slide, this.snapshot.theme, { size });
334
+ page.style.transform = `scale(${scale})`;
335
+ page.style.transformOrigin = 'top left';
336
+ stage.appendChild(page);
337
+ const prev = el('button', 'pp-reading__nav pp-reading__nav--prev');
338
+ prev.type = 'button';
339
+ prev.title = '上一页';
340
+ prev.innerHTML = icon('chevronLeft', 24);
341
+ prev.disabled = this.index === 0;
342
+ prev.addEventListener('click', () => this.selectSlide(this.index - 1));
343
+ const next = el('button', 'pp-reading__nav pp-reading__nav--next');
344
+ next.type = 'button';
345
+ next.title = '下一页';
346
+ next.innerHTML = icon('chevronRight', 24);
347
+ next.disabled = this.index >= this.snapshot.slides.length - 1;
348
+ next.addEventListener('click', () => this.selectSlide(this.index + 1));
349
+ const bar = el('div', 'pp-reading__bar');
350
+ const counter = el('span', '', `${this.index + 1} / ${this.snapshot.slides.length}`);
351
+ const quit = el('button', 'pp-reading__quit', '关闭阅读视图 (Esc)');
352
+ quit.type = 'button';
353
+ quit.addEventListener('click', () => this.setView('normal'));
354
+ bar.append(counter, quit);
355
+ this.readingEl.append(prev, stage, next, bar);
356
+ }
357
+
358
+ /* ===================== 脏状态/历史 ===================== */
359
+
196
360
  setDirty(on) {
197
- this.dirty = on;
198
- this.dirtyEl.hidden = !on;
361
+ this.dirty = !!on;
362
+ this.titlebar.refresh();
363
+ }
364
+
365
+ touch() {
366
+ this.revision += 1;
367
+ this.setDirty(true);
368
+ this.scheduleAutosave();
369
+ }
370
+
371
+ markDirty() {
372
+ this.touch();
373
+ this.titlebar.refresh();
374
+ }
375
+
376
+ persistPrefs() {
377
+ savePrefs(this.prefs);
199
378
  }
200
379
 
201
380
  scheduleAutosave() {
202
- clearTimeout(this._autoTimer);
203
- this._autoTimer = setTimeout(() => {
381
+ clearTimeout(this.autosaveTimer);
382
+ if (!this.autosave || !this.doc.handle || !this.dirty) return;
383
+ this.autosaveTimer = setTimeout(() => {
204
384
  if (this.dirty && this.doc.handle) this.save(true);
205
- }, 2500);
385
+ }, AUTOSAVE_MS);
206
386
  }
207
387
 
208
- /* ===================== 历史 ===================== */
209
-
210
388
  pushHistory() {
211
- this.history.push(JSON.stringify(this.snapshot));
389
+ this.pushHistorySnapshot(JSON.stringify(this.snapshot));
390
+ }
391
+
392
+ pushHistorySnapshot(snapshot) {
393
+ this.history.push(snapshot);
212
394
  if (this.history.length > HISTORY_LIMIT) this.history.shift();
213
395
  this.future = [];
214
396
  }
215
397
 
398
+ beginGesture() {
399
+ this.pushHistory();
400
+ }
401
+
216
402
  canUndo() { return this.history.length > 0; }
217
403
  canRedo() { return this.future.length > 0; }
218
404
 
219
405
  undo() {
406
+ this.commitEditing({ render: false });
220
407
  if (!this.history.length) return;
221
408
  this.future.push(JSON.stringify(this.snapshot));
222
409
  this.snapshot = JSON.parse(this.history.pop());
410
+ this.index = clamp(this.index, 0, this.snapshot.slides.length - 1);
223
411
  this.selectedIds = [];
224
- this.notifyChange();
412
+ this.touch();
413
+ this.renderAll();
225
414
  }
226
415
 
227
416
  redo() {
417
+ this.commitEditing({ render: false });
228
418
  if (!this.future.length) return;
229
419
  this.history.push(JSON.stringify(this.snapshot));
230
420
  this.snapshot = JSON.parse(this.future.pop());
421
+ this.index = clamp(this.index, 0, this.snapshot.slides.length - 1);
231
422
  this.selectedIds = [];
232
- this.notifyChange();
233
- }
234
-
235
- /* ===================== 选择 ===================== */
236
-
237
- currentSlide() {
238
- return this.snapshot.slides[this.index] || this.snapshot.slides[0];
423
+ this.touch();
424
+ this.renderAll();
239
425
  }
240
426
 
241
- selectedById(id) {
242
- return this.currentSlide().objects.find((o) => o.id === id) || null;
427
+ notifyChange(opts = {}) {
428
+ if (this.editing) this.commitEditing({ render: false });
429
+ this.touch();
430
+ this.statusbar.setStatus('');
431
+ if (opts.canvasOnly && this.view === 'normal') {
432
+ this.canvas.render();
433
+ this.slidePane.render();
434
+ this.formatPane.render();
435
+ this.ribbon.refresh();
436
+ this.titlebar.refresh();
437
+ this.statusbar.refresh();
438
+ return;
439
+ }
440
+ this.renderAll();
243
441
  }
244
442
 
245
- firstSelected() {
246
- return this.selectedById(this.selectedIds[0]);
247
- }
443
+ /* ===================== 选择 ===================== */
248
444
 
249
445
  selectObjects(ids) {
250
- this.selectedIds = [...new Set(ids)];
446
+ const next = [...new Set(ids)].filter((id) => this.currentSlide()?.objects.some((o) => o.id === id));
447
+ if (this.editing && !next.includes(this.editing.id)) this.commitEditing({ render: false });
448
+ this.selectedIds = next;
251
449
  this.canvas.syncSelection();
252
- this.inspector.render();
253
- this.toolbar.refresh();
450
+ this.formatPane.render();
451
+ this.ribbon.refresh();
452
+ this.statusbar.refresh();
254
453
  }
255
454
 
256
455
  toggleSelect(id) {
257
456
  const set = new Set(this.selectedIds);
258
- if (set.has(id)) set.delete(id); else set.add(id);
457
+ if (set.has(id)) set.delete(id);
458
+ else set.add(id);
259
459
  this.selectObjects([...set]);
260
460
  }
261
461
 
262
462
  clearSelection() {
463
+ if (this.editing) this.commitEditing({ render: false });
263
464
  if (!this.selectedIds.length) return;
264
465
  this.selectedIds = [];
265
466
  this.canvas.syncSelection();
266
- this.inspector.render();
267
- this.toolbar.refresh();
467
+ this.formatPane.render();
468
+ this.ribbon.refresh();
469
+ this.statusbar.refresh();
470
+ }
471
+
472
+ selectAll() {
473
+ const slide = this.currentSlide();
474
+ if (!slide) return;
475
+ this.selectObjects(slide.objects.map((o) => o.id));
268
476
  }
269
477
 
270
478
  selectSlide(i) {
271
- this.index = Math.max(0, Math.min(this.snapshot.slides.length - 1, i));
479
+ this.commitEditing({ render: false });
480
+ const next = clamp(Number(i) || 0, 0, this.snapshot.slides.length - 1);
481
+ this.index = next;
272
482
  this.selectedIds = [];
483
+ this.tableCursor = null;
484
+ this.notesSession = false;
485
+ this.renderAll();
486
+ }
487
+
488
+ /* ===================== 文本编辑状态 ===================== */
489
+
490
+ beginTextEdit(obj, node, kind, meta = {}) {
491
+ this.editing = {
492
+ obj, id: obj.id, node, kind, meta,
493
+ before: JSON.stringify(this.snapshot),
494
+ changed: false,
495
+ range: null,
496
+ };
497
+ if (kind === 'cell') {
498
+ this.tableCursor = { objId: obj.id, ri: meta.ri, ci: meta.ci };
499
+ }
500
+ }
501
+
502
+ onSelectionChange() {
503
+ const e = this.editing;
504
+ if (!e?.node) return;
505
+ const sel = window.getSelection();
506
+ if (!sel?.rangeCount) return;
507
+ if (e.node.contains(sel.anchorNode) && e.node.contains(sel.focusNode)) {
508
+ e.range = sel.getRangeAt(0).cloneRange();
509
+ }
510
+ }
511
+
512
+ syncEditing() {
513
+ const e = this.editing;
514
+ if (!e) return;
515
+ if (!e.changed) {
516
+ this.pushHistorySnapshot(e.before);
517
+ e.changed = true;
518
+ }
519
+ if (e.kind === 'cell') {
520
+ const { ri, ci } = e.meta;
521
+ const rows = e.obj.props.rows;
522
+ if (rows[ri]) rows[ri][ci] = String(e.node.innerText || '').replace(/\n+$/, '');
523
+ } else if (e.kind === 'text') {
524
+ e.obj.props.html = sanitizeTextHtml(e.node.innerHTML);
525
+ } else if (e.kind === 'shape') {
526
+ e.obj.props.text = String(e.node.innerText || '').replace(/\n+$/, '');
527
+ }
528
+ this.markDirty();
529
+ this.ribbon.refresh();
530
+ this.titlebar.refresh();
531
+ }
532
+
533
+ noteEditChange() {
534
+ const e = this.editing;
535
+ if (!e || e.changed) return;
536
+ this.pushHistorySnapshot(e.before);
537
+ e.changed = true;
538
+ this.markDirty();
539
+ }
540
+
541
+ commitEditing({ render = true, node = null } = {}) {
542
+ const e = this.editing;
543
+ if (!e) return;
544
+ if (node && e.node !== node) return;
545
+ if (e.kind === 'cell') {
546
+ this.tableCursor = { objId: e.obj.id, ri: e.meta.ri, ci: e.meta.ci };
547
+ }
548
+ this.editing = null;
549
+ if (e.changed) {
550
+ this.setDirty(true);
551
+ if (render) this.notifyChange();
552
+ else {
553
+ // 不重建格式窗格:点击窗格控件触发的 blur 不能把正在点的 DOM 换掉
554
+ this.ribbon.refresh();
555
+ this.titlebar.refresh();
556
+ }
557
+ }
558
+ }
559
+
560
+ startEditingById(id) {
561
+ this.selectSlide(this.index);
562
+ this.selectObjects([id]);
563
+ setTimeout(() => this.canvas.editObject(id), 0);
564
+ }
565
+
566
+ editCellAt(objId, ri, ci) {
567
+ const obj = this.selectedById(objId);
568
+ if (!obj || obj.type !== 'table') return;
569
+ if (ri >= obj.props.rows.length || ci >= (obj.props.rows[0]?.length || 1)) return;
570
+ this.selectedIds = [obj.id];
273
571
  this.renderAll();
572
+ this.canvas.editCell(obj, ri, ci);
573
+ }
574
+
575
+ /* ===================== 文本格式 ===================== */
576
+
577
+ canFormatText() {
578
+ if (this.editing) return true;
579
+ const objs = this.selectedObjects();
580
+ return objs.some((o) => o.type === 'text' || o.type === 'shape' || o.type === 'table');
581
+ }
582
+
583
+ canRichText() {
584
+ if (this.editing) return this.editing.kind !== 'cell';
585
+ const objs = this.selectedObjects();
586
+ return objs.length > 0 && objs.every((o) => o.type === 'text' || o.type === 'shape');
587
+ }
588
+
589
+ canAlignText() {
590
+ return this.canRichText();
591
+ }
592
+
593
+ canList() {
594
+ if (this.editing) return this.editing.kind === 'text';
595
+ return this.selectedObjects().some((o) => o.type === 'text');
274
596
  }
275
597
 
276
- /* ===================== 对象编辑 ===================== */
598
+ textState() {
599
+ const base = {
600
+ bold: false, italic: false, underline: false, strike: false,
601
+ font: '', fontSize: 0, color: '', align: 'left', lineSpacing: 1, list: '', editing: false,
602
+ };
603
+ if (this.editing) {
604
+ const e = this.editing;
605
+ const sel = window.getSelection();
606
+ let node = sel?.anchorNode || e.node;
607
+ if (node.nodeType === Node.TEXT_NODE) node = node.parentElement;
608
+ if (!node || !e.node.contains(node)) node = e.node;
609
+ const cs = window.getComputedStyle(node);
610
+ const style = styleFromNode(node, e.node);
611
+ const block = closestBlock(node, e.node);
612
+ const alignMap = { left: 'left', start: 'left', center: 'center', right: 'right', justify: 'justify' };
613
+ const list = node.closest?.('ul,ol');
614
+ return {
615
+ ...base,
616
+ ...style,
617
+ align: alignMap[closeAlign(block)] || 'left',
618
+ lineSpacing: e.obj.props.lineSpacing || 1,
619
+ list: list ? (list.tagName === 'OL' ? 'number' : 'bullet') : '',
620
+ editing: true,
621
+ fontSize: parseFloat(cs.fontSize) || e.obj.props.fontSize || 24,
622
+ color: rgbToHex(cs.color) || e.obj.props.color || '',
623
+ };
624
+ }
625
+ const o = this.firstSelected();
626
+ if (!o) return base;
627
+ const p = o.props || {};
628
+ const defaultColor = themeOf(this.snapshot.theme).text;
629
+ return {
630
+ ...base,
631
+ bold: !!p.bold,
632
+ italic: !!p.italic,
633
+ underline: !!p.underline,
634
+ strike: !!p.strike,
635
+ font: p.font || '',
636
+ fontSize: p.fontSize || 0,
637
+ color: o.type === 'shape' ? (p.textColor || defaultColor) : (p.color || defaultColor),
638
+ align: p.align || 'left',
639
+ lineSpacing: p.lineSpacing || 1,
640
+ list: '',
641
+ editing: false,
642
+ };
643
+ }
644
+
645
+ toggleTextStyle(key) {
646
+ const command = { bold: 'bold', italic: 'italic', underline: 'underline', strike: 'strikeThrough' }[key];
647
+ if (!command) return;
648
+ if (this.editing?.kind === 'text') {
649
+ this.canvas.focusEditing?.();
650
+ document.execCommand(command, false);
651
+ this.syncEditing();
652
+ this.ribbon.refresh();
653
+ return;
654
+ }
655
+ if (this.editing?.kind === 'shape') {
656
+ const o = this.editing.obj;
657
+ const value = !o.props[key];
658
+ o.props[key] = value;
659
+ if (key === 'bold') this.editing.node.style.fontWeight = value ? '700' : '400';
660
+ else if (key === 'italic') this.editing.node.style.fontStyle = value ? 'italic' : 'normal';
661
+ else {
662
+ this.editing.node.style.textDecoration = [o.props.underline ? 'underline' : '', o.props.strike ? 'line-through' : '']
663
+ .filter(Boolean).join(' ') || 'none';
664
+ }
665
+ this.noteEditChange();
666
+ this.ribbon.refresh();
667
+ return;
668
+ }
669
+ if (this.editing) return;
670
+ if (!this.canRichText()) return;
671
+ const objs = this.selectedObjects();
672
+ const first = objs[0];
673
+ const value = !first?.props?.[key];
674
+ this.pushHistory();
675
+ for (const o of objs) {
676
+ if (o.type === 'text' || o.type === 'shape') o.props[key] = value;
677
+ }
678
+ this.notifyChange();
679
+ }
680
+
681
+ applyFontFamily(font) {
682
+ if (this.editing?.kind === 'text' && this.canvas.wrapSelection({ fontFamily: font })) {
683
+ this.ribbon.refresh();
684
+ return;
685
+ }
686
+ if (this.editing) {
687
+ const o = this.editing.obj;
688
+ if (this.editing.kind === 'cell') {
689
+ o.props.font = font;
690
+ this.editing.node.closest('table')?.querySelectorAll('td').forEach((td) => { td.style.fontFamily = font; });
691
+ } else {
692
+ for (const target of this.selectedObjects()) if (target.props) target.props.font = font;
693
+ this.editing.node.style.fontFamily = font;
694
+ }
695
+ this.noteEditChange();
696
+ this.ribbon.refresh();
697
+ return;
698
+ }
699
+ if (!this.canFormatText()) return;
700
+ this.pushHistory();
701
+ for (const o of this.selectedObjects()) {
702
+ if (o.props && o.type !== 'line') o.props.font = font;
703
+ }
704
+ this.notifyChange();
705
+ }
706
+
707
+ applyFontSize(px) {
708
+ const value = clamp(Math.round(Number(px) || 0), 6, 200);
709
+ if (!value) return;
710
+ if (this.editing?.kind === 'text' && this.canvas.wrapSelection({ fontSize: `${value}px` })) {
711
+ this.ribbon.refresh();
712
+ return;
713
+ }
714
+ if (this.editing) {
715
+ const o = this.editing.obj;
716
+ if (this.editing.kind === 'cell') {
717
+ o.props.fontSize = value;
718
+ this.editing.node.closest('table')?.querySelectorAll('td').forEach((td) => { td.style.fontSize = `${value}px`; });
719
+ } else {
720
+ for (const target of this.selectedObjects()) {
721
+ if (target.type === 'text') setObjectFontSize(target, value);
722
+ else if (target.props) target.props.fontSize = value;
723
+ }
724
+ this.editing.node.style.fontSize = `${value}px`;
725
+ }
726
+ this.noteEditChange();
727
+ this.ribbon.refresh();
728
+ return;
729
+ }
730
+ if (!this.canFormatText()) return;
731
+ this.pushHistory();
732
+ for (const o of this.selectedObjects()) {
733
+ if (o.type === 'text') setObjectFontSize(o, value);
734
+ else if (o.type === 'shape' || o.type === 'table') o.props.fontSize = value;
735
+ }
736
+ this.notifyChange();
737
+ }
738
+
739
+ setFontSize(px) { this.applyFontSize(px); }
740
+ setFontFamily(font) { this.applyFontFamily(font); }
741
+
742
+ stepFontSize(delta) {
743
+ const current = this.textState().fontSize || 24;
744
+ this.applyFontSize(current + (delta > 0 ? 2 : -2));
745
+ }
746
+
747
+ applyTextColor(color) {
748
+ const themed = color || themeOf(this.snapshot.theme).text;
749
+ if (this.editing?.kind === 'text' && this.canvas.wrapSelection({ color: themed })) {
750
+ this.ribbon.refresh();
751
+ return;
752
+ }
753
+ if (this.editing) {
754
+ if (this.editing.kind === 'cell') {
755
+ this.editing.obj.props.color = color;
756
+ this.editing.node.closest('table')?.querySelectorAll('td').forEach((td) => { td.style.color = themed; });
757
+ } else {
758
+ for (const o of this.selectedObjects()) {
759
+ if (o.type === 'shape') o.props.textColor = themed;
760
+ else if (o.props && o.type !== 'line') o.props.color = color;
761
+ }
762
+ this.editing.node.style.color = themed;
763
+ }
764
+ this.noteEditChange();
765
+ this.ribbon.refresh();
766
+ return;
767
+ }
768
+ if (!this.canFormatText()) return;
769
+ this.pushHistory();
770
+ for (const o of this.selectedObjects()) {
771
+ if (o.type === 'shape') o.props.textColor = themed;
772
+ else if (o.props && o.type !== 'line') o.props.color = color;
773
+ }
774
+ this.notifyChange();
775
+ }
776
+
777
+ applyAlign(align) {
778
+ if (this.editing?.kind === 'text') {
779
+ const command = { left: 'justifyLeft', center: 'justifyCenter', right: 'justifyRight', justify: 'justifyFull' }[align];
780
+ if (command) document.execCommand(command, false);
781
+ this.syncEditing();
782
+ this.ribbon.refresh();
783
+ return;
784
+ }
785
+ if (this.editing?.kind === 'shape') {
786
+ this.editing.obj.props.align = align;
787
+ this.editing.node.style.textAlign = align;
788
+ this.noteEditChange();
789
+ this.ribbon.refresh();
790
+ return;
791
+ }
792
+ if (this.editing) return;
793
+ if (!this.canAlignText()) return;
794
+ this.pushHistory();
795
+ for (const o of this.selectedObjects()) if (o.props) o.props.align = align;
796
+ this.notifyChange();
797
+ }
798
+
799
+ applyList(kind) {
800
+ if (this.editing) {
801
+ if (this.editing.kind !== 'text') return;
802
+ document.execCommand(kind === 'bullet' ? 'insertUnorderedList' : 'insertOrderedList', false);
803
+ this.syncEditing();
804
+ this.ribbon.refresh();
805
+ return;
806
+ }
807
+ if (!this.canRichText()) return;
808
+ this.pushHistory();
809
+ for (const o of this.selectedObjects()) {
810
+ if (o.type !== 'text') continue;
811
+ const lines = htmlToPlain(o.props.html).split('\n').map((s) => s.trim()).filter(Boolean);
812
+ if (!lines.length) continue;
813
+ const tag = kind === 'bullet' ? 'ul' : 'ol';
814
+ o.props.html = `<${tag}>${lines.map((line) => `<li>${escapeHtmlText(line)}</li>`).join('')}</${tag}>`;
815
+ }
816
+ this.notifyChange();
817
+ }
818
+
819
+ applyIndent(delta) {
820
+ if (!this.editing || this.editing.kind !== 'text') return;
821
+ // 只对列表项改层级:普通段落缩进不在对象模型里,做了也存不下来
822
+ if (!this.textState().list) return;
823
+ document.execCommand(delta > 0 ? 'indent' : 'outdent', false);
824
+ this.syncEditing();
825
+ this.ribbon.refresh();
826
+ }
827
+
828
+ applyLineSpacing(v) {
829
+ const value = clamp(Number(v) || 1, 0.6, 4);
830
+ if (this.editing) {
831
+ if (this.editing.kind === 'cell') return;
832
+ for (const o of this.selectedObjects()) if (o.props && (o.type === 'text' || o.type === 'shape')) o.props.lineSpacing = value;
833
+ this.editing.node.style.lineHeight = String(value * 1.2);
834
+ this.noteEditChange();
835
+ this.ribbon.refresh();
836
+ return;
837
+ }
838
+ if (!this.canRichText()) return;
839
+ this.pushHistory();
840
+ for (const o of this.selectedObjects()) if (o.props && (o.type === 'text' || o.type === 'shape')) o.props.lineSpacing = value;
841
+ this.notifyChange();
842
+ }
843
+
844
+ clearFormatting() {
845
+ if (this.editing?.kind === 'cell') {
846
+ const table = this.editing.obj;
847
+ Object.assign(table.props, { font: '', fontSize: 16, color: '' });
848
+ this.editing.node.closest('table')?.querySelectorAll('td').forEach((td) => {
849
+ td.style.fontFamily = '';
850
+ td.style.fontSize = '16px';
851
+ td.style.color = themeOf(this.snapshot.theme).text;
852
+ });
853
+ this.noteEditChange();
854
+ this.ribbon.refresh();
855
+ return;
856
+ }
857
+ if (this.editing?.kind === 'shape') {
858
+ const shape = this.editing.obj;
859
+ Object.assign(shape.props, {
860
+ font: '', fontSize: 18, textColor: '#ffffff', bold: false, italic: false,
861
+ underline: false, strike: false, align: 'center', lineSpacing: 1,
862
+ });
863
+ Object.assign(this.editing.node.style, {
864
+ fontFamily: '', fontSize: '18px', color: '#ffffff', fontWeight: '400',
865
+ fontStyle: 'normal', textDecoration: 'none', textAlign: 'center', lineHeight: '1.2',
866
+ });
867
+ this.noteEditChange();
868
+ this.ribbon.refresh();
869
+ return;
870
+ }
871
+ if (this.editing) {
872
+ this.canvas.focusEditing();
873
+ document.execCommand('removeFormat', false);
874
+ const o = this.editing.obj;
875
+ Object.assign(o.props, {
876
+ font: '', fontSize: 24, color: '', bold: false, italic: false,
877
+ underline: false, strike: false, lineSpacing: 1,
878
+ });
879
+ Object.assign(this.editing.node.style, {
880
+ fontFamily: '', fontSize: '24px', color: themeOf(this.snapshot.theme).text,
881
+ fontWeight: '400', fontStyle: 'normal', textDecoration: 'none', lineHeight: '1.2',
882
+ });
883
+ this.syncEditing();
884
+ this.ribbon.refresh();
885
+ return;
886
+ }
887
+ if (!this.selectedObjects().length) return;
888
+ this.pushHistory();
889
+ for (const o of this.selectedObjects()) {
890
+ if (o.type === 'text') {
891
+ const paras = htmlToParas(o.props.html);
892
+ for (const p of paras) {
893
+ for (const r of p.runs) {
894
+ r.bold = false; r.italic = false; r.underline = false; r.strike = false;
895
+ r.color = ''; r.font = ''; r.size = 0;
896
+ }
897
+ }
898
+ o.props.html = parasToHTML(paras);
899
+ Object.assign(o.props, { font: '', fontSize: 24, color: '', bold: false, italic: false, underline: false, strike: false, align: 'left', lineSpacing: 1 });
900
+ } else if (o.type === 'shape') {
901
+ Object.assign(o.props, { font: '', fontSize: 18, textColor: '#ffffff', bold: false, italic: false, underline: false, align: 'center', lineSpacing: 1, shadow: false });
902
+ } else if (o.type === 'table') {
903
+ Object.assign(o.props, { font: '', fontSize: 16, color: '', tableStyle: 'plain', headerRow: false, bandedRows: false });
904
+ }
905
+ }
906
+ this.notifyChange();
907
+ }
908
+
909
+ /* ===================== 对象属性/插入 ===================== */
277
910
 
278
911
  updateObject(id, patch) {
279
912
  const obj = this.selectedById(id);
280
913
  if (!obj) return;
281
914
  this.pushHistory();
282
915
  Object.assign(obj, patch);
283
- this.notifyChange({ thumbs: false });
916
+ this.notifyChange();
284
917
  }
285
918
 
286
919
  updateProps(id, patch) {
287
920
  const obj = this.selectedById(id);
288
921
  if (!obj) return;
289
922
  this.pushHistory();
290
- Object.assign(obj.props, patch);
923
+ if (patch.fontSize !== undefined && obj.type === 'text') setObjectFontSize(obj, Number(patch.fontSize));
924
+ else Object.assign(obj.props, patch);
291
925
  this.notifyChange();
292
926
  }
293
927
 
294
- setProp(key, value) {
295
- if (!this.selectedIds.length) return;
928
+ setSelectedProp(key, value) {
929
+ const objs = this.selectedObjects();
930
+ if (!objs.length) return;
296
931
  this.pushHistory();
297
- for (const obj of this.currentSlide().objects) {
298
- if (this.selectedIds.includes(obj.id)) obj.props[key] = value;
932
+ for (const o of objs) {
933
+ if (!o.props) continue;
934
+ if (key === 'stroke') {
935
+ o.props.stroke = value;
936
+ o.props.strokeW = value ? Math.max(1, Number(o.props.strokeW) || 1) : 0;
937
+ } else if (key === 'strokeW') {
938
+ o.props.strokeW = Math.max(0, Number(value) || 0);
939
+ if (o.props.strokeW > 0 && !o.props.stroke) o.props.stroke = themeOf(this.snapshot.theme).text;
940
+ } else if (key === 'kind') {
941
+ if (o.type === 'shape') o.props.kind = value;
942
+ } else if (key === 'shadow') {
943
+ if (o.type !== 'line') o.props.shadow = !!value;
944
+ } else {
945
+ o.props[key] = value;
946
+ }
299
947
  }
300
948
  this.notifyChange();
301
949
  }
302
950
 
303
- toggleProp(key) {
304
- if (!this.selectedIds.length) return;
951
+ setProp(key, value) { this.setSelectedProp(key, value); }
952
+
953
+ applyShapeQuickStyle(style) {
954
+ const objs = this.selectedObjects();
955
+ if (!objs.length) return;
305
956
  this.pushHistory();
306
- for (const obj of this.currentSlide().objects) {
307
- if (this.selectedIds.includes(obj.id)) obj.props[key] = !obj.props[key];
957
+ for (const o of objs) {
958
+ if (o.type === 'shape') {
959
+ o.props.fill = style.fill;
960
+ o.props.stroke = style.stroke;
961
+ o.props.strokeW = style.stroke ? 1.5 : 0;
962
+ o.props.textColor = style.text;
963
+ o.props.shadow = false;
964
+ } else if (o.type === 'line') {
965
+ o.props.stroke = style.stroke || style.fill || style.text;
966
+ o.props.strokeW = 2;
967
+ }
308
968
  }
309
969
  this.notifyChange();
310
970
  }
311
971
 
312
- setFontSize(px) {
313
- if (!this.selectedIds.length || !px) return;
972
+ rotateSelected(delta) {
973
+ const objs = this.selectedObjects();
974
+ if (!objs.length) return;
314
975
  this.pushHistory();
315
- for (const obj of this.currentSlide().objects) {
316
- if (this.selectedIds.includes(obj.id)) setObjectFontSize(obj, px);
317
- }
976
+ for (const o of objs) o.rot = (((Number(o.rot) || 0) + delta) % 360 + 360) % 360;
318
977
  this.notifyChange();
319
978
  }
320
979
 
321
- setFontFamily(font) {
322
- if (!this.selectedIds.length) return;
980
+ resetSelected() {
981
+ const objs = this.selectedObjects();
982
+ if (!objs.length) return;
323
983
  this.pushHistory();
324
- for (const obj of this.currentSlide().objects) {
325
- if (this.selectedIds.includes(obj.id)) obj.props.font = font;
984
+ for (const o of objs) {
985
+ o.rot = 0;
986
+ if (o.type === 'text') { o.w = 360; o.h = 110; }
987
+ else if (o.type === 'shape') { o.w = 220; o.h = 140; }
988
+ else if (o.type === 'table') { o.w = 440; o.h = 200; }
989
+ else if (o.type === 'line') { o.w = Math.sign(o.w || 1) * 240; o.h = 0; }
326
990
  }
327
991
  this.notifyChange();
328
992
  }
329
993
 
330
- /** 新建对象:落在当前页中心附近,自动选中 */
331
994
  insert(kind, variant) {
995
+ const size = this.size;
332
996
  const slide = this.currentSlide();
333
- const cx = Math.round((SLIDE_W - 360) / 2);
334
- const cy = Math.round((SLIDE_H - 110) / 2);
335
- const z = topZ(slide.objects) + 1;
336
- this.pushHistory();
997
+ if (!slide) return;
337
998
  let obj = null;
338
- if (kind === 'text') obj = createTextObject(cx, cy, z);
339
- else if (kind === 'shape') obj = createShapeObject(variant || 'rect', cx, cy, z);
340
- else if (kind === 'line') obj = createLineObject(cx, cy, z, false);
341
- else if (kind === 'arrow') obj = createLineObject(cx, cy, z, true);
342
- else if (kind === 'table') obj = createTableObject(cx, cy, z);
999
+ let w = 360;
1000
+ let h = 110;
1001
+ if (kind === 'text') { w = 360; h = 110; }
1002
+ else if (kind === 'shape') { w = 220; h = 140; }
1003
+ else if (kind === 'line' || kind === 'arrow') { w = 240; h = 0; }
1004
+ else if (kind === 'table') { w = 440; h = 200; }
343
1005
  else if (kind === 'image') { this.pickImage(); return; }
1006
+ const x = Math.round((size.w - w) / 2);
1007
+ const y = Math.round((size.h - h) / 2);
1008
+ const z = topZ(slide.objects) + 1;
1009
+ if (kind === 'text') obj = createTextObject(x, y, z);
1010
+ else if (kind === 'shape') {
1011
+ obj = createShapeObject(variant || 'rect', x, y, z);
1012
+ const accent = themeOf(this.snapshot.theme).accent;
1013
+ obj.props.fill = accent;
1014
+ obj.props.stroke = '';
1015
+ obj.props.strokeW = 0;
1016
+ obj.props.textColor = contrastText(accent);
1017
+ } else if (kind === 'line' || kind === 'arrow') {
1018
+ obj = createLineObject(x, y, z, kind === 'arrow');
1019
+ obj.props.stroke = themeOf(this.snapshot.theme).text;
1020
+ }
1021
+ else if (kind === 'table') obj = createTableObject(x, y, z);
344
1022
  if (!obj) return;
1023
+ this.pushHistory();
1024
+ slide.objects.push(obj);
1025
+ this.selectedIds = [obj.id];
1026
+ this.notifyChange();
1027
+ }
1028
+
1029
+ insertTable(rows, cols) {
1030
+ const size = this.size;
1031
+ const slide = this.currentSlide();
1032
+ if (!slide) return;
1033
+ const w = 440;
1034
+ const h = 200;
1035
+ const obj = createTableObject(Math.round((size.w - w) / 2), Math.round((size.h - h) / 2), topZ(slide.objects) + 1, rows, cols);
1036
+ this.pushHistory();
345
1037
  slide.objects.push(obj);
346
1038
  this.selectedIds = [obj.id];
347
1039
  this.notifyChange();
348
1040
  }
349
1041
 
350
- pickImage() {
351
- const input = document.createElement('input');
352
- input.type = 'file';
353
- input.accept = 'image/png,image/jpeg,image/gif';
354
- input.addEventListener('change', () => {
355
- const file = input.files?.[0];
356
- if (!file) return;
1042
+ async pickImage() {
1043
+ const file = await pickImageFile();
1044
+ if (!file) return;
1045
+ await this.insertImageFile(file);
1046
+ }
1047
+
1048
+ async insertImageFile(file, point = null) {
1049
+ if (!file || !/^image\/(png|jpeg|gif)$/i.test(file.type)) {
1050
+ notify.warning('只支持 PNG / JPEG / GIF 图片');
1051
+ return;
1052
+ }
1053
+ const src = await new Promise((resolve, reject) => {
357
1054
  const reader = new FileReader();
358
- reader.onload = () => {
359
- const img = new Image();
360
- img.onload = () => {
361
- const maxW = 480;
362
- const ratio = img.height / Math.max(1, img.width);
363
- const w = Math.min(maxW, img.width);
364
- const h = Math.round(w * ratio);
365
- const slide = this.currentSlide();
366
- this.pushHistory();
367
- const obj = createImageObject(reader.result, Math.round((SLIDE_W - w) / 2), Math.round((SLIDE_H - h) / 2), w, h, topZ(slide.objects) + 1);
368
- slide.objects.push(obj);
369
- this.selectedIds = [obj.id];
370
- this.notifyChange();
371
- };
372
- img.src = String(reader.result);
373
- };
1055
+ reader.onload = () => resolve(String(reader.result));
1056
+ reader.onerror = () => reject(reader.error);
374
1057
  reader.readAsDataURL(file);
1058
+ }).catch(() => '');
1059
+ if (!src) return;
1060
+ const img = await new Promise((resolve) => {
1061
+ const image = new Image();
1062
+ image.onload = () => resolve(image);
1063
+ image.onerror = () => resolve(null);
1064
+ image.src = src;
375
1065
  });
376
- input.click();
1066
+ if (!img) return;
1067
+ const size = this.size;
1068
+ const maxW = size.w * 0.62;
1069
+ const maxH = size.h * 0.62;
1070
+ const scale = Math.min(1, maxW / img.width, maxH / img.height);
1071
+ const w = Math.max(24, Math.round(img.width * scale));
1072
+ const h = Math.max(24, Math.round(img.height * scale));
1073
+ const cx = point ? point.x : size.w / 2;
1074
+ const cy = point ? point.y : size.h / 2;
1075
+ const x = clamp(Math.round(cx - w / 2), 0, Math.max(0, size.w - w));
1076
+ const y = clamp(Math.round(cy - h / 2), 0, Math.max(0, size.h - h));
1077
+ const slide = this.currentSlide();
1078
+ if (!slide) return;
1079
+ const obj = createImageObject(src, x, y, w, h, topZ(slide.objects) + 1);
1080
+ this.pushHistory();
1081
+ slide.objects.push(obj);
1082
+ this.selectedIds = [obj.id];
1083
+ this.notifyChange();
377
1084
  }
378
1085
 
379
- removeSelected() {
380
- if (!this.selectedIds.length) return;
1086
+ async replaceSelectedImage() {
1087
+ const obj = this.firstSelected();
1088
+ if (!obj || obj.type !== 'image') return;
1089
+ const file = await pickImageFile();
1090
+ if (!file) return;
1091
+ const src = await new Promise((resolve) => {
1092
+ const reader = new FileReader();
1093
+ reader.onload = () => resolve(String(reader.result));
1094
+ reader.onerror = () => resolve('');
1095
+ reader.readAsDataURL(file);
1096
+ });
1097
+ if (!src) return;
381
1098
  this.pushHistory();
382
- const slide = this.currentSlide();
383
- slide.objects = slide.objects.filter((o) => !this.selectedIds.includes(o.id));
384
- this.selectedIds = [];
1099
+ obj.props.src = src;
1100
+ obj.props.crop = { l: 0, t: 0, r: 0, b: 0 };
385
1101
  this.notifyChange();
386
1102
  }
387
1103
 
388
- duplicateSelected() {
389
- if (!this.selectedIds.length) return;
1104
+ resetSelectedImage() {
1105
+ const obj = this.firstSelected();
1106
+ if (!obj || obj.type !== 'image') return;
390
1107
  this.pushHistory();
391
- const slide = this.currentSlide();
392
- const copies = [];
393
- for (const o of slide.objects) {
394
- if (!this.selectedIds.includes(o.id)) continue;
395
- const c = cloneObject(o);
396
- c.x += 16;
397
- c.y += 16;
398
- c.z = topZ(slide.objects) + 1 + copies.length;
399
- copies.push(c);
400
- }
401
- slide.objects.push(...copies);
402
- this.selectedIds = copies.map((c) => c.id);
1108
+ obj.props.crop = { l: 0, t: 0, r: 0, b: 0 };
1109
+ obj.props.shadow = false;
403
1110
  this.notifyChange();
404
1111
  }
405
1112
 
1113
+ cropSelected() {
1114
+ const obj = this.firstSelected();
1115
+ if (!obj || obj.type !== 'image') return;
1116
+ const crop = obj.props.crop || { l: 0, t: 0, r: 0, b: 0 };
1117
+ let inputs = null;
1118
+ openModal({
1119
+ title: '裁剪图片',
1120
+ width: 420,
1121
+ confirmText: '应用',
1122
+ onConfirm: () => {
1123
+ if (!inputs) return;
1124
+ const v = (key) => clamp(Number(inputs[key].value) || 0, 0, 49);
1125
+ this.pushHistory();
1126
+ obj.props.crop = { l: v('l'), t: v('t'), r: v('r'), b: v('b') };
1127
+ this.notifyChange();
1128
+ },
1129
+ build: (body) => {
1130
+ inputs = {};
1131
+ for (const [key, label] of [['l', '左'], ['t', '上'], ['r', '右'], ['b', '下']]) {
1132
+ const input = numberInput(crop[key] || 0, { min: 0, max: 49 });
1133
+ inputs[key] = input;
1134
+ body.appendChild(field(`${label}侧裁剪 %`, input));
1135
+ }
1136
+ const hint = el('p', 'pp-backstage__muted', '按百分比裁掉图片四边;四边合计不超过 98%。');
1137
+ body.appendChild(hint);
1138
+ },
1139
+ });
1140
+ }
1141
+
1142
+ editAltText() {
1143
+ const obj = this.firstSelected();
1144
+ if (!obj || obj.type !== 'image') return;
1145
+ promptText({ title: '替代文字', label: '描述图片内容', value: obj.props.alt || '' }).then((value) => {
1146
+ if (value === null) return;
1147
+ this.pushHistory();
1148
+ obj.props.alt = value;
1149
+ this.notifyChange();
1150
+ });
1151
+ }
1152
+
1153
+ /* ===================== 剪贴板 ===================== */
1154
+
1155
+ canPaste() {
1156
+ return Boolean(this.editing) || Boolean(this.clipboard?.length);
1157
+ }
1158
+
406
1159
  copySelected() {
407
- if (!this.selectedIds.length) return;
408
- this.clipboard = this.currentSlide().objects.filter((o) => this.selectedIds.includes(o.id)).map((o) => JSON.parse(JSON.stringify(o)));
1160
+ if (this.editing) {
1161
+ document.execCommand('copy');
1162
+ notify.info('已复制所选文字');
1163
+ return;
1164
+ }
1165
+ const objs = this.selectedObjects();
1166
+ if (!objs.length) return;
1167
+ this.clipboard = objs.map((o) => JSON.parse(JSON.stringify(o)));
1168
+ this.ribbon.refresh();
1169
+ notify.info(`已复制 ${objs.length} 个对象`);
409
1170
  }
410
1171
 
411
1172
  cutSelected() {
1173
+ if (this.editing) {
1174
+ document.execCommand('cut');
1175
+ this.syncEditing();
1176
+ return;
1177
+ }
1178
+ if (!this.selectedObjects().length) return;
412
1179
  this.copySelected();
413
1180
  this.removeSelected();
414
1181
  }
415
1182
 
416
1183
  paste() {
1184
+ if (this.editing) {
1185
+ this.pastePlain();
1186
+ return;
1187
+ }
417
1188
  if (!this.clipboard?.length) return;
418
- this.pushHistory();
419
1189
  const slide = this.currentSlide();
1190
+ if (!slide) return;
1191
+ this.pushHistory();
420
1192
  const pasted = this.clipboard.map((o, i) => {
421
- const c = JSON.parse(JSON.stringify(o));
422
- c.id = `${c.id}-p${Date.now().toString(36)}${i}`;
423
- c.x += 16;
424
- c.y += 16;
425
- c.z = topZ(slide.objects) + 1 + i;
426
- return c;
1193
+ const copy = cloneObject(o);
1194
+ copy.x += 18;
1195
+ copy.y += 18;
1196
+ copy.z = topZ(slide.objects) + 1 + i;
1197
+ return copy;
427
1198
  });
428
1199
  slide.objects.push(...pasted);
429
- this.selectedIds = pasted.map((c) => c.id);
1200
+ this.selectedIds = pasted.map((o) => o.id);
1201
+ this.notifyChange();
1202
+ }
1203
+
1204
+ pasteText(text) {
1205
+ const value = String(text || '');
1206
+ if (!value.trim()) return;
1207
+ const html = value.split(/\r?\n/).map((line) => `<div>${escapeHtmlText(line) || '<br>'}</div>`).join('');
1208
+ const size = this.size;
1209
+ const obj = createTextObject(Math.round(size.w * 0.1), Math.round(size.h * 0.1), topZ(this.currentSlide().objects) + 1);
1210
+ obj.w = Math.min(640, Math.max(260, Math.round(size.w * 0.55)));
1211
+ obj.h = Math.min(280, Math.max(80, value.split(/\n/).length * 34));
1212
+ obj.props.html = html;
1213
+ obj.props.fontSize = 20;
1214
+ this.pushHistory();
1215
+ this.currentSlide().objects.push(obj);
1216
+ this.selectedIds = [obj.id];
1217
+ this.notifyChange();
1218
+ }
1219
+
1220
+ async pastePlain() {
1221
+ if (this.editing) {
1222
+ try {
1223
+ const text = await navigator.clipboard.readText();
1224
+ document.execCommand('insertText', false, text);
1225
+ this.syncEditing();
1226
+ } catch {
1227
+ notify.warning('浏览器未授予剪贴板读取权限');
1228
+ }
1229
+ return;
1230
+ }
1231
+ try {
1232
+ const text = await navigator.clipboard.readText();
1233
+ this.pasteText(text);
1234
+ } catch {
1235
+ notify.warning('浏览器未授予剪贴板读取权限,请直接用 Ctrl+V');
1236
+ }
1237
+ }
1238
+
1239
+ removeSelected() {
1240
+ const objs = this.selectedObjects();
1241
+ if (!objs.length) return;
1242
+ this.pushHistory();
1243
+ const ids = new Set(objs.map((o) => o.id));
1244
+ this.currentSlide().objects = this.currentSlide().objects.filter((o) => !ids.has(o.id));
1245
+ this.selectedIds = [];
1246
+ this.notifyChange();
1247
+ }
1248
+
1249
+ duplicateSelected() {
1250
+ const objs = this.selectedObjects();
1251
+ if (!objs.length) return;
1252
+ this.pushHistory();
1253
+ const slide = this.currentSlide();
1254
+ const copies = objs.map((o, i) => {
1255
+ const copy = cloneObject(o);
1256
+ copy.x += 16;
1257
+ copy.y += 16;
1258
+ copy.z = topZ(slide.objects) + 1 + i;
1259
+ return copy;
1260
+ });
1261
+ slide.objects.push(...copies);
1262
+ this.selectedIds = copies.map((o) => o.id);
1263
+ this.notifyChange();
1264
+ }
1265
+
1266
+ nudge(dx, dy) {
1267
+ const objs = this.selectedObjects();
1268
+ if (!objs.length) return;
1269
+ this.pushHistory();
1270
+ for (const o of objs) {
1271
+ o.x += dx;
1272
+ o.y += dy;
1273
+ }
1274
+ this.notifyChange({ canvasOnly: true });
1275
+ }
1276
+
1277
+ /* ===================== 排列/对齐 ===================== */
1278
+
1279
+ arrange(key) {
1280
+ const slide = this.currentSlide();
1281
+ const sel = this.selectedObjects();
1282
+ if (!sel.length) return;
1283
+ this.pushHistory();
1284
+ const sorted = [...slide.objects].sort((a, b) => (a.z || 0) - (b.z || 0));
1285
+ for (const o of sel) {
1286
+ const i = sorted.indexOf(o);
1287
+ if (key === 'front') { sorted.splice(i, 1); sorted.push(o); }
1288
+ else if (key === 'back') { sorted.splice(i, 1); sorted.unshift(o); }
1289
+ else if (key === 'forward' && i < sorted.length - 1) { sorted.splice(i, 1); sorted.splice(i + 1, 0, o); }
1290
+ else if (key === 'backward' && i > 0) { sorted.splice(i, 1); sorted.splice(i - 1, 0, o); }
1291
+ }
1292
+ sorted.forEach((o, i) => { o.z = i + 1; });
1293
+ this.notifyChange();
1294
+ }
1295
+
1296
+ alignToSlide(key) {
1297
+ const sel = this.selectedObjects();
1298
+ if (!sel.length) return;
1299
+ const size = this.size;
1300
+ this.pushHistory();
1301
+ for (const o of sel) {
1302
+ const r = objectRect(o);
1303
+ if (key === 'left') o.x = 0;
1304
+ else if (key === 'centerH') o.x = Math.round((size.w - r.width) / 2);
1305
+ else if (key === 'right') o.x = size.w - r.width;
1306
+ else if (key === 'top') o.y = 0;
1307
+ else if (key === 'middle') o.y = Math.round((size.h - r.height) / 2);
1308
+ else if (key === 'bottom') o.y = size.h - r.height;
1309
+ }
1310
+ this.notifyChange();
1311
+ }
1312
+
1313
+ distribute(axis) {
1314
+ const sel = this.selectedObjects();
1315
+ if (sel.length < 3) return;
1316
+ this.pushHistory();
1317
+ const items = sel.map((o) => ({ o, r: objectRect(o) }));
1318
+ items.sort((a, b) => (axis === 'h' ? a.r.left - b.r.left : a.r.top - b.r.top));
1319
+ const first = items[0];
1320
+ const last = items[items.length - 1];
1321
+ if (axis === 'h') {
1322
+ const start = first.r.left + first.r.width / 2;
1323
+ const end = last.r.left + last.r.width / 2;
1324
+ const step = (end - start) / (items.length - 1);
1325
+ items.forEach((item, i) => { item.o.x = Math.round(start + step * i - item.r.width / 2); });
1326
+ } else {
1327
+ const start = first.r.top + first.r.height / 2;
1328
+ const end = last.r.top + last.r.height / 2;
1329
+ const step = (end - start) / (items.length - 1);
1330
+ items.forEach((item, i) => { item.o.y = Math.round(start + step * i - item.r.height / 2); });
1331
+ }
1332
+ this.notifyChange();
1333
+ }
1334
+
1335
+ /* ===================== 表格 ===================== */
1336
+
1337
+ resizeTable(id, rows, cols) {
1338
+ const obj = this.selectedById(id);
1339
+ if (!obj || obj.type !== 'table') return;
1340
+ const r = clamp(Math.round(rows), 1, 50);
1341
+ const c = clamp(Math.round(cols), 1, 30);
1342
+ this.pushHistory();
1343
+ const cur = obj.props.rows;
1344
+ obj.props.rows = Array.from({ length: r }, (_, ri) => Array.from({ length: c }, (_, ci) => cur[ri]?.[ci] ?? ''));
1345
+ obj.props.colW = [];
1346
+ obj.props.rowH = [];
1347
+ this.notifyChange();
1348
+ }
1349
+
1350
+ insertTableRow(where) {
1351
+ const obj = this.firstSelected();
1352
+ if (!obj || obj.type !== 'table') return;
1353
+ const cur = this.tableCursor?.objId === obj.id ? this.tableCursor.ri : 0;
1354
+ const at = where === 'above' ? cur : cur + 1;
1355
+ this.pushHistory();
1356
+ obj.props.rows.splice(at, 0, Array.from({ length: obj.props.rows[0].length }, () => ''));
1357
+ obj.props.rowH = [];
1358
+ this.notifyChange();
1359
+ }
1360
+
1361
+ insertTableColumn(where) {
1362
+ const obj = this.firstSelected();
1363
+ if (!obj || obj.type !== 'table') return;
1364
+ const cur = this.tableCursor?.objId === obj.id ? this.tableCursor.ci : 0;
1365
+ const at = where === 'left' ? cur : cur + 1;
1366
+ this.pushHistory();
1367
+ for (const row of obj.props.rows) row.splice(at, 0, '');
1368
+ obj.props.colW = [];
1369
+ this.notifyChange();
1370
+ }
1371
+
1372
+ deleteTableRow() {
1373
+ const obj = this.firstSelected();
1374
+ if (!obj || obj.type !== 'table') return;
1375
+ if (obj.props.rows.length <= 1) return notify.warning('表格至少要保留一行');
1376
+ const cur = this.tableCursor?.objId === obj.id ? this.tableCursor.ri : 0;
1377
+ this.pushHistory();
1378
+ obj.props.rows.splice(Math.min(cur, obj.props.rows.length - 1), 1);
1379
+ obj.props.rowH = [];
430
1380
  this.notifyChange();
431
1381
  }
432
1382
 
433
- /** 层级调整 */
434
- arrange(key) {
435
- const slide = this.currentSlide();
436
- const sel = slide.objects.filter((o) => this.selectedIds.includes(o.id));
437
- if (!sel.length) return;
1383
+ deleteTableColumn() {
1384
+ const obj = this.firstSelected();
1385
+ if (!obj || obj.type !== 'table') return;
1386
+ const cols = obj.props.rows[0]?.length || 0;
1387
+ if (cols <= 1) return notify.warning('表格至少要保留一列');
1388
+ const cur = this.tableCursor?.objId === obj.id ? this.tableCursor.ci : 0;
438
1389
  this.pushHistory();
439
- const sorted = [...slide.objects].sort((a, b) => (a.z || 0) - (b.z || 0));
440
- for (const o of sel) {
441
- const i = sorted.indexOf(o);
442
- if (key === 'front') sorted.splice(i, 1), sorted.push(o);
443
- else if (key === 'back') sorted.splice(i, 1), sorted.unshift(o);
444
- else if (key === 'forward' && i < sorted.length - 1) { sorted.splice(i, 1); sorted.splice(i + 1, 0, o); }
445
- else if (key === 'backward' && i > 0) { sorted.splice(i, 1); sorted.splice(i - 1, 0, o); }
446
- }
447
- sorted.forEach((o, i) => { o.z = i + 1; });
1390
+ for (const row of obj.props.rows) row.splice(Math.min(cur, cols - 1), 1);
1391
+ obj.props.colW = [];
448
1392
  this.notifyChange();
449
1393
  }
450
1394
 
451
- /** 对齐页面 */
452
- alignToSlide(key) {
453
- const slide = this.currentSlide();
454
- const sel = slide.objects.filter((o) => this.selectedIds.includes(o.id));
455
- if (!sel.length) return;
1395
+ setTableStyle(style) {
1396
+ const obj = this.firstSelected();
1397
+ if (!obj || obj.type !== 'table') return;
456
1398
  this.pushHistory();
457
- for (const o of sel) {
458
- const r = objectRect(o);
459
- if (key === 'left') o.x = 0;
460
- else if (key === 'centerH') o.x = Math.round((SLIDE_W - r.width) / 2);
461
- else if (key === 'right') o.x = SLIDE_W - r.width;
462
- else if (key === 'top') o.y = 0;
463
- else if (key === 'middle') o.y = Math.round((SLIDE_H - r.height) / 2);
464
- else if (key === 'bottom') o.y = SLIDE_H - r.height;
465
- }
1399
+ obj.props.tableStyle = style;
1400
+ obj.props.headerRow = style !== 'plain';
1401
+ obj.props.bandedRows = style === 'banded' || style === 'dark';
466
1402
  this.notifyChange();
467
1403
  }
468
1404
 
469
- resizeTable(id, rows, cols) {
470
- const obj = this.selectedById(id);
1405
+ toggleHeaderRow() {
1406
+ const obj = this.firstSelected();
471
1407
  if (!obj || obj.type !== 'table') return;
472
1408
  this.pushHistory();
473
- const cur = obj.props.rows;
474
- const next = [];
475
- for (let r = 0; r < rows; r += 1) {
476
- const row = [];
477
- for (let c = 0; c < cols; c += 1) row.push(cur[r]?.[c] ?? '');
478
- next.push(row);
1409
+ obj.props.headerRow = !obj.props.headerRow;
1410
+ if (!obj.props.headerRow) {
1411
+ obj.props.tableStyle = obj.props.bandedRows ? (obj.props.tableStyle === 'dark' ? 'dark' : 'banded') : 'plain';
1412
+ } else if (obj.props.tableStyle === 'plain') {
1413
+ obj.props.tableStyle = 'header';
479
1414
  }
480
- obj.props.rows = next;
481
- obj.props.colW = [];
482
- obj.props.rowH = [];
483
1415
  this.notifyChange();
484
1416
  }
485
1417
 
486
- /** 文本列表(项目符号/编号):把正文各行包成列表 */
487
- applyList(tag) {
1418
+ toggleBandedRows() {
488
1419
  const obj = this.firstSelected();
489
- if (!obj || obj.type !== 'text') return;
1420
+ if (!obj || obj.type !== 'table') return;
490
1421
  this.pushHistory();
491
- const items = String(obj.props.html || '')
492
- .replace(/<\/?br\s*\/?>/gi, '\n')
493
- .replace(/<\/?[^>]+>/g, '\n')
494
- .split('\n')
495
- .map((s) => s.trim())
496
- .filter(Boolean);
497
- obj.props.html = `<${tag}>${items.map((t) => `<li>${t}</li>`).join('')}</${tag}>`;
1422
+ obj.props.bandedRows = !obj.props.bandedRows;
1423
+ if (obj.props.bandedRows) {
1424
+ if (obj.props.tableStyle === 'plain' || obj.props.tableStyle === 'header') obj.props.tableStyle = 'banded';
1425
+ } else if (obj.props.tableStyle === 'banded' || obj.props.tableStyle === 'dark') {
1426
+ obj.props.tableStyle = obj.props.headerRow ? 'header' : 'plain';
1427
+ }
498
1428
  this.notifyChange();
499
1429
  }
500
1430
 
501
1431
  /* ===================== 页操作 ===================== */
502
1432
 
503
- addSlide(key) {
1433
+ addSlide(layoutKey) {
1434
+ const slide = layoutKey ? createSlideWithLayout(layoutKey, this.size) : createSlide();
504
1435
  this.pushHistory();
505
- const slide = key ? createSlideWithLayout(key) : createSlide();
506
1436
  this.snapshot.slides.splice(this.index + 1, 0, slide);
507
1437
  this.index += 1;
508
1438
  this.selectedIds = [];
@@ -513,6 +1443,7 @@ export class SlidesApp {
513
1443
  this.pushHistory();
514
1444
  this.snapshot.slides.splice(this.index + 1, 0, copySlide(this.currentSlide()));
515
1445
  this.index += 1;
1446
+ this.selectedIds = [];
516
1447
  this.notifyChange();
517
1448
  }
518
1449
 
@@ -520,110 +1451,337 @@ export class SlidesApp {
520
1451
  if (this.snapshot.slides.length <= 1) return notify.warning('至少要保留一页');
521
1452
  this.pushHistory();
522
1453
  this.snapshot.slides.splice(this.index, 1);
523
- this.index = Math.max(0, this.index - 1);
1454
+ this.index = clamp(this.index, 0, this.snapshot.slides.length - 1);
524
1455
  this.selectedIds = [];
525
1456
  this.notifyChange();
526
1457
  }
527
1458
 
528
1459
  moveSlide(delta) {
529
- const next = this.index + delta;
530
- if (next < 0 || next >= this.snapshot.slides.length) return;
1460
+ this.moveSlideTo(this.index, this.index + delta);
1461
+ }
1462
+
1463
+ moveSlideTo(from, to) {
1464
+ const length = this.snapshot.slides.length;
1465
+ if (from < 0 || from >= length || to < 0 || to >= length || from === to) return;
531
1466
  this.pushHistory();
532
- const [slide] = this.snapshot.slides.splice(this.index, 1);
533
- this.snapshot.slides.splice(next, 0, slide);
534
- this.index = next;
1467
+ const [slide] = this.snapshot.slides.splice(from, 1);
1468
+ this.snapshot.slides.splice(to, 0, slide);
1469
+ this.index = to;
1470
+ this.selectedIds = [];
1471
+ this.notifyChange();
1472
+ }
1473
+
1474
+ toggleSlideHidden() {
1475
+ const slide = this.currentSlide();
1476
+ if (!slide) return;
1477
+ this.pushHistory();
1478
+ slide.hidden = !slide.hidden;
1479
+ this.notifyChange();
1480
+ }
1481
+
1482
+ setTransition(patch) {
1483
+ const slide = this.currentSlide();
1484
+ if (!slide) return;
1485
+ this.pushHistory();
1486
+ slide.transition = normalizeTransition({ ...transitionOf(slide), ...patch });
1487
+ this.notifyChange();
1488
+ }
1489
+
1490
+ applyTransitionAll() {
1491
+ const current = transitionOf(this.currentSlide());
1492
+ this.pushHistory();
1493
+ for (const slide of this.snapshot.slides) slide.transition = { ...current };
1494
+ this.notifyChange();
1495
+ notify.success('已把当前切换应用到全部幻灯片');
1496
+ }
1497
+
1498
+ previewTransition() {
1499
+ this.canvas.previewTransition(transitionOf(this.currentSlide()));
1500
+ }
1501
+
1502
+ setSlideBg(color) {
1503
+ const slide = this.currentSlide();
1504
+ if (!slide) return;
1505
+ this.pushHistory();
1506
+ slide.bg = color || '';
535
1507
  this.notifyChange();
536
1508
  }
537
1509
 
538
1510
  setTheme(key) {
539
- if (this.snapshot.theme === key) return;
1511
+ if (!THEMES[key] || this.snapshot.theme === key) return;
540
1512
  this.pushHistory();
541
1513
  this.snapshot.theme = key;
542
1514
  this.notifyChange();
543
1515
  }
544
1516
 
545
- setSlideBg(color) {
1517
+ setSlideSize(presetKey) {
1518
+ const preset = SLIDE_SIZES.find((s) => s.key === presetKey);
1519
+ if (!preset) return;
1520
+ if (this.size.w === preset.w && this.size.h === preset.h) return;
546
1521
  this.pushHistory();
547
- this.currentSlide().bg = color || '';
1522
+ scaleSnapshotSize(this.snapshot, { w: preset.w, h: preset.h });
548
1523
  this.notifyChange();
1524
+ this.fitToWindow();
1525
+ }
1526
+
1527
+ /* ===================== 视图/缩放 ===================== */
1528
+
1529
+ setView(view) {
1530
+ if (!['normal', 'sorter', 'reading'].includes(view)) return;
1531
+ this.commitEditing({ render: false });
1532
+ this.view = view;
1533
+ if (view !== 'normal') {
1534
+ this.selectedIds = [];
1535
+ this.findEl && (this.findEl.hidden = true);
1536
+ }
1537
+ this.updateLayout();
1538
+ this.renderAll();
1539
+ this.statusbar.refresh();
1540
+ this.ribbon.refresh();
549
1541
  }
550
1542
 
551
- setZoom(z) {
552
- this.zoom = Math.max(20, Math.min(200, Math.round(z)));
1543
+ setZoom(z, opts = {}) {
1544
+ this.zoom = clamp(Math.round(Number(z) || 100), ZOOM_MIN, ZOOM_MAX);
553
1545
  this.prefs.zoom = this.zoom;
554
1546
  savePrefs(this.prefs);
555
- this.canvas.render();
556
- this.renderStatus();
1547
+ if (this.view === 'normal') this.canvas.rescale();
1548
+ else if (this.view === 'sorter') this.renderSorter();
1549
+ else this.renderReading();
1550
+ this.statusbar.refresh();
1551
+ if (!opts.fromSlider) this.statusbar.slider.value = String(this.zoom);
557
1552
  }
558
1553
 
559
- /* ===================== 放映 ===================== */
1554
+ fitToWindow() {
1555
+ if (this.view !== 'normal') return;
1556
+ const w = Math.max(200, this.canvas.scroll.clientWidth - 72);
1557
+ const h = Math.max(150, this.canvas.scroll.clientHeight - 72);
1558
+ const size = this.size;
1559
+ this.setZoom(Math.min(w / size.w, h / size.h) * 100);
1560
+ }
560
1561
 
561
- present() {
562
- if (!this.snapshot.slides.length) return;
563
- this.presenter.open(this.index);
1562
+ toggleNotes() {
1563
+ this.commitEditing({ render: false });
1564
+ this.notesVisible = !this.notesVisible;
1565
+ this.prefs.notesVisible = this.notesVisible;
1566
+ savePrefs(this.prefs);
1567
+ this.updateLayout();
1568
+ this.renderNotes();
1569
+ this.ribbon.refresh();
1570
+ this.statusbar.refresh();
1571
+ }
1572
+
1573
+ toggleGrid() {
1574
+ this.commitEditing({ render: false });
1575
+ this.gridVisible = !this.gridVisible;
1576
+ this.prefs.grid = this.gridVisible;
1577
+ savePrefs(this.prefs);
1578
+ if (this.view === 'normal') this.canvas.render();
1579
+ this.ribbon.refresh();
1580
+ }
1581
+
1582
+ toggleGuides() {
1583
+ this.commitEditing({ render: false });
1584
+ this.guidesVisible = !this.guidesVisible;
1585
+ this.prefs.guides = this.guidesVisible;
1586
+ savePrefs(this.prefs);
1587
+ if (this.view === 'normal') this.canvas.render();
1588
+ this.ribbon.refresh();
1589
+ }
1590
+
1591
+ setRibbonCollapsed(on) {
1592
+ this.ribbonCollapsed = !!on;
1593
+ this.prefs.ribbonCollapsed = this.ribbonCollapsed;
1594
+ savePrefs(this.prefs);
1595
+ this.ribbon.setCollapsed(this.ribbonCollapsed);
1596
+ }
1597
+
1598
+ toggleFormatPane() {
1599
+ if (this.formatPaneOpen && this.view === 'normal') {
1600
+ this.formatPaneOpen = false;
1601
+ this.formatPane.close();
1602
+ } else {
1603
+ this.openFormatPane();
1604
+ return;
1605
+ }
1606
+ this.prefs.formatPaneOpen = this.formatPaneOpen;
1607
+ savePrefs(this.prefs);
1608
+ this.updateLayout();
1609
+ this.ribbon.refresh();
1610
+ }
1611
+
1612
+ openFormatPane() {
1613
+ if (this.view !== 'normal') this.setView('normal');
1614
+ this.formatPaneOpen = true;
1615
+ this.prefs.formatPaneOpen = true;
1616
+ savePrefs(this.prefs);
1617
+ this.updateLayout();
1618
+ this.formatPane.open();
1619
+ this.ribbon.refresh();
564
1620
  }
565
1621
 
566
- presentAt(i) {
567
- this.presenter.open(i);
1622
+ togglePresenter() {
1623
+ this.presentOptions.presenter = !this.presentOptions.presenter;
1624
+ this.prefs.presenter = this.presentOptions.presenter;
1625
+ savePrefs(this.prefs);
1626
+ this.ribbon.refresh();
1627
+ }
1628
+
1629
+ toggleLoop() {
1630
+ this.presentOptions.loop = !this.presentOptions.loop;
1631
+ this.prefs.loop = this.presentOptions.loop;
1632
+ savePrefs(this.prefs);
1633
+ this.ribbon.refresh();
568
1634
  }
569
1635
 
1636
+ /* ===================== 放映 ===================== */
1637
+
570
1638
  presentFromStart() {
1639
+ this.commitEditing({ render: false });
571
1640
  this.presenter.open(0);
572
1641
  }
573
1642
 
1643
+ presentFromCurrent() {
1644
+ this.commitEditing({ render: false });
1645
+ this.presenter.open(this.index);
1646
+ }
1647
+
1648
+ presentAt(index) {
1649
+ this.commitEditing({ render: false });
1650
+ this.presenter.open(Number(index) || 0);
1651
+ }
1652
+
574
1653
  /* ===================== 文件 ===================== */
575
1654
 
576
- newDoc() {
577
- const start = () => {
578
- this.doc = { name: '新建演示', handle: null };
579
- this.snapshot = createDraft();
580
- this.index = 0;
581
- this.selectedIds = [];
582
- this.history = [];
583
- this.future = [];
584
- this.setDirty(false);
585
- this.renderAll();
586
- };
587
- if (this.dirty && !window.confirm('当前演示有未保存的修改,新建将丢弃这些修改。\n\n确定继续吗?')) return;
588
- start();
1655
+ resetDoc(draft, name, handle = null) {
1656
+ this.snapshot = draft;
1657
+ this.doc = { name, handle, savedAt: 0 };
1658
+ this.snapshot.title = name;
1659
+ this.index = 0;
1660
+ this.selectedIds = [];
1661
+ this.editing = null;
1662
+ this.history = [];
1663
+ this.future = [];
1664
+ this.revision = 0;
1665
+ this.dirty = false;
1666
+ this.lastBytes = null;
1667
+ this.tableCursor = null;
1668
+ this.notesSession = false;
1669
+ this.view = 'normal';
1670
+ this.closeFind();
1671
+ this.renderAll();
1672
+ this.titlebar.refresh();
1673
+ }
1674
+
1675
+ async confirmDiscard(action) {
1676
+ if (!this.dirty) return true;
1677
+ return confirmDialog({
1678
+ title: action || '放弃更改?',
1679
+ message: '当前演示有未保存的更改,继续将丢弃这些更改。',
1680
+ confirmText: '继续',
1681
+ danger: true,
1682
+ });
1683
+ }
1684
+
1685
+ newDoc(layoutKey = '') {
1686
+ this.confirmDiscard('新建演示文稿').then((ok) => {
1687
+ if (!ok) return;
1688
+ const draft = createDraft();
1689
+ if (layoutKey) draft.slides = [createSlideWithLayout(layoutKey, draft.size)];
1690
+ const seq = Number(this.prefs.docSeq) || 1;
1691
+ this.prefs.docSeq = seq + 1;
1692
+ savePrefs(this.prefs);
1693
+ this.resetDoc(draft, `演示文稿${seq}`);
1694
+ this.backstage.close();
1695
+ notify.success('已新建空白演示');
1696
+ });
589
1697
  }
590
1698
 
591
1699
  async openFile() {
1700
+ if (!(await this.confirmDiscard('打开演示文稿'))) return;
592
1701
  try {
593
1702
  const picked = await openPptx();
594
1703
  if (!picked) return;
595
- if (this.dirty && !window.confirm('当前演示有未保存的修改,打开将丢弃这些修改。\n\n确定继续吗?')) return;
596
1704
  await this.applyBytes(picked.bytes, picked.name);
597
- this.doc = { name: picked.name.replace(/\.pptx$/i, ''), handle: picked.handle };
1705
+ this.doc.handle = picked.handle;
1706
+ this.doc.name = stripExt(picked.name) || '新建演示';
1707
+ this.snapshot.title = this.doc.name;
1708
+ this.titlebar.refresh();
1709
+ this.backstage.close();
598
1710
  notify.success(`已打开 ${picked.name}`);
599
1711
  } catch (err) {
600
1712
  notify.error(`打开失败:${err.message || err}`);
601
1713
  }
602
1714
  }
603
1715
 
1716
+ async importFile(file) {
1717
+ if (!file) return;
1718
+ if (!isPptxFile(file)) {
1719
+ if (/^image\/(png|jpeg|gif)$/i.test(file.type || '')) return this.insertImageFile(file);
1720
+ notify.error('请选择 .pptx 演示文稿或 PNG/JPEG/GIF 图片');
1721
+ return;
1722
+ }
1723
+ if (!(await this.confirmDiscard('打开演示文稿'))) return;
1724
+ try {
1725
+ const bytes = await readBytes(file);
1726
+ await this.applyBytes(bytes, file.name);
1727
+ this.backstage.close();
1728
+ notify.success(`已打开 ${file.name}`);
1729
+ } catch (err) {
1730
+ notify.error(`打开失败:${err.message || err}`);
1731
+ }
1732
+ }
1733
+
604
1734
  async applyBytes(bytes, name) {
605
- const snap = normalizeSnapshot(await parsePptx(bytes)) || createDraft();
606
- if (!snap.title) snap.title = String(name || '').replace(/\.pptx$/i, '');
1735
+ const raw = await parsePptx(bytes);
1736
+ const snap = normalizeSnapshot(raw);
1737
+ if (!snap) throw new Error('文件内容无法识别');
607
1738
  this.snapshot = snap;
1739
+ this.doc = { name: stripExt(name) || '新建演示', handle: null, savedAt: 0 };
1740
+ this.snapshot.title = this.doc.name;
608
1741
  this.index = 0;
609
1742
  this.selectedIds = [];
1743
+ this.editing = null;
610
1744
  this.history = [];
611
1745
  this.future = [];
612
- this.setDirty(false);
1746
+ this.revision = 0;
1747
+ this.dirty = false;
1748
+ this.lastBytes = bytes;
1749
+ this.tableCursor = null;
1750
+ this.notesSession = false;
1751
+ this.view = 'normal';
1752
+ this.closeFind();
613
1753
  this.renderAll();
1754
+ this.fitToWindow();
1755
+ const w = raw.warnings || {};
1756
+ const parts = [];
1757
+ if (w.groups) parts.push(`${w.groups} 个组合已摊平`);
1758
+ if (w.charts) parts.push(`${w.charts} 个图表已跳过`);
1759
+ if (w.media) parts.push(`${w.media} 个音视频已跳过`);
1760
+ if (w.unknown) parts.push(`${w.unknown} 个未知元素已跳过`);
1761
+ if (parts.length) notify.warning(`已导入;${parts.join('、')}`);
1762
+ return snap;
614
1763
  }
615
1764
 
616
1765
  async save(silent = false) {
617
1766
  if (!this.snapshot.slides.length) return false;
618
- if (!this.doc.handle) return this.saveAs();
1767
+ if (!this.doc.handle) return this.saveAs(this.doc.name);
1768
+ if (this.saving) return false;
619
1769
  this.saving = true;
1770
+ const rev = this.revision;
1771
+ this.statusbar.setStatus('正在保存…');
620
1772
  try {
1773
+ this.snapshot.title = this.doc.name;
621
1774
  const bytes = await buildPptxVerified(this.snapshot);
622
- await savePptx(bytes, `${this.doc.name || '新建演示'}.pptx`, this.doc.handle);
623
- this.setDirty(false);
1775
+ await savePptx(bytes, ensureExt(this.doc.name, '.pptx'), this.doc.handle);
1776
+ this.lastBytes = bytes;
1777
+ this.doc.savedAt = Date.now();
1778
+ if (this.revision === rev) this.setDirty(false);
1779
+ this.statusbar.setStatus('已保存');
1780
+ setTimeout(() => this.statusbar.setStatus(''), 1600);
624
1781
  if (!silent) notify.success('已保存');
625
1782
  return true;
626
1783
  } catch (err) {
1784
+ this.statusbar.setStatus('保存失败');
627
1785
  notify.error(`保存失败:${err.message || err}`);
628
1786
  return false;
629
1787
  } finally {
@@ -631,214 +1789,658 @@ export class SlidesApp {
631
1789
  }
632
1790
  }
633
1791
 
634
- async saveAs() {
1792
+ async saveAs(name) {
635
1793
  if (!this.snapshot.slides.length) return false;
1794
+ if (this.saving) return false;
1795
+ this.saving = true;
636
1796
  try {
1797
+ const suggested = stripExt(name || this.doc.name || '新建演示') || '新建演示';
1798
+ this.snapshot.title = suggested;
637
1799
  const bytes = await buildPptxVerified(this.snapshot);
638
- const result = await savePptxAs(bytes, this.doc.name || '新建演示');
1800
+ const result = await savePptxAs(bytes, suggested);
639
1801
  if (!result.saved) return false;
640
- this.doc = { name: (result.name || this.doc.name).replace(/\.pptx$/i, ''), handle: result.handle };
1802
+ this.doc = { name: stripExt(result.name || suggested), handle: result.handle, savedAt: Date.now() };
1803
+ this.snapshot.title = this.doc.name;
1804
+ this.lastBytes = bytes;
641
1805
  this.setDirty(false);
642
- this.renderHead();
1806
+ this.titlebar.refresh();
1807
+ if (this.backstage.el.isConnected) this.backstage.go(this.backstage.tab);
643
1808
  notify.success('已另存为');
644
1809
  return true;
645
1810
  } catch (err) {
646
1811
  notify.error(`另存失败:${err.message || err}`);
647
1812
  return false;
1813
+ } finally {
1814
+ this.saving = false;
648
1815
  }
649
1816
  }
650
1817
 
651
1818
  async exportPptx() {
652
1819
  if (!this.snapshot.slides.length) return;
653
1820
  try {
1821
+ this.snapshot.title = this.doc.name;
654
1822
  const bytes = await buildPptxVerified(this.snapshot);
1823
+ this.lastBytes = bytes;
655
1824
  downloadBlob(new Blob([bytes], { type: PPTX_MIME }), ensureExt(this.doc.name || '新建演示', '.pptx'));
1825
+ notify.success('已导出 .pptx');
656
1826
  } catch (err) {
657
1827
  notify.error(`导出失败:${err.message || err}`);
658
1828
  }
659
1829
  }
660
1830
 
661
1831
  exportPdf() {
662
- printSlides(this.snapshot.slides, this.snapshot.theme, (slide, theme) => renderPage(slide, theme));
1832
+ this.commitEditing({ render: false });
1833
+ printSlides(this.snapshot.slides, this.snapshot.theme, renderPage, this.size);
663
1834
  }
664
1835
 
665
- importDoc() {
666
- const input = document.createElement('input');
667
- input.type = 'file';
668
- input.accept = '.pptx';
669
- input.addEventListener('change', async () => {
670
- const file = input.files?.[0];
671
- if (!file) return;
672
- try {
673
- const bytes = new Uint8Array(await file.arrayBuffer());
674
- await this.applyBytes(bytes, file.name);
675
- this.doc = { name: file.name.replace(/\.pptx$/i, ''), handle: null };
676
- this.renderHead();
677
- notify.success(`已导入 ${file.name}`);
678
- } catch (err) {
679
- notify.error(`导入失败:${err.message || err}`);
1836
+ renameDoc(name) {
1837
+ const value = String(name || '').trim() || '新建演示';
1838
+ this.doc.name = value;
1839
+ this.snapshot.title = value;
1840
+ this.touch();
1841
+ this.titlebar.refresh();
1842
+ }
1843
+
1844
+ async closeDocument() {
1845
+ if (!(await this.confirmDiscard('关闭演示文稿'))) return;
1846
+ const seq = Number(this.prefs.docSeq) || 1;
1847
+ this.prefs.docSeq = seq + 1;
1848
+ savePrefs(this.prefs);
1849
+ this.resetDoc(createDraft(), `演示文稿${seq}`);
1850
+ this.backstage.close();
1851
+ notify.success('演示文稿已关闭');
1852
+ }
1853
+
1854
+ openBackstage(tab = 'home') {
1855
+ this.commitEditing({ render: false });
1856
+ this.backstage.open(tab);
1857
+ this.ribbon.setFileActive(true);
1858
+ }
1859
+
1860
+ closeBackstage() {
1861
+ if (!this.backstage || this.backstage.el.hidden) return;
1862
+ this.backstage.close();
1863
+ }
1864
+
1865
+ onBackstageClosed() {
1866
+ this.ribbon.setFileActive(false);
1867
+ this.ribbon.activate(this.ribbon.activeTab || 'home', { expand: false });
1868
+ }
1869
+
1870
+ /* ===================== 查找替换 ===================== */
1871
+
1872
+ openFind(replace = false) {
1873
+ if (this.view !== 'normal') this.setView('normal');
1874
+ this.commitEditing({ render: false });
1875
+ if (!this.findEl) this.buildFindBar();
1876
+ this.findEl.hidden = false;
1877
+ this.findEl.classList.toggle('is-replace', replace);
1878
+ this.findReplaceRow.hidden = !replace;
1879
+ this.findState.replace = replace;
1880
+ this.refreshMatches();
1881
+ this.findInput.focus();
1882
+ this.findInput.select();
1883
+ }
1884
+
1885
+ closeFind() {
1886
+ if (!this.findEl) return;
1887
+ this.findEl.hidden = true;
1888
+ }
1889
+
1890
+ buildFindBar() {
1891
+ const bar = el('div', 'pp-findbar');
1892
+ const top = el('div', 'pp-findbar__row');
1893
+ this.findInput = el('input', 'pp-input pp-findbar__input');
1894
+ this.findInput.type = 'text';
1895
+ this.findInput.placeholder = '查找';
1896
+ this.findCount = el('span', 'pp-findbar__count', '0/0');
1897
+ const prev = el('button', 'pp-iconbtn', '');
1898
+ prev.type = 'button';
1899
+ prev.title = '上一个';
1900
+ prev.innerHTML = icon('chevronUp', 15);
1901
+ const next = el('button', 'pp-iconbtn', '');
1902
+ next.type = 'button';
1903
+ next.title = '下一个';
1904
+ next.innerHTML = icon('chevronDown', 15);
1905
+ const close = el('button', 'pp-iconbtn', '');
1906
+ close.type = 'button';
1907
+ close.title = '关闭';
1908
+ close.innerHTML = icon('close', 15);
1909
+ top.append(this.findInput, this.findCount, prev, next, close);
1910
+
1911
+ this.findReplaceRow = el('div', 'pp-findbar__row');
1912
+ this.replaceInput = el('input', 'pp-input pp-findbar__input');
1913
+ this.replaceInput.type = 'text';
1914
+ this.replaceInput.placeholder = '替换为';
1915
+ const replaceBtn = el('button', 'pp-chip', '替换');
1916
+ replaceBtn.type = 'button';
1917
+ const allBtn = el('button', 'pp-chip', '全部替换');
1918
+ allBtn.type = 'button';
1919
+ this.findReplaceRow.append(this.replaceInput, replaceBtn, allBtn);
1920
+ bar.append(top, this.findReplaceRow);
1921
+ this.center.appendChild(bar);
1922
+ this.findEl = bar;
1923
+ this.findState = { replace: false, matches: [], cursor: -1 };
1924
+
1925
+ prev.addEventListener('click', () => this.findNext(true));
1926
+ next.addEventListener('click', () => this.findNext(false));
1927
+ close.addEventListener('click', () => this.closeFind());
1928
+ replaceBtn.addEventListener('click', () => this.replaceCurrent());
1929
+ allBtn.addEventListener('click', () => this.replaceAll());
1930
+ this.findInput.addEventListener('input', () => { this.refreshMatches(); this.findNext(false); });
1931
+ this.findInput.addEventListener('keydown', (e) => {
1932
+ if (e.key === 'Enter') { e.preventDefault(); this.findNext(e.shiftKey); }
1933
+ if (e.key === 'Escape') { e.preventDefault(); this.closeFind(); }
1934
+ });
1935
+ this.replaceInput.addEventListener('keydown', (e) => {
1936
+ if (e.key === 'Enter') { e.preventDefault(); this.replaceCurrent(); }
1937
+ if (e.key === 'Escape') { e.preventDefault(); this.closeFind(); }
1938
+ });
1939
+ }
1940
+
1941
+ objectTextFields(slide) {
1942
+ const fields = [];
1943
+ for (const o of slide.objects) {
1944
+ if (o.type === 'text') fields.push({ obj: o, field: 'html', text: htmlToPlain(o.props.html) });
1945
+ else if (o.type === 'shape') fields.push({ obj: o, field: 'text', text: o.props.text || '' });
1946
+ else if (o.type === 'table') fields.push({ obj: o, field: 'table', text: (o.props.rows || []).flat().join('\n') });
1947
+ }
1948
+ return fields;
1949
+ }
1950
+
1951
+ refreshMatches() {
1952
+ if (!this.findEl) return;
1953
+ const q = this.findInput.value;
1954
+ const matches = [];
1955
+ if (q) {
1956
+ this.snapshot.slides.forEach((slide, si) => {
1957
+ for (const f of this.objectTextFields(slide)) {
1958
+ if (f.text.toLowerCase().includes(q.toLowerCase())) matches.push({ si, objId: f.obj.id, field: f.field });
1959
+ }
1960
+ });
1961
+ }
1962
+ this.findState.matches = matches;
1963
+ this.findState.cursor = matches.length ? Math.min(this.findState.cursor, matches.length - 1) : -1;
1964
+ this.findCount.textContent = matches.length ? `${this.findState.cursor + 1}/${matches.length}` : '0/0';
1965
+ }
1966
+
1967
+ findNext(back = false) {
1968
+ const state = this.findState;
1969
+ if (!state?.matches?.length) return;
1970
+ state.cursor = back
1971
+ ? (state.cursor - 1 + state.matches.length) % state.matches.length
1972
+ : (state.cursor + 1) % state.matches.length;
1973
+ const match = state.matches[state.cursor];
1974
+ this.findCount.textContent = `${state.cursor + 1}/${state.matches.length}`;
1975
+ if (match.si !== this.index) this.selectSlide(match.si);
1976
+ this.selectObjects([match.objId]);
1977
+ this.canvas.flashObject(match.objId);
1978
+ this.statusbar.setStatus(`找到于第 ${match.si + 1} 页`);
1979
+ }
1980
+
1981
+ replaceCurrent() {
1982
+ const state = this.findState;
1983
+ const match = state?.matches?.[state.cursor];
1984
+ const q = this.findInput.value;
1985
+ if (!match || !q) return;
1986
+ const slide = this.snapshot.slides[match.si];
1987
+ const obj = slide.objects.find((o) => o.id === match.objId);
1988
+ if (!obj) return;
1989
+ this.pushHistory();
1990
+ const replacement = this.replaceInput.value;
1991
+ if (match.field === 'html') obj.props.html = replaceInHtml(obj.props.html, q, replacement);
1992
+ else if (match.field === 'text') obj.props.text = replaceInPlain(obj.props.text, q, replacement);
1993
+ else obj.props.rows = obj.props.rows.map((row) => row.map((cell) => replaceInPlain(cell, q, replacement)));
1994
+ this.notifyChange();
1995
+ this.refreshMatches();
1996
+ this.findNext(false);
1997
+ }
1998
+
1999
+ replaceAll() {
2000
+ const q = this.findInput.value;
2001
+ if (!q) return;
2002
+ const replacement = this.replaceInput.value;
2003
+ this.pushHistory();
2004
+ for (const slide of this.snapshot.slides) {
2005
+ for (const o of slide.objects) {
2006
+ if (o.type === 'text') o.props.html = replaceInHtml(o.props.html, q, replacement, true);
2007
+ else if (o.type === 'shape') o.props.text = replaceInPlain(o.props.text, q, replacement, true);
2008
+ else if (o.type === 'table') o.props.rows = o.props.rows.map((row) => row.map((cell) => replaceInPlain(cell, q, replacement, true)));
2009
+ }
2010
+ }
2011
+ this.notifyChange();
2012
+ this.refreshMatches();
2013
+ notify.success('已完成全部替换');
2014
+ }
2015
+
2016
+ /* ===================== 统计 ===================== */
2017
+
2018
+ showWordCount() {
2019
+ let chars = 0;
2020
+ let words = 0;
2021
+ let textBoxes = 0;
2022
+ let shapes = 0;
2023
+ let images = 0;
2024
+ let tables = 0;
2025
+ const allText = [];
2026
+ for (const slide of this.snapshot.slides) {
2027
+ for (const o of slide.objects) {
2028
+ if (o.type === 'text') { textBoxes += 1; allText.push(htmlToPlain(o.props.html)); }
2029
+ else if (o.type === 'shape') { shapes += 1; allText.push(o.props.text || ''); }
2030
+ else if (o.type === 'image') images += 1;
2031
+ else if (o.type === 'table') { tables += 1; allText.push(...o.props.rows.flat()); }
2032
+ else if (o.type === 'line') shapes += 1;
680
2033
  }
2034
+ }
2035
+ const text = allText.join('\n');
2036
+ chars = text.replace(/\s/g, '').length;
2037
+ words = (text.match(/[\u4e00-\u9fa5]|[A-Za-z0-9]+/g) || []).length;
2038
+ openModal({
2039
+ title: '字数统计',
2040
+ width: 420,
2041
+ confirmText: '关闭',
2042
+ build: (body) => {
2043
+ const grid = el('div', 'pp-info-grid');
2044
+ for (const [k, v] of [
2045
+ ['幻灯片', `${this.snapshot.slides.length} 页`],
2046
+ ['文字框', textBoxes],
2047
+ ['图形/线条', shapes],
2048
+ ['图片', images],
2049
+ ['表格', tables],
2050
+ ['字数', words],
2051
+ ['字符数(不计空格)', chars],
2052
+ ]) {
2053
+ const item = el('div', 'pp-info-grid__item');
2054
+ item.append(el('span', '', k), el('strong', '', String(v)));
2055
+ grid.appendChild(item);
2056
+ }
2057
+ body.appendChild(grid);
2058
+ },
681
2059
  });
682
- input.click();
683
2060
  }
684
2061
 
685
2062
  /* ===================== 右键菜单 ===================== */
686
2063
 
687
- openObjectMenu(x, y) {
688
- const hasSel = this.selectedIds.length > 0;
2064
+ openCanvasMenu(x, y) {
2065
+ const has = this.selectedObjects().length > 0;
2066
+ const o = this.firstSelected();
2067
+ const items = [];
2068
+ if (!has) {
2069
+ items.push(
2070
+ { label: '粘贴', icon: 'paste', shortcut: 'Ctrl+V', disabled: !this.canPaste(), onClick: () => this.paste() },
2071
+ { divided: true },
2072
+ { label: '新建文本框', icon: 'textBox', onClick: () => this.insert('text') },
2073
+ { label: '新建幻灯片', icon: 'newSlide', shortcut: 'Ctrl+M', onClick: () => this.addSlide() },
2074
+ { divided: true },
2075
+ { label: '设置背景格式…', icon: 'background', onClick: () => this.openFormatPane() },
2076
+ { label: '网格线', checked: this.gridVisible, onClick: () => this.toggleGrid() },
2077
+ { label: '参考线', checked: this.guidesVisible, onClick: () => this.toggleGuides() },
2078
+ );
2079
+ } else {
2080
+ items.push(
2081
+ { label: '剪切', icon: 'cut', shortcut: 'Ctrl+X', onClick: () => this.cutSelected() },
2082
+ { label: '复制', icon: 'copy', shortcut: 'Ctrl+C', onClick: () => this.copySelected() },
2083
+ { label: '粘贴', icon: 'paste', shortcut: 'Ctrl+V', disabled: !this.canPaste(), onClick: () => this.paste() },
2084
+ { label: '复制对象', icon: 'duplicate', shortcut: 'Ctrl+D', onClick: () => this.duplicateSelected() },
2085
+ { divided: true },
2086
+ { label: '置于顶层', icon: 'bringForward', onClick: () => this.arrange('front') },
2087
+ { label: '上移一层', onClick: () => this.arrange('forward') },
2088
+ { label: '下移一层', onClick: () => this.arrange('backward') },
2089
+ { label: '置于底层', icon: 'sendBackward', onClick: () => this.arrange('back') },
2090
+ { divided: true },
2091
+ {
2092
+ label: '对齐页面',
2093
+ icon: 'alignLeft',
2094
+ children: [
2095
+ { label: '左对齐', onClick: () => this.alignToSlide('left') },
2096
+ { label: '水平居中', onClick: () => this.alignToSlide('centerH') },
2097
+ { label: '右对齐', onClick: () => this.alignToSlide('right') },
2098
+ { divided: true },
2099
+ { label: '顶端对齐', onClick: () => this.alignToSlide('top') },
2100
+ { label: '垂直居中', onClick: () => this.alignToSlide('middle') },
2101
+ { label: '底端对齐', onClick: () => this.alignToSlide('bottom') },
2102
+ ],
2103
+ },
2104
+ { divided: true },
2105
+ );
2106
+ if (o?.type === 'text' || o?.type === 'shape') {
2107
+ items.push({ label: '编辑文字', icon: 'text', onClick: () => this.startEditingById(o.id) });
2108
+ }
2109
+ if (o?.type === 'image') {
2110
+ items.push(
2111
+ { label: '替换图片…', icon: 'replaceImage', onClick: () => this.replaceSelectedImage() },
2112
+ { label: '裁剪图片…', icon: 'crop', onClick: () => this.cropSelected() },
2113
+ );
2114
+ }
2115
+ if (o?.type === 'table') {
2116
+ items.push(
2117
+ { label: '在上方插入行', icon: 'rowAbove', onClick: () => this.insertTableRow('above') },
2118
+ { label: '在下方插入行', icon: 'rowBelow', onClick: () => this.insertTableRow('below') },
2119
+ { label: '在左侧插入列', icon: 'colLeft', onClick: () => this.insertTableColumn('left') },
2120
+ { label: '在右侧插入列', icon: 'colRight', onClick: () => this.insertTableColumn('right') },
2121
+ );
2122
+ }
2123
+ items.push(
2124
+ { label: '设置形状格式…', icon: 'formatPane', onClick: () => this.openFormatPane() },
2125
+ { divided: true },
2126
+ { label: '删除对象', icon: 'delete', shortcut: 'Del', danger: true, onClick: () => this.removeSelected() },
2127
+ );
2128
+ }
2129
+ openContextMenu({ x, y, items });
2130
+ }
2131
+
2132
+ openSlideMenu(x, y, index) {
2133
+ const slide = this.snapshot.slides[index];
2134
+ if (!slide) return;
689
2135
  openContextMenu({
690
- x, y,
2136
+ x,
2137
+ y,
691
2138
  items: [
692
- { label: '剪切', shortcut: 'Ctrl+X', disabled: !hasSel, onClick: () => this.cutSelected() },
693
- { label: '复制', shortcut: 'Ctrl+C', disabled: !hasSel, onClick: () => this.copySelected() },
694
- { label: '粘贴', shortcut: 'Ctrl+V', disabled: !this.clipboard?.length, onClick: () => this.paste() },
695
- { label: '复制对象', shortcut: 'Ctrl+D', disabled: !hasSel, onClick: () => this.duplicateSelected() },
2139
+ { label: '新建幻灯片', icon: 'newSlide', onClick: () => this.addSlide() },
2140
+ { label: '复制幻灯片', icon: 'duplicate', onClick: () => this.dupSlide() },
2141
+ { label: '删除幻灯片', icon: 'delete', danger: true, disabled: this.snapshot.slides.length <= 1, onClick: () => this.delSlide() },
696
2142
  { divided: true },
697
- { label: '置于顶层', disabled: !hasSel, onClick: () => this.arrange('front') },
698
- { label: '置于底层', disabled: !hasSel, onClick: () => this.arrange('back') },
2143
+ { label: '隐藏幻灯片', icon: 'hide', checked: !!slide.hidden, onClick: () => this.toggleSlideHidden() },
2144
+ {
2145
+ label: '新建页(版式)',
2146
+ icon: 'layout',
2147
+ children: SLIDE_LAYOUTS.map((l) => ({ label: l.label, onClick: () => this.addSlide(l.key) })),
2148
+ },
2149
+ {
2150
+ label: '切换',
2151
+ icon: 'transition',
2152
+ children: TRANSITIONS.map((t) => ({ label: t.label, onClick: () => this.setTransition({ type: t.key, dir: t.dir || 'l' }) })),
2153
+ },
699
2154
  { divided: true },
700
- { label: '删除对象', shortcut: 'Del', disabled: !hasSel, onClick: () => this.removeSelected() },
2155
+ { label: '设置背景格式…', icon: 'background', onClick: () => this.openFormatPane() },
701
2156
  ],
702
2157
  });
703
2158
  }
704
2159
 
705
- /* ===================== 菜单 ctx ===================== */
2160
+ /* ===================== 全局事件 ===================== */
706
2161
 
707
- menuCtx() {
708
- const app = this;
709
- return {
710
- state: {
711
- hasDoc: app.snapshot.slides.length > 0,
712
- autosave: app.autosave,
713
- canUndo: app.canUndo(),
714
- canRedo: app.canRedo(),
715
- hasSelection: app.selectedIds.length > 0,
716
- canPaste: Boolean(app.clipboard?.length),
717
- canRemoveSlide: app.snapshot.slides.length > 1,
718
- canMoveUp: app.index > 0,
719
- canMoveDown: app.index < app.snapshot.slides.length - 1,
720
- editing: app.firstSelected()?.type === 'text',
721
- bulletList: false,
722
- numberList: false,
723
- theme: app.snapshot.theme,
724
- notesVisible: app.notesVisible,
725
- },
726
- file: {
727
- newDoc: () => app.newDoc(),
728
- open: () => app.openFile(),
729
- save: () => app.save(),
730
- saveAs: () => app.saveAs(),
731
- setAutosave: (on) => { app.autosave = on; app.prefs.autosave = on; savePrefs(app.prefs); app.autosaveEl.checked = on; },
732
- importDoc: () => app.importDoc(),
733
- exportPptx: () => app.exportPptx(),
734
- exportPdf: () => app.exportPdf(),
735
- print: () => app.exportPdf(),
736
- },
737
- edit: {
738
- undo: () => app.undo(),
739
- redo: () => app.redo(),
740
- cut: () => app.cutSelected(),
741
- copy: () => app.copySelected(),
742
- paste: () => app.paste(),
743
- remove: () => app.removeSelected(),
744
- selectAll: () => app.selectObjects(app.currentSlide().objects.map((o) => o.id)),
745
- },
746
- insert: {
747
- text: () => app.insert('text'),
748
- image: () => app.insert('image'),
749
- shape: (kind) => app.insert('shape', kind),
750
- shapeKinds: SHAPE_KINDS,
751
- line: () => app.insert('line'),
752
- arrow: () => app.insert('arrow'),
753
- table: () => app.insert('table'),
754
- },
755
- slide: {
756
- new: () => app.addSlide(),
757
- newWithLayout: (key) => app.addSlide(key),
758
- duplicate: () => app.dupSlide(),
759
- remove: () => app.delSlide(),
760
- moveUp: () => app.moveSlide(-1),
761
- moveDown: () => app.moveSlide(1),
762
- background: () => app.editSlideBg(),
763
- },
764
- format: {
765
- bullet: () => app.applyList('ul'),
766
- numbered: () => app.applyList('ol'),
767
- align: (key) => app.alignToSlide(key),
768
- order: (key) => app.arrange(key),
769
- duplicate: () => app.duplicateSelected(),
770
- remove: () => app.removeSelected(),
771
- },
772
- design: {
773
- theme: (key) => app.setTheme(key),
774
- },
775
- view: {
776
- zoomIn: () => app.setZoom(app.zoom + 10),
777
- zoomOut: () => app.setZoom(app.zoom - 10),
778
- zoomReset: () => app.setZoom(60),
779
- present: () => app.present(),
780
- presentFromStart: () => app.presentFromStart(),
781
- toggleNotes: () => app.toggleNotes(),
782
- },
2162
+ bindGlobal() {
2163
+ this.onKeyBound = (e) => this.onKeyDown(e);
2164
+ this.onSelectionChangeBound = () => this.onSelectionChange();
2165
+ this.onBeforeUnloadBound = (e) => {
2166
+ if (!this.dirty) return;
2167
+ e.preventDefault();
2168
+ e.returnValue = '';
2169
+ };
2170
+ this.onDragOverBound = (e) => {
2171
+ if ([...e.dataTransfer.types].includes('Files')) e.preventDefault();
2172
+ };
2173
+ this.onDropBound = (e) => this.onDrop(e);
2174
+ this.onPasteBound = (e) => this.onPaste(e);
2175
+ this.onResizeBound = () => {
2176
+ if (this.view === 'reading') this.renderReading();
783
2177
  };
2178
+
2179
+ document.addEventListener('keydown', this.onKeyBound);
2180
+ document.addEventListener('selectionchange', this.onSelectionChangeBound);
2181
+ document.addEventListener('paste', this.onPasteBound);
2182
+ window.addEventListener('beforeunload', this.onBeforeUnloadBound);
2183
+ window.addEventListener('dragover', this.onDragOverBound);
2184
+ window.addEventListener('drop', this.onDropBound);
2185
+ window.addEventListener('resize', this.onResizeBound);
784
2186
  }
785
2187
 
786
- editSlideBg() {
787
- promptText({ title: '页面背景', label: '背景色 #rrggbb(留空跟随主题)', value: this.currentSlide().bg || '' }).then((v) => {
788
- if (v === null) return;
789
- this.setSlideBg(v.trim());
790
- });
2188
+ isTypingTarget(target) {
2189
+ return target instanceof Element && (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName));
2190
+ }
2191
+
2192
+ onKeyDown(e) {
2193
+ if (this.presenter?.el) return;
2194
+ if (this.backstage?.el && !this.backstage.el.hidden) return;
2195
+ const target = e.target;
2196
+ const typing = this.isTypingTarget(target);
2197
+ const mod = e.ctrlKey || e.metaKey;
2198
+ const k = e.key.toLowerCase();
2199
+
2200
+ if (mod && !e.altKey) {
2201
+ if (k === 's') { e.preventDefault(); e.shiftKey ? this.saveAs(this.doc.name) : this.save(); return; }
2202
+ if (k === 'o') { e.preventDefault(); this.openFile(); return; }
2203
+ if (k === 'n') { e.preventDefault(); this.newDoc(); return; }
2204
+ if (k === 'f') { e.preventDefault(); this.commitEditing({ render: false }); this.openFind(false); return; }
2205
+ if (k === 'h') { e.preventDefault(); this.commitEditing({ render: false }); this.openFind(true); return; }
2206
+ if (this.editing) {
2207
+ const styleKey = { b: 'bold', i: 'italic', u: 'underline' }[k];
2208
+ if (styleKey) { e.preventDefault(); this.toggleTextStyle(styleKey); return; }
2209
+ const alignKey = { l: 'left', e: 'center', r: 'right', j: 'justify' }[k];
2210
+ if (alignKey) { e.preventDefault(); this.applyAlign(alignKey); return; }
2211
+ }
2212
+ if (typing) return;
2213
+ if (k === 'z' && e.shiftKey) { e.preventDefault(); this.redo(); return; }
2214
+ if (k === 'z') { e.preventDefault(); this.undo(); return; }
2215
+ if (k === 'y') { e.preventDefault(); this.redo(); return; }
2216
+ if (k === 'm') { e.preventDefault(); this.addSlide(); return; }
2217
+ if (k === 'd') { e.preventDefault(); this.selectedIds.length ? this.duplicateSelected() : this.dupSlide(); return; }
2218
+ if (k === 'a') { e.preventDefault(); this.selectAll(); return; }
2219
+ if (k === 'c') { e.preventDefault(); this.copySelected(); return; }
2220
+ if (k === 'x') { e.preventDefault(); this.cutSelected(); return; }
2221
+ if (k === 'v') {
2222
+ // 有内部对象剪贴板才拦截;否则交给 paste 事件处理系统文字/图片
2223
+ if (this.canPaste()) { e.preventDefault(); this.paste(); }
2224
+ return;
2225
+ }
2226
+ const alignKey = { l: 'left', e: 'center', r: 'right', j: 'justify' }[k];
2227
+ if (alignKey) { e.preventDefault(); this.applyAlign(alignKey); return; }
2228
+ if (k === '=' || k === '+') { e.preventDefault(); this.setZoom(this.zoom + 10); return; }
2229
+ if (k === '-') { e.preventDefault(); this.setZoom(this.zoom - 10); return; }
2230
+ if (k === '0') { e.preventDefault(); this.setZoom(100); return; }
2231
+ if (k === 'b' && !typing) { e.preventDefault(); this.toggleTextStyle('bold'); return; }
2232
+ if (k === 'i' && !typing) { e.preventDefault(); this.toggleTextStyle('italic'); return; }
2233
+ if (k === 'u' && !typing) { e.preventDefault(); this.toggleTextStyle('underline'); return; }
2234
+ }
2235
+
2236
+ if (typing) {
2237
+ if (e.key === 'Escape' && this.findEl && !this.findEl.hidden) this.closeFind();
2238
+ return;
2239
+ }
2240
+
2241
+ if (e.key === 'F5') { e.preventDefault(); e.shiftKey ? this.presentFromCurrent() : this.presentFromStart(); return; }
2242
+ if (e.key === 'Escape') {
2243
+ if (this.findEl && !this.findEl.hidden) { this.closeFind(); return; }
2244
+ if (this.view !== 'normal') { this.setView('normal'); return; }
2245
+ this.clearSelection();
2246
+ return;
2247
+ }
2248
+ if (this.view === 'reading') {
2249
+ if (e.key === 'ArrowRight' || e.key === 'PageDown' || e.key === ' ') { e.preventDefault(); this.selectSlide(this.index + 1); }
2250
+ if (e.key === 'ArrowLeft' || e.key === 'PageUp') { e.preventDefault(); this.selectSlide(this.index - 1); }
2251
+ return;
2252
+ }
2253
+ if (this.view === 'sorter' && ['ArrowRight', 'ArrowLeft', 'ArrowUp', 'ArrowDown'].includes(e.key)) {
2254
+ e.preventDefault();
2255
+ const delta = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : -1;
2256
+ this.selectSlide(this.index + delta);
2257
+ return;
2258
+ }
2259
+
2260
+ if (e.key === 'Delete' || e.key === 'Backspace') {
2261
+ if (this.selectedIds.length) { e.preventDefault(); this.removeSelected(); }
2262
+ return;
2263
+ }
2264
+ if (e.key === 'F2' || e.key === 'Enter') {
2265
+ const o = this.firstSelected();
2266
+ if (o && (o.type === 'text' || o.type === 'shape')) {
2267
+ e.preventDefault();
2268
+ this.startEditingById(o.id);
2269
+ }
2270
+ return;
2271
+ }
2272
+ if (e.key === 'Tab') {
2273
+ const objs = this.currentSlide()?.objects || [];
2274
+ if (!objs.length) return;
2275
+ e.preventDefault();
2276
+ const current = this.selectedIds[0];
2277
+ const at = objs.findIndex((o) => o.id === current);
2278
+ const next = e.shiftKey ? (at - 1 + objs.length) % objs.length : (at + 1) % objs.length;
2279
+ this.selectObjects([objs[next].id]);
2280
+ return;
2281
+ }
2282
+ if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key) && this.selectedIds.length) {
2283
+ e.preventDefault();
2284
+ const step = e.shiftKey ? 10 : 1;
2285
+ const dx = e.key === 'ArrowLeft' ? -step : e.key === 'ArrowRight' ? step : 0;
2286
+ const dy = e.key === 'ArrowUp' ? -step : e.key === 'ArrowDown' ? step : 0;
2287
+ this.nudge(dx, dy);
2288
+ }
2289
+ }
2290
+
2291
+ onPaste(e) {
2292
+ const files = [...(e.clipboardData?.files || [])];
2293
+ const items = [...(e.clipboardData?.items || [])];
2294
+ const imageItem = items.find((i) => i.type.startsWith('image/'));
2295
+ const image = files.find((f) => /^image\/(png|jpeg|gif)$/i.test(f.type)) || imageItem?.getAsFile();
2296
+ if (image) {
2297
+ // 图片一律作为独立对象插入(正文里不支持内联图片)
2298
+ e.preventDefault();
2299
+ this.insertImageFile(image);
2300
+ return;
2301
+ }
2302
+ if (this.editing || this.isTypingTarget(e.target)) return;
2303
+ const text = e.clipboardData?.getData('text/plain');
2304
+ if (text && text.trim()) {
2305
+ e.preventDefault();
2306
+ this.pasteText(text);
2307
+ }
2308
+ }
2309
+
2310
+ async onDrop(e) {
2311
+ const files = [...(e.dataTransfer?.files || [])];
2312
+ if (!files.length) return;
2313
+ e.preventDefault();
2314
+ const pptx = files.find((f) => isPptxFile(f));
2315
+ if (pptx) {
2316
+ await this.importFile(pptx);
2317
+ return;
2318
+ }
2319
+ const images = files.filter((f) => /^image\/(png|jpeg|gif)$/i.test(f.type));
2320
+ if (!images.length) return;
2321
+ let point = null;
2322
+ if (this.canvas.el.contains(e.target) || e.target === this.canvas.el) {
2323
+ const rect = this.canvas.inner.getBoundingClientRect();
2324
+ point = { x: (e.clientX - rect.left) / (this.zoom / 100), y: (e.clientY - rect.top) / (this.zoom / 100) };
2325
+ }
2326
+ for (const image of images) await this.insertImageFile(image, point);
791
2327
  }
792
2328
 
793
- /** 自检:前端编解码往返(build → parse)——供控制台/自动化快速校验内核与 gbooxml 集成 */
2329
+ /* ===================== 自检 ===================== */
2330
+
794
2331
  async selfTest() {
795
2332
  const snap = {
796
- version: 1,
2333
+ version: 2,
797
2334
  title: '自检',
798
2335
  theme: 'midnight',
2336
+ size: { w: 960, h: 540 },
799
2337
  slides: [
800
2338
  {
801
2339
  id: 's1',
802
2340
  bg: '',
803
2341
  notes: '备注第一行\n第二行',
2342
+ hidden: false,
2343
+ transition: { type: 'fade', dir: 'l', speed: 'med' },
804
2344
  objects: [
805
- { id: 'o1', type: 'text', x: 40, y: 30, w: 400, h: 120, rot: 0, z: 1, props: { html: '<div>标题 <b>加粗</b></div>', font: '', fontSize: 32, color: '', align: 'left', bold: false, italic: false, underline: false } },
806
- { id: 'o2', type: 'shape', x: 500, y: 60, w: 220, h: 140, rot: 0, z: 2, props: { kind: 'round', fill: '#4c9be8', stroke: '#333333', strokeW: 2, text: '形状文字', textColor: '#ffffff', font: '', fontSize: 18, bold: false } },
807
- { id: 'o3', type: 'line', x: 260, y: 300, w: -200, h: 80, rot: 0, z: 3, props: { stroke: '#202124', strokeW: 2, dash: true, arrowEnd: true } },
808
- { id: 'o4', type: 'table', x: 120, y: 380, w: 440, h: 120, rot: 0, z: 4, props: { rows: [['A', 'B'], ['C', 'D']], headerRow: true, font: '', fontSize: 16, color: '', colW: [], rowH: [] } },
2345
+ { id: 'o1', type: 'text', x: 40, y: 30, w: 400, h: 120, rot: 0, z: 1, props: { html: '<div>标题 <b>加粗</b></div><ul><li>项目一</li><li>项目二</li></ul>', font: '', fontSize: 32, color: '', align: 'left', bold: false, italic: false, underline: false, strike: false, anchor: 'top', lineSpacing: 1, fill: '', stroke: '', strokeW: 0 } },
2346
+ { id: 'o2', type: 'shape', x: 500, y: 60, w: 220, h: 140, rot: 15, z: 2, props: { kind: 'star', fill: '#4c9be8', stroke: '#333333', strokeW: 2, dash: 'dash', shadow: true, text: '形状文字', textColor: '#ffffff', font: '', fontSize: 18, bold: false, italic: false, underline: false, align: 'center', anchor: 'middle' } },
2347
+ { id: 'o3', type: 'line', x: 260, y: 300, w: -200, h: 80, rot: 0, z: 3, props: { stroke: '#202124', strokeW: 2, dash: 'dot', arrowStart: true, arrowEnd: true } },
2348
+ { id: 'o4', type: 'table', x: 120, y: 380, w: 440, h: 120, rot: 0, z: 4, props: { rows: [['A', 'B'], ['C', 'D']], headerRow: true, bandedRows: true, tableStyle: 'banded', font: '', fontSize: 16, color: '', colW: [], rowH: [] } },
809
2349
  ],
810
2350
  },
811
- { id: 's2', bg: '#123456', notes: '', objects: [] },
2351
+ { id: 's2', bg: '#123456', notes: '', hidden: true, transition: { type: 'push', dir: 'u', speed: 'slow' }, objects: [] },
812
2352
  ],
813
2353
  };
814
2354
  const bytes = await buildPptxVerified(snap);
815
2355
  const back = await parsePptx(bytes);
816
2356
  return {
817
2357
  bytes: bytes.length,
2358
+ size: back.size,
818
2359
  slides: back.slides.length,
819
2360
  theme: back.theme,
820
- title: back.title,
821
- s1Objects: back.slides[0].objects.length,
822
- s1Types: back.slides[0].objects.map((o) => o.type),
823
- s1Notes: back.slides[0].notes,
824
- bg2: back.slides[1].bg,
2361
+ hidden: back.slides.map((s) => s.hidden),
2362
+ transition: back.slides.map((s) => s.transition.type),
2363
+ objects: back.slides[0].objects.map((o) => o.type),
2364
+ list: back.slides[0].objects[0]?.props?.html?.includes('<ul>'),
2365
+ tableStyle: back.slides[0].objects[3]?.props?.tableStyle,
825
2366
  };
826
2367
  }
827
-
828
- async start() {
829
- this.renderAll();
830
- notify.info('gbpptx 已就绪:可直接编辑,或用「打开」载入 .pptx');
831
- }
832
-
833
- destroy() {
834
- this.presenter.close();
835
- clearTimeout(this._autoTimer);
836
- }
837
2368
  }
838
2369
 
2370
+ /* ===================== 工具 ===================== */
2371
+
839
2372
  function loadPrefs() {
840
2373
  try { return JSON.parse(localStorage.getItem(LS_KEY) || '{}') || {}; } catch { return {}; }
841
2374
  }
2375
+
842
2376
  function savePrefs(prefs) {
843
2377
  try { localStorage.setItem(LS_KEY, JSON.stringify(prefs)); } catch { /* 忽略存储失败 */ }
844
2378
  }
2379
+
2380
+ function rgbToHex(css) {
2381
+ const m = String(css || '').match(/rgba?\(([^)]+)\)/i);
2382
+ if (!m) return /^#[0-9a-f]{6}$/i.test(css || '') ? String(css).toLowerCase() : '';
2383
+ const parts = m[1].split(',').map((s) => Number(s.trim()));
2384
+ if (parts.length < 3 || parts.some((n) => !Number.isFinite(n))) return '';
2385
+ return `#${parts.slice(0, 3).map((n) => clamp(Math.round(n), 0, 255).toString(16).padStart(2, '0')).join('')}`;
2386
+ }
2387
+
2388
+ function styleFromNode(node, root) {
2389
+ let bold = false;
2390
+ let italic = false;
2391
+ let underline = false;
2392
+ let strike = false;
2393
+ let font = '';
2394
+ let size = 0;
2395
+ let color = '';
2396
+ let el = node;
2397
+ while (el && el !== root.parentElement) {
2398
+ const tag = el.tagName;
2399
+ if (tag === 'B' || tag === 'STRONG') bold = true;
2400
+ if (tag === 'I' || tag === 'EM') italic = true;
2401
+ if (tag === 'U') underline = true;
2402
+ if (tag === 'S' || tag === 'STRIKE' || tag === 'DEL') strike = true;
2403
+ const cs = window.getComputedStyle(el);
2404
+ if (cs.fontWeight === 'bold' || Number(cs.fontWeight) >= 600) bold = true;
2405
+ if (cs.fontStyle === 'italic') italic = true;
2406
+ if (cs.textDecorationLine?.includes('underline') || cs.textDecoration?.includes('underline')) underline = true;
2407
+ if (cs.textDecorationLine?.includes('line-through') || cs.textDecoration?.includes('line-through')) strike = true;
2408
+ if (!font) font = cs.fontFamily || '';
2409
+ if (!size) size = parseFloat(cs.fontSize) || 0;
2410
+ if (!color) color = rgbToHex(cs.color);
2411
+ if (el === root) break;
2412
+ el = el.parentElement;
2413
+ }
2414
+ return { bold, italic, underline, strike, font, fontSize: size, color };
2415
+ }
2416
+
2417
+ function closestBlock(node, root) {
2418
+ let el = node;
2419
+ while (el && el !== root) {
2420
+ if (['DIV', 'P', 'LI', 'H1', 'H2', 'H3', 'BLOCKQUOTE'].includes(el.tagName)) return el;
2421
+ el = el.parentElement;
2422
+ }
2423
+ return root;
2424
+ }
2425
+
2426
+ function closeAlign(block) {
2427
+ const align = window.getComputedStyle(block).textAlign;
2428
+ return align || 'left';
2429
+ }
2430
+
2431
+ function replaceInHtml(html, query, replacement, all = false) {
2432
+ if (!html || !query) return html;
2433
+ const doc = new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html');
2434
+ const re = new RegExp(escapeRegExp(query), all ? 'gi' : 'i');
2435
+ const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT);
2436
+ const nodes = [];
2437
+ let n = walker.nextNode();
2438
+ while (n) { nodes.push(n); n = walker.nextNode(); }
2439
+ for (const node of nodes) node.data = node.data.replace(re, () => replacement);
2440
+ return doc.body.innerHTML;
2441
+ }
2442
+
2443
+ function replaceInPlain(text, query, replacement, all = false) {
2444
+ if (!text || !query) return text;
2445
+ return String(text).replace(new RegExp(escapeRegExp(query), all ? 'gi' : 'i'), () => replacement);
2446
+ }