gbpptx 0.2.0 → 0.4.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.
Files changed (46) hide show
  1. package/README.md +237 -214
  2. package/package.json +5 -3
  3. package/src/kernel/model.js +1 -2
  4. package/src/kernel/parts.js +11 -15
  5. package/src/kernel/print.js +14 -16
  6. package/web/app/main.js +8 -8
  7. package/web/app/slides/arrange.js +101 -0
  8. package/web/app/slides/clipboard.js +93 -0
  9. package/web/app/slides/file.js +213 -0
  10. package/web/app/slides/find.js +201 -0
  11. package/web/app/slides/history.js +100 -0
  12. package/web/app/slides/keys.js +179 -0
  13. package/web/app/slides/menus.js +105 -0
  14. package/web/app/slides/objects.js +254 -0
  15. package/web/app/slides/render.js +183 -0
  16. package/web/app/slides/shared.js +85 -0
  17. package/web/app/slides/slides.js +103 -0
  18. package/web/app/slides/table.js +102 -0
  19. package/web/app/slides/text.js +418 -0
  20. package/web/app/slides/view.js +156 -0
  21. package/web/app/slides-app.js +323 -2446
  22. package/web/app/ui/canvas.js +769 -755
  23. package/web/app/ui/color-panel.js +58 -76
  24. package/web/app/ui/dialogs.js +120 -159
  25. package/web/app/ui/file-io.js +116 -132
  26. package/web/app/ui/format-pane.js +427 -427
  27. package/web/app/ui/icons.js +129 -129
  28. package/web/app/ui/menu.js +75 -89
  29. package/web/app/ui/notify.js +45 -45
  30. package/web/app/ui/page-view.js +221 -221
  31. package/web/app/ui/popup.js +80 -80
  32. package/web/app/ui/present.js +292 -292
  33. package/web/app/ui/ribbon.js +868 -878
  34. package/web/app/ui/slide-pane.js +197 -189
  35. package/web/app/ui/statusbar.js +93 -93
  36. package/web/app/ui/text-styles.js +84 -84
  37. package/web/app/ui/titlebar.js +184 -67
  38. package/web/app/ui/transition.js +30 -30
  39. package/web/index.html +23 -21
  40. package/web/serve.mjs +22 -67
  41. package/web/styles/office.css +466 -644
  42. package/web/styles/slides.css +97 -219
  43. package/web/styles/tokens.css +154 -155
  44. package/src/kernel/util/escape.js +0 -21
  45. package/src/kernel/util/id.js +0 -13
  46. package/web/app/ui/backstage.js +0 -255
@@ -1,2446 +1,323 @@
1
- // [文件] gbpptx·SlidesApp —— Office 式演示编辑器装配(Ribbon/窗格/画布/放映/文件读写/查找替换)
2
-
3
- import {
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,
8
- } from '../../src/kernel/model.js';
9
- import { buildPptxVerified } from '../../src/kernel/roundtrip.js';
10
- import { parsePptx } from '../../src/kernel/read.js';
11
- import { printSlides } from '../../src/kernel/print.js';
12
- import { htmlToParas, parasToHTML, sanitizeTextHtml } from '../../src/kernel/text.js';
13
- import { notify } from './ui/notify.js';
14
- import { TitleBar } from './ui/titlebar.js';
15
- import { Ribbon } from './ui/ribbon.js';
16
- import { SlidePane } from './ui/slide-pane.js';
17
- import { Canvas } from './ui/canvas.js';
18
- import { FormatPane } from './ui/format-pane.js';
19
- import { StatusBar } from './ui/statusbar.js';
20
- import { Backstage } from './ui/backstage.js';
21
- import { Present } from './ui/present.js';
22
- import { renderPage } from './ui/page-view.js';
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
- };
47
-
48
- export class SlidesApp {
49
- constructor(mount) {
50
- this.mount = mount;
51
- const prefs = loadPrefs();
52
- this.prefs = prefs;
53
- this.snapshot = createDraft();
54
- this.index = 0;
55
- this.selectedIds = [];
56
- this.zoom = clamp(Number(prefs.zoom) || 65, ZOOM_MIN, ZOOM_MAX);
57
- this.dirty = false;
58
- this.saving = false;
59
- this.revision = 0;
60
- this.history = [];
61
- this.future = [];
62
- this.clipboard = null;
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
-
81
- this.build();
82
- this.bindGlobal();
83
- this.presenter = new Present(this);
84
- this.backstage = new Backstage(this);
85
- }
86
-
87
- /* ===================== 骨架 ===================== */
88
-
89
- get size() {
90
- return sizeOf(this.snapshot);
91
- }
92
-
93
- build() {
94
- const root = el('div', 'pp-app');
95
- root.innerHTML = `
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>
111
- </div>
112
- <div class="pp-statusbar-host"></div>`;
113
- this.mount.appendChild(root);
114
- this.root = root;
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);
125
- this.canvas = new Canvas(this);
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
- }
146
-
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('正在编辑备注');
159
- });
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());
167
- }
168
-
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;
215
- });
216
- }
217
-
218
- /* ===================== 启动/销毁 ===================== */
219
-
220
- start() {
221
- this.renderAll();
222
- notify.info('已就绪:可直接编辑,或用「文件 → 打开」载入 .pptx');
223
- }
224
-
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);
235
- }
236
-
237
- /* ===================== 渲染 ===================== */
238
-
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();
268
- }
269
- this.slidePane.render();
270
- this.formatPane.render();
271
- this.ribbon.refresh();
272
- this.titlebar.refresh();
273
- this.statusbar.refresh();
274
- }
275
-
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;
289
- }
290
-
291
- renderNotes() {
292
- const slide = this.currentSlide();
293
- if (this.notesText && document.activeElement !== this.notesText) this.notesText.value = slide?.notes || '';
294
- }
295
-
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
- });
320
- }
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
-
360
- setDirty(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);
378
- }
379
-
380
- scheduleAutosave() {
381
- clearTimeout(this.autosaveTimer);
382
- if (!this.autosave || !this.doc.handle || !this.dirty) return;
383
- this.autosaveTimer = setTimeout(() => {
384
- if (this.dirty && this.doc.handle) this.save(true);
385
- }, AUTOSAVE_MS);
386
- }
387
-
388
- pushHistory() {
389
- this.pushHistorySnapshot(JSON.stringify(this.snapshot));
390
- }
391
-
392
- pushHistorySnapshot(snapshot) {
393
- this.history.push(snapshot);
394
- if (this.history.length > HISTORY_LIMIT) this.history.shift();
395
- this.future = [];
396
- }
397
-
398
- beginGesture() {
399
- this.pushHistory();
400
- }
401
-
402
- canUndo() { return this.history.length > 0; }
403
- canRedo() { return this.future.length > 0; }
404
-
405
- undo() {
406
- this.commitEditing({ render: false });
407
- if (!this.history.length) return;
408
- this.future.push(JSON.stringify(this.snapshot));
409
- this.snapshot = JSON.parse(this.history.pop());
410
- this.index = clamp(this.index, 0, this.snapshot.slides.length - 1);
411
- this.selectedIds = [];
412
- this.touch();
413
- this.renderAll();
414
- }
415
-
416
- redo() {
417
- this.commitEditing({ render: false });
418
- if (!this.future.length) return;
419
- this.history.push(JSON.stringify(this.snapshot));
420
- this.snapshot = JSON.parse(this.future.pop());
421
- this.index = clamp(this.index, 0, this.snapshot.slides.length - 1);
422
- this.selectedIds = [];
423
- this.touch();
424
- this.renderAll();
425
- }
426
-
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();
441
- }
442
-
443
- /* ===================== 选择 ===================== */
444
-
445
- selectObjects(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;
449
- this.canvas.syncSelection();
450
- this.formatPane.render();
451
- this.ribbon.refresh();
452
- this.statusbar.refresh();
453
- }
454
-
455
- toggleSelect(id) {
456
- const set = new Set(this.selectedIds);
457
- if (set.has(id)) set.delete(id);
458
- else set.add(id);
459
- this.selectObjects([...set]);
460
- }
461
-
462
- clearSelection() {
463
- if (this.editing) this.commitEditing({ render: false });
464
- if (!this.selectedIds.length) return;
465
- this.selectedIds = [];
466
- this.canvas.syncSelection();
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));
476
- }
477
-
478
- selectSlide(i) {
479
- this.commitEditing({ render: false });
480
- const next = clamp(Number(i) || 0, 0, this.snapshot.slides.length - 1);
481
- this.index = next;
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];
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');
596
- }
597
-
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
- /* ===================== 对象属性/插入 ===================== */
910
-
911
- updateObject(id, patch) {
912
- const obj = this.selectedById(id);
913
- if (!obj) return;
914
- this.pushHistory();
915
- Object.assign(obj, patch);
916
- this.notifyChange();
917
- }
918
-
919
- updateProps(id, patch) {
920
- const obj = this.selectedById(id);
921
- if (!obj) return;
922
- this.pushHistory();
923
- if (patch.fontSize !== undefined && obj.type === 'text') setObjectFontSize(obj, Number(patch.fontSize));
924
- else Object.assign(obj.props, patch);
925
- this.notifyChange();
926
- }
927
-
928
- setSelectedProp(key, value) {
929
- const objs = this.selectedObjects();
930
- if (!objs.length) return;
931
- this.pushHistory();
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
- }
947
- }
948
- this.notifyChange();
949
- }
950
-
951
- setProp(key, value) { this.setSelectedProp(key, value); }
952
-
953
- applyShapeQuickStyle(style) {
954
- const objs = this.selectedObjects();
955
- if (!objs.length) return;
956
- this.pushHistory();
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
- }
968
- }
969
- this.notifyChange();
970
- }
971
-
972
- rotateSelected(delta) {
973
- const objs = this.selectedObjects();
974
- if (!objs.length) return;
975
- this.pushHistory();
976
- for (const o of objs) o.rot = (((Number(o.rot) || 0) + delta) % 360 + 360) % 360;
977
- this.notifyChange();
978
- }
979
-
980
- resetSelected() {
981
- const objs = this.selectedObjects();
982
- if (!objs.length) return;
983
- this.pushHistory();
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; }
990
- }
991
- this.notifyChange();
992
- }
993
-
994
- insert(kind, variant) {
995
- const size = this.size;
996
- const slide = this.currentSlide();
997
- if (!slide) return;
998
- let obj = null;
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; }
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);
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();
1037
- slide.objects.push(obj);
1038
- this.selectedIds = [obj.id];
1039
- this.notifyChange();
1040
- }
1041
-
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) => {
1054
- const reader = new FileReader();
1055
- reader.onload = () => resolve(String(reader.result));
1056
- reader.onerror = () => reject(reader.error);
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;
1065
- });
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();
1084
- }
1085
-
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;
1098
- this.pushHistory();
1099
- obj.props.src = src;
1100
- obj.props.crop = { l: 0, t: 0, r: 0, b: 0 };
1101
- this.notifyChange();
1102
- }
1103
-
1104
- resetSelectedImage() {
1105
- const obj = this.firstSelected();
1106
- if (!obj || obj.type !== 'image') return;
1107
- this.pushHistory();
1108
- obj.props.crop = { l: 0, t: 0, r: 0, b: 0 };
1109
- obj.props.shadow = false;
1110
- this.notifyChange();
1111
- }
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
-
1159
- copySelected() {
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} 个对象`);
1170
- }
1171
-
1172
- cutSelected() {
1173
- if (this.editing) {
1174
- document.execCommand('cut');
1175
- this.syncEditing();
1176
- return;
1177
- }
1178
- if (!this.selectedObjects().length) return;
1179
- this.copySelected();
1180
- this.removeSelected();
1181
- }
1182
-
1183
- paste() {
1184
- if (this.editing) {
1185
- this.pastePlain();
1186
- return;
1187
- }
1188
- if (!this.clipboard?.length) return;
1189
- const slide = this.currentSlide();
1190
- if (!slide) return;
1191
- this.pushHistory();
1192
- const pasted = this.clipboard.map((o, i) => {
1193
- const copy = cloneObject(o);
1194
- copy.x += 18;
1195
- copy.y += 18;
1196
- copy.z = topZ(slide.objects) + 1 + i;
1197
- return copy;
1198
- });
1199
- slide.objects.push(...pasted);
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 = [];
1380
- this.notifyChange();
1381
- }
1382
-
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;
1389
- this.pushHistory();
1390
- for (const row of obj.props.rows) row.splice(Math.min(cur, cols - 1), 1);
1391
- obj.props.colW = [];
1392
- this.notifyChange();
1393
- }
1394
-
1395
- setTableStyle(style) {
1396
- const obj = this.firstSelected();
1397
- if (!obj || obj.type !== 'table') return;
1398
- this.pushHistory();
1399
- obj.props.tableStyle = style;
1400
- obj.props.headerRow = style !== 'plain';
1401
- obj.props.bandedRows = style === 'banded' || style === 'dark';
1402
- this.notifyChange();
1403
- }
1404
-
1405
- toggleHeaderRow() {
1406
- const obj = this.firstSelected();
1407
- if (!obj || obj.type !== 'table') return;
1408
- this.pushHistory();
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';
1414
- }
1415
- this.notifyChange();
1416
- }
1417
-
1418
- toggleBandedRows() {
1419
- const obj = this.firstSelected();
1420
- if (!obj || obj.type !== 'table') return;
1421
- this.pushHistory();
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
- }
1428
- this.notifyChange();
1429
- }
1430
-
1431
- /* ===================== 页操作 ===================== */
1432
-
1433
- addSlide(layoutKey) {
1434
- const slide = layoutKey ? createSlideWithLayout(layoutKey, this.size) : createSlide();
1435
- this.pushHistory();
1436
- this.snapshot.slides.splice(this.index + 1, 0, slide);
1437
- this.index += 1;
1438
- this.selectedIds = [];
1439
- this.notifyChange();
1440
- }
1441
-
1442
- dupSlide() {
1443
- this.pushHistory();
1444
- this.snapshot.slides.splice(this.index + 1, 0, copySlide(this.currentSlide()));
1445
- this.index += 1;
1446
- this.selectedIds = [];
1447
- this.notifyChange();
1448
- }
1449
-
1450
- delSlide() {
1451
- if (this.snapshot.slides.length <= 1) return notify.warning('至少要保留一页');
1452
- this.pushHistory();
1453
- this.snapshot.slides.splice(this.index, 1);
1454
- this.index = clamp(this.index, 0, this.snapshot.slides.length - 1);
1455
- this.selectedIds = [];
1456
- this.notifyChange();
1457
- }
1458
-
1459
- moveSlide(delta) {
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;
1466
- this.pushHistory();
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 || '';
1507
- this.notifyChange();
1508
- }
1509
-
1510
- setTheme(key) {
1511
- if (!THEMES[key] || this.snapshot.theme === key) return;
1512
- this.pushHistory();
1513
- this.snapshot.theme = key;
1514
- this.notifyChange();
1515
- }
1516
-
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;
1521
- this.pushHistory();
1522
- scaleSnapshotSize(this.snapshot, { w: preset.w, h: preset.h });
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();
1541
- }
1542
-
1543
- setZoom(z, opts = {}) {
1544
- this.zoom = clamp(Math.round(Number(z) || 100), ZOOM_MIN, ZOOM_MAX);
1545
- this.prefs.zoom = this.zoom;
1546
- savePrefs(this.prefs);
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);
1552
- }
1553
-
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
- }
1561
-
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();
1620
- }
1621
-
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();
1634
- }
1635
-
1636
- /* ===================== 放映 ===================== */
1637
-
1638
- presentFromStart() {
1639
- this.commitEditing({ render: false });
1640
- this.presenter.open(0);
1641
- }
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
-
1653
- /* ===================== 文件 ===================== */
1654
-
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
- });
1697
- }
1698
-
1699
- async openFile() {
1700
- if (!(await this.confirmDiscard('打开演示文稿'))) return;
1701
- try {
1702
- const picked = await openPptx();
1703
- if (!picked) return;
1704
- await this.applyBytes(picked.bytes, picked.name);
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();
1710
- notify.success(`已打开 ${picked.name}`);
1711
- } catch (err) {
1712
- notify.error(`打开失败:${err.message || err}`);
1713
- }
1714
- }
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
-
1734
- async applyBytes(bytes, name) {
1735
- const raw = await parsePptx(bytes);
1736
- const snap = normalizeSnapshot(raw);
1737
- if (!snap) throw new Error('文件内容无法识别');
1738
- this.snapshot = snap;
1739
- this.doc = { name: stripExt(name) || '新建演示', handle: null, savedAt: 0 };
1740
- this.snapshot.title = this.doc.name;
1741
- this.index = 0;
1742
- this.selectedIds = [];
1743
- this.editing = null;
1744
- this.history = [];
1745
- this.future = [];
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();
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;
1763
- }
1764
-
1765
- async save(silent = false) {
1766
- if (!this.snapshot.slides.length) return false;
1767
- if (!this.doc.handle) return this.saveAs(this.doc.name);
1768
- if (this.saving) return false;
1769
- this.saving = true;
1770
- const rev = this.revision;
1771
- this.statusbar.setStatus('正在保存…');
1772
- try {
1773
- this.snapshot.title = this.doc.name;
1774
- const bytes = await buildPptxVerified(this.snapshot);
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);
1781
- if (!silent) notify.success('已保存');
1782
- return true;
1783
- } catch (err) {
1784
- this.statusbar.setStatus('保存失败');
1785
- notify.error(`保存失败:${err.message || err}`);
1786
- return false;
1787
- } finally {
1788
- this.saving = false;
1789
- }
1790
- }
1791
-
1792
- async saveAs(name) {
1793
- if (!this.snapshot.slides.length) return false;
1794
- if (this.saving) return false;
1795
- this.saving = true;
1796
- try {
1797
- const suggested = stripExt(name || this.doc.name || '新建演示') || '新建演示';
1798
- this.snapshot.title = suggested;
1799
- const bytes = await buildPptxVerified(this.snapshot);
1800
- const result = await savePptxAs(bytes, suggested);
1801
- if (!result.saved) return false;
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;
1805
- this.setDirty(false);
1806
- this.titlebar.refresh();
1807
- if (this.backstage.el.isConnected) this.backstage.go(this.backstage.tab);
1808
- notify.success('已另存为');
1809
- return true;
1810
- } catch (err) {
1811
- notify.error(`另存失败:${err.message || err}`);
1812
- return false;
1813
- } finally {
1814
- this.saving = false;
1815
- }
1816
- }
1817
-
1818
- async exportPptx() {
1819
- if (!this.snapshot.slides.length) return;
1820
- try {
1821
- this.snapshot.title = this.doc.name;
1822
- const bytes = await buildPptxVerified(this.snapshot);
1823
- this.lastBytes = bytes;
1824
- downloadBlob(new Blob([bytes], { type: PPTX_MIME }), ensureExt(this.doc.name || '新建演示', '.pptx'));
1825
- notify.success('已导出 .pptx');
1826
- } catch (err) {
1827
- notify.error(`导出失败:${err.message || err}`);
1828
- }
1829
- }
1830
-
1831
- exportPdf() {
1832
- this.commitEditing({ render: false });
1833
- printSlides(this.snapshot.slides, this.snapshot.theme, renderPage, this.size);
1834
- }
1835
-
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;
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
- },
2059
- });
2060
- }
2061
-
2062
- /* ===================== 右键菜单 ===================== */
2063
-
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;
2135
- openContextMenu({
2136
- x,
2137
- y,
2138
- items: [
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() },
2142
- { divided: true },
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
- },
2154
- { divided: true },
2155
- { label: '设置背景格式…', icon: 'background', onClick: () => this.openFormatPane() },
2156
- ],
2157
- });
2158
- }
2159
-
2160
- /* ===================== 全局事件 ===================== */
2161
-
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();
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);
2186
- }
2187
-
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);
2327
- }
2328
-
2329
- /* ===================== 自检 ===================== */
2330
-
2331
- async selfTest() {
2332
- const snap = {
2333
- version: 2,
2334
- title: '自检',
2335
- theme: 'midnight',
2336
- size: { w: 960, h: 540 },
2337
- slides: [
2338
- {
2339
- id: 's1',
2340
- bg: '',
2341
- notes: '备注第一行\n第二行',
2342
- hidden: false,
2343
- transition: { type: 'fade', dir: 'l', speed: 'med' },
2344
- objects: [
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: [] } },
2349
- ],
2350
- },
2351
- { id: 's2', bg: '#123456', notes: '', hidden: true, transition: { type: 'push', dir: 'u', speed: 'slow' }, objects: [] },
2352
- ],
2353
- };
2354
- const bytes = await buildPptxVerified(snap);
2355
- const back = await parsePptx(bytes);
2356
- return {
2357
- bytes: bytes.length,
2358
- size: back.size,
2359
- slides: back.slides.length,
2360
- theme: back.theme,
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,
2366
- };
2367
- }
2368
- }
2369
-
2370
- /* ===================== 工具 ===================== */
2371
-
2372
- function loadPrefs() {
2373
- try { return JSON.parse(localStorage.getItem(LS_KEY) || '{}') || {}; } catch { return {}; }
2374
- }
2375
-
2376
- function savePrefs(prefs) {
2377
- try { localStorage.setItem(LS_KEY, JSON.stringify(prefs)); } catch { /* 忽略存储失败 */ }
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
- }
1
+ // [文件] gbpptx·SlidesApp —— Office 式演示编辑器装配(Ribbon/窗格/画布/放映/文件读写/查找替换)
2
+ //
3
+ // [设计] 本文件只留「装配 + 渲染 + 生命周期 + 自检」;其余职责按段落拆到 ./slides/*:
4
+ // render(选择与渲染)/ history(脏状态与撤销)/ text(文本编辑与格式)/ objects(属性与插入)/
5
+ // clipboard / arrange / table / slides(页操作)/ view(视图与放映)/ file / find / menus / keys。
6
+ // 各模块导出方法组,由文件末尾 Object.assign 装配到 SlidesApp.prototype —— 同一个 this、同一套调用,
7
+ // 外部拿到的 SlidesApp 形状与拆分前完全一致。
8
+ // [坑] 装配必须在实例化之前完成:Object.assign 在模块求值时执行,而实例只能在 import 之后 new。
9
+
10
+ import { clamp, createReadOnlyGuard } from 'guabiutils';
11
+ import { createDraft, sizeOf } from '../../src/kernel/model.js';
12
+ import { buildPptxVerified } from '../../src/kernel/roundtrip.js';
13
+ import { parsePptx } from '../../src/kernel/read.js';
14
+ import { notify } from './ui/notify.js';
15
+ import { TitleBar } from './ui/titlebar.js';
16
+ import { Ribbon } from './ui/ribbon.js';
17
+ import { SlidePane } from './ui/slide-pane.js';
18
+ import { Canvas } from './ui/canvas.js';
19
+ import { FormatPane } from './ui/format-pane.js';
20
+ import { StatusBar } from './ui/statusbar.js';
21
+ import { Present } from './ui/present.js';
22
+ import { icon } from './ui/icons.js';
23
+ import { el, loadPrefs, savePrefs, ZOOM_MIN, ZOOM_MAX } from './slides/shared.js';
24
+ import { renderMethods } from './slides/render.js';
25
+ import { historyMethods } from './slides/history.js';
26
+ import { textMethods } from './slides/text.js';
27
+ import { objectsMethods } from './slides/objects.js';
28
+ import { clipboardMethods } from './slides/clipboard.js';
29
+ import { arrangeMethods } from './slides/arrange.js';
30
+ import { tableMethods } from './slides/table.js';
31
+ import { slidesMethods } from './slides/slides.js';
32
+ import { viewMethods } from './slides/view.js';
33
+ import { fileMethods } from './slides/file.js';
34
+ import { findMethods } from './slides/find.js';
35
+ import { menusMethods } from './slides/menus.js';
36
+ import { keysMethods } from './slides/keys.js';
37
+
38
+ export class SlidesApp {
39
+ /** @param {object} [options] readOnly=只读预览(禁写且锁编辑控件);hideMenuBar=隐藏顶部菜单栏那一行 */
40
+ constructor(mount, options = {}) {
41
+ this.mount = mount;
42
+ this.readOnly = Boolean(options.readOnly);
43
+ this.menuBarVisible = !options.hideMenuBar;
44
+ const prefs = loadPrefs();
45
+ this.prefs = prefs;
46
+ this.snapshot = createDraft();
47
+ this.index = 0;
48
+ this.selectedIds = [];
49
+ this.zoom = clamp(Number(prefs.zoom) || 65, ZOOM_MIN, ZOOM_MAX);
50
+ this.dirty = false;
51
+ this.saving = false;
52
+ this.revision = 0;
53
+ this.history = [];
54
+ this.future = [];
55
+ this.clipboard = null;
56
+ this.editing = null;
57
+ this.tableCursor = null;
58
+ this.notesSession = false;
59
+ this.autosave = !!prefs.autosave;
60
+ this.notesVisible = prefs.notesVisible !== false;
61
+ this.gridVisible = !!prefs.grid;
62
+ this.guidesVisible = prefs.guides === true;
63
+ this.ribbonCollapsed = !!prefs.ribbonCollapsed;
64
+ this.formatPaneOpen = !!prefs.formatPaneOpen;
65
+ this.view = 'normal';
66
+ this.preview = false;
67
+ this.previewRestore = null;
68
+ this.presentOptions = { presenter: !!prefs.presenter, loop: !!prefs.loop };
69
+ this.lastBytes = null;
70
+
71
+ const seq = Number(prefs.docSeq) || 1;
72
+ prefs.docSeq = seq + 1;
73
+ savePrefs(prefs);
74
+ this.doc = { name: `演示文稿${seq}`, handle: null, savedAt: 0 };
75
+
76
+ this.build();
77
+ this.bindGlobal();
78
+ this.presenter = new Present(this);
79
+ this.applyMode();
80
+ }
81
+
82
+ /* ===================== 骨架 ===================== */
83
+
84
+ get size() {
85
+ return sizeOf(this.snapshot);
86
+ }
87
+
88
+ build() {
89
+ const root = el('div', 'pp-app');
90
+ root.innerHTML = `
91
+ <div class="pp-topbar-host"></div>
92
+ <div class="pp-ribbon-host"></div>
93
+ <div class="pp-main">
94
+ <div class="pp-main__left"></div>
95
+ <div class="pp-center">
96
+ <div class="pp-canvas-host"></div>
97
+ <div class="pp-notes" hidden>
98
+ <div class="pp-notes__head">
99
+ <span class="pp-notes__title">备注</span>
100
+ <button type="button" class="pp-iconbtn" data-act="notes-close" title="关闭备注">${icon('close', 14)}</button>
101
+ </div>
102
+ <textarea class="pp-notes__text" placeholder="单击此处添加演讲者备注"></textarea>
103
+ </div>
104
+ </div>
105
+ <div class="pp-main__right"></div>
106
+ </div>
107
+ <div class="pp-statusbar-host"></div>`;
108
+ this.mount.appendChild(root);
109
+ this.root = root;
110
+ this.topbarHost = root.querySelector('.pp-topbar-host');
111
+ this.ribbonHost = root.querySelector('.pp-ribbon-host');
112
+ this.formatPaneHost = root.querySelector('.pp-main__right');
113
+ this.left = root.querySelector('.pp-main__left');
114
+ this.center = root.querySelector('.pp-center');
115
+ this.right = root.querySelector('.pp-main__right');
116
+ this.canvasHost = root.querySelector('.pp-canvas-host');
117
+ this.notesEl = root.querySelector('.pp-notes');
118
+ this.notesText = root.querySelector('.pp-notes__text');
119
+
120
+ this.titlebar = new TitleBar(this);
121
+ this.ribbon = new Ribbon(this);
122
+ this.slidePane = new SlidePane(this);
123
+ this.canvas = new Canvas(this);
124
+ this.formatPane = new FormatPane(this);
125
+ this.statusbar = new StatusBar(this);
126
+
127
+ root.querySelector('.pp-topbar-host').appendChild(this.titlebar.el);
128
+ root.querySelector('.pp-ribbon-host').appendChild(this.ribbon.el);
129
+ this.left.appendChild(this.slidePane.el);
130
+ this.canvasHost.appendChild(this.canvas.el);
131
+ this.right.appendChild(this.formatPane.el);
132
+ root.querySelector('.pp-statusbar-host').appendChild(this.statusbar.el);
133
+
134
+ this.sorterEl = el('div', 'pp-sorter');
135
+ this.sorterEl.hidden = true;
136
+ this.center.appendChild(this.sorterEl);
137
+ this.readingEl = el('div', 'pp-reading');
138
+ this.readingEl.hidden = true;
139
+ this.center.appendChild(this.readingEl);
140
+ this.buildSorterEvents();
141
+
142
+ this.bindNotes(root.querySelector('[data-act="notes-close"]'));
143
+ // 只 inert 功能区与各选项卡本身:预览按钮同在选项卡行,必须保持可点
144
+ this.guard = createReadOnlyGuard(root, {
145
+ editZones: () => [
146
+ this.ribbon.bodyEl,
147
+ ...this.ribbon.tabsEl.querySelectorAll('.pp-rb-tab'),
148
+ this.ribbon.contextHost,
149
+ this.formatPaneHost,
150
+ this.notesEl,
151
+ ],
152
+ });
153
+ }
154
+
155
+ /** 构造参数落 DOM:装配完成后才调用,此时标题栏、Ribbon、格式窗格都已就位 */
156
+ applyMode() {
157
+ this.setMenuBarVisible(this.menuBarVisible);
158
+ if (this.readOnly) this.setReadOnly(true);
159
+ }
160
+
161
+ /** 显示/隐藏顶部菜单栏那一行(含同行文档名与保存按钮) */
162
+ setMenuBarVisible(on) {
163
+ this.menuBarVisible = !!on;
164
+ this.topbarHost.style.display = this.menuBarVisible ? '' : 'none';
165
+ }
166
+
167
+ /** 只读开关:DOM 守卫 + 编辑面板 + 菜单栏/备注可用性同一处切换 */
168
+ setReadOnly(on) {
169
+ this.readOnly = !!on;
170
+ this.guard.setReadOnly(this.readOnly);
171
+ this.notesText.disabled = this.readOnly;
172
+ this.renderAll();
173
+ }
174
+
175
+ bindNotes(closeBtn) {
176
+ this.notesText.addEventListener('focus', () => { this.notesSession = false; });
177
+ this.notesText.addEventListener('input', () => {
178
+ const slide = this.currentSlide();
179
+ if (!slide) return;
180
+ if (!this.notesSession) {
181
+ this.pushHistory();
182
+ this.notesSession = true;
183
+ }
184
+ slide.notes = this.notesText.value;
185
+ this.markDirty();
186
+ this.statusbar.setStatus('正在编辑备注');
187
+ });
188
+ this.notesText.addEventListener('blur', () => {
189
+ if (!this.notesSession) return;
190
+ this.notesSession = false;
191
+ this.statusbar.setStatus('');
192
+ this.ribbon.refresh();
193
+ });
194
+ closeBtn.addEventListener('click', () => this.toggleNotes());
195
+ }
196
+
197
+ buildSorterEvents() {
198
+ this.sorterEl.addEventListener('click', (e) => {
199
+ const card = e.target.closest('[data-index]');
200
+ if (card) this.selectSlide(Number(card.dataset.index));
201
+ });
202
+ this.sorterEl.addEventListener('dblclick', (e) => {
203
+ const card = e.target.closest('[data-index]');
204
+ if (card) {
205
+ this.selectSlide(Number(card.dataset.index));
206
+ this.setView('normal');
207
+ }
208
+ });
209
+ this.sorterEl.addEventListener('contextmenu', (e) => {
210
+ const card = e.target.closest('[data-index]');
211
+ if (!card) return;
212
+ e.preventDefault();
213
+ const i = Number(card.dataset.index);
214
+ this.selectSlide(i);
215
+ this.openSlideMenu(e.clientX, e.clientY, i);
216
+ });
217
+ this.sorterEl.addEventListener('dragstart', (e) => {
218
+ const card = e.target.closest('[data-index]');
219
+ if (!card) return;
220
+ this.dragIndex = Number(card.dataset.index);
221
+ card.classList.add('gbp-is-dragging');
222
+ e.dataTransfer.effectAllowed = 'move';
223
+ e.dataTransfer.setData('text/plain', String(this.dragIndex));
224
+ });
225
+ this.sorterEl.addEventListener('dragend', () => {
226
+ this.dragIndex = null;
227
+ this.sorterEl.querySelectorAll('.gbp-is-dragging, .gbp-is-drop').forEach((n) => n.classList.remove('gbp-is-dragging', 'gbp-is-drop'));
228
+ });
229
+ this.sorterEl.addEventListener('dragover', (e) => {
230
+ const card = e.target.closest('[data-index]');
231
+ if (!card || this.dragIndex === null) return;
232
+ e.preventDefault();
233
+ this.sorterEl.querySelectorAll('.gbp-is-drop').forEach((n) => n.classList.remove('gbp-is-drop'));
234
+ card.classList.add('gbp-is-drop');
235
+ });
236
+ this.sorterEl.addEventListener('drop', (e) => {
237
+ const card = e.target.closest('[data-index]');
238
+ if (!card || this.dragIndex === null) return;
239
+ e.preventDefault();
240
+ const to = Number(card.dataset.index);
241
+ if (to !== this.dragIndex) this.moveSlideTo(this.dragIndex, to);
242
+ this.dragIndex = null;
243
+ });
244
+ }
245
+
246
+ /* ===================== 启动/销毁 ===================== */
247
+
248
+ start() {
249
+ this.renderAll();
250
+ notify.info(this.readOnly ? '已就绪:只读预览' : '已就绪:可直接编辑,或用「文件 → 打开」载入 .pptx');
251
+ }
252
+
253
+ destroy() {
254
+ this.canvas?.unbindWheel?.();
255
+ this.presenter?.close();
256
+ clearTimeout(this.autosaveTimer);
257
+ document.removeEventListener('keydown', this.onKeyBound);
258
+ document.removeEventListener('paste', this.onPasteBound);
259
+ document.removeEventListener('selectionchange', this.onSelectionChangeBound);
260
+ window.removeEventListener('beforeunload', this.onBeforeUnloadBound);
261
+ window.removeEventListener('dragover', this.onDragOverBound);
262
+ window.removeEventListener('drop', this.onDropBound);
263
+ window.removeEventListener('resize', this.onResizeBound);
264
+ this.guard.destroy();
265
+ }
266
+
267
+ /* ===================== 渲染 ===================== */
268
+
269
+ async selfTest() {
270
+ const snap = {
271
+ version: 2,
272
+ title: '自检',
273
+ theme: 'midnight',
274
+ size: { w: 960, h: 540 },
275
+ slides: [
276
+ {
277
+ id: 's1',
278
+ bg: '',
279
+ notes: '备注第一行\n第二行',
280
+ hidden: false,
281
+ transition: { type: 'fade', dir: 'l', speed: 'med' },
282
+ objects: [
283
+ { 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 } },
284
+ { 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' } },
285
+ { 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 } },
286
+ { 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: [] } },
287
+ ],
288
+ },
289
+ { id: 's2', bg: '#123456', notes: '', hidden: true, transition: { type: 'push', dir: 'u', speed: 'slow' }, objects: [] },
290
+ ],
291
+ };
292
+ const bytes = await buildPptxVerified(snap);
293
+ const back = await parsePptx(bytes);
294
+ return {
295
+ bytes: bytes.length,
296
+ size: back.size,
297
+ slides: back.slides.length,
298
+ theme: back.theme,
299
+ hidden: back.slides.map((s) => s.hidden),
300
+ transition: back.slides.map((s) => s.transition.type),
301
+ objects: back.slides[0].objects.map((o) => o.type),
302
+ list: back.slides[0].objects[0]?.props?.html?.includes('<ul>'),
303
+ tableStyle: back.slides[0].objects[3]?.props?.tableStyle,
304
+ };
305
+ }
306
+ }
307
+
308
+ Object.assign(
309
+ SlidesApp.prototype,
310
+ renderMethods,
311
+ historyMethods,
312
+ textMethods,
313
+ objectsMethods,
314
+ clipboardMethods,
315
+ arrangeMethods,
316
+ tableMethods,
317
+ slidesMethods,
318
+ viewMethods,
319
+ fileMethods,
320
+ findMethods,
321
+ menusMethods,
322
+ keysMethods
323
+ );