gbpptx 0.2.0 → 0.3.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 +220 -214
  2. package/package.json +4 -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 +243 -0
  10. package/web/app/slides/find.js +199 -0
  11. package/web/app/slides/history.js +100 -0
  12. package/web/app/slides/keys.js +174 -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 +130 -0
  21. package/web/app/slides-app.js +285 -2446
  22. package/web/app/ui/backstage.js +255 -255
  23. package/web/app/ui/canvas.js +762 -755
  24. package/web/app/ui/color-panel.js +58 -76
  25. package/web/app/ui/dialogs.js +120 -159
  26. package/web/app/ui/file-io.js +116 -132
  27. package/web/app/ui/format-pane.js +427 -427
  28. package/web/app/ui/icons.js +129 -129
  29. package/web/app/ui/menu.js +75 -89
  30. package/web/app/ui/notify.js +45 -45
  31. package/web/app/ui/page-view.js +221 -221
  32. package/web/app/ui/popup.js +80 -80
  33. package/web/app/ui/present.js +292 -292
  34. package/web/app/ui/ribbon.js +878 -878
  35. package/web/app/ui/slide-pane.js +189 -189
  36. package/web/app/ui/statusbar.js +93 -93
  37. package/web/app/ui/text-styles.js +84 -84
  38. package/web/app/ui/titlebar.js +173 -66
  39. package/web/app/ui/transition.js +30 -30
  40. package/web/index.html +23 -22
  41. package/web/serve.mjs +20 -67
  42. package/web/styles/office.css +642 -644
  43. package/web/styles/slides.css +210 -219
  44. package/web/styles/tokens.css +154 -155
  45. package/src/kernel/util/escape.js +0 -21
  46. package/src/kernel/util/id.js +0 -13
@@ -0,0 +1,101 @@
1
+ // [文件] gbpptx·slides·arrange —— 排列 —— 删除/再制/微移/层级/对齐/分布
2
+
3
+ // [设计] 方法以独立函数导出,由 slides-app.js 末尾 Object.assign 装配到 SlidesApp.prototype:
4
+ // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
+
6
+ import { cloneObject, objectRect, topZ } from '../../../src/kernel/model.js';
7
+ function removeSelected() {
8
+ const objs = this.selectedObjects();
9
+ if (!objs.length) return;
10
+ this.pushHistory();
11
+ const ids = new Set(objs.map((o) => o.id));
12
+ this.currentSlide().objects = this.currentSlide().objects.filter((o) => !ids.has(o.id));
13
+ this.selectedIds = [];
14
+ this.notifyChange();
15
+ }
16
+
17
+ function duplicateSelected() {
18
+ const objs = this.selectedObjects();
19
+ if (!objs.length) return;
20
+ this.pushHistory();
21
+ const slide = this.currentSlide();
22
+ const copies = objs.map((o, i) => {
23
+ const copy = cloneObject(o);
24
+ copy.x += 16;
25
+ copy.y += 16;
26
+ copy.z = topZ(slide.objects) + 1 + i;
27
+ return copy;
28
+ });
29
+ slide.objects.push(...copies);
30
+ this.selectedIds = copies.map((o) => o.id);
31
+ this.notifyChange();
32
+ }
33
+
34
+ function nudge(dx, dy) {
35
+ const objs = this.selectedObjects();
36
+ if (!objs.length) return;
37
+ this.pushHistory();
38
+ for (const o of objs) {
39
+ o.x += dx;
40
+ o.y += dy;
41
+ }
42
+ this.notifyChange({ canvasOnly: true });
43
+ }
44
+
45
+ function arrange(key) {
46
+ const slide = this.currentSlide();
47
+ const sel = this.selectedObjects();
48
+ if (!sel.length) return;
49
+ this.pushHistory();
50
+ const sorted = [...slide.objects].sort((a, b) => (a.z || 0) - (b.z || 0));
51
+ for (const o of sel) {
52
+ const i = sorted.indexOf(o);
53
+ if (key === 'front') { sorted.splice(i, 1); sorted.push(o); }
54
+ else if (key === 'back') { sorted.splice(i, 1); sorted.unshift(o); }
55
+ else if (key === 'forward' && i < sorted.length - 1) { sorted.splice(i, 1); sorted.splice(i + 1, 0, o); }
56
+ else if (key === 'backward' && i > 0) { sorted.splice(i, 1); sorted.splice(i - 1, 0, o); }
57
+ }
58
+ sorted.forEach((o, i) => { o.z = i + 1; });
59
+ this.notifyChange();
60
+ }
61
+
62
+ function alignToSlide(key) {
63
+ const sel = this.selectedObjects();
64
+ if (!sel.length) return;
65
+ const size = this.size;
66
+ this.pushHistory();
67
+ for (const o of sel) {
68
+ const r = objectRect(o);
69
+ if (key === 'left') o.x = 0;
70
+ else if (key === 'centerH') o.x = Math.round((size.w - r.width) / 2);
71
+ else if (key === 'right') o.x = size.w - r.width;
72
+ else if (key === 'top') o.y = 0;
73
+ else if (key === 'middle') o.y = Math.round((size.h - r.height) / 2);
74
+ else if (key === 'bottom') o.y = size.h - r.height;
75
+ }
76
+ this.notifyChange();
77
+ }
78
+
79
+ function distribute(axis) {
80
+ const sel = this.selectedObjects();
81
+ if (sel.length < 3) return;
82
+ this.pushHistory();
83
+ const items = sel.map((o) => ({ o, r: objectRect(o) }));
84
+ items.sort((a, b) => (axis === 'h' ? a.r.left - b.r.left : a.r.top - b.r.top));
85
+ const first = items[0];
86
+ const last = items[items.length - 1];
87
+ if (axis === 'h') {
88
+ const start = first.r.left + first.r.width / 2;
89
+ const end = last.r.left + last.r.width / 2;
90
+ const step = (end - start) / (items.length - 1);
91
+ items.forEach((item, i) => { item.o.x = Math.round(start + step * i - item.r.width / 2); });
92
+ } else {
93
+ const start = first.r.top + first.r.height / 2;
94
+ const end = last.r.top + last.r.height / 2;
95
+ const step = (end - start) / (items.length - 1);
96
+ items.forEach((item, i) => { item.o.y = Math.round(start + step * i - item.r.height / 2); });
97
+ }
98
+ this.notifyChange();
99
+ }
100
+
101
+ export const arrangeMethods = { removeSelected, duplicateSelected, nudge, arrange, alignToSlide, distribute };
@@ -0,0 +1,93 @@
1
+ // [文件] gbpptx·slides·clipboard —— 剪贴板 —— 复制/剪切/粘贴(含纯文本与富文本两条路径)
2
+
3
+ // [设计] 方法以独立函数导出,由 slides-app.js 末尾 Object.assign 装配到 SlidesApp.prototype:
4
+ // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
+
6
+ import { escapeHtml } from 'guabiutils';
7
+ import { cloneObject, createTextObject, topZ } from '../../../src/kernel/model.js';
8
+ import { notify } from '../ui/notify.js';
9
+ function canPaste() {
10
+ return Boolean(this.editing) || Boolean(this.clipboard?.length);
11
+ }
12
+
13
+ function copySelected() {
14
+ if (this.editing) {
15
+ document.execCommand('copy');
16
+ notify.info('已复制所选文字');
17
+ return;
18
+ }
19
+ const objs = this.selectedObjects();
20
+ if (!objs.length) return;
21
+ this.clipboard = objs.map((o) => JSON.parse(JSON.stringify(o)));
22
+ this.ribbon.refresh();
23
+ notify.info(`已复制 ${objs.length} 个对象`);
24
+ }
25
+
26
+ function cutSelected() {
27
+ if (this.editing) {
28
+ document.execCommand('cut');
29
+ this.syncEditing();
30
+ return;
31
+ }
32
+ if (!this.selectedObjects().length) return;
33
+ this.copySelected();
34
+ this.removeSelected();
35
+ }
36
+
37
+ function paste() {
38
+ if (this.editing) {
39
+ this.pastePlain();
40
+ return;
41
+ }
42
+ if (!this.clipboard?.length) return;
43
+ const slide = this.currentSlide();
44
+ if (!slide) return;
45
+ this.pushHistory();
46
+ const pasted = this.clipboard.map((o, i) => {
47
+ const copy = cloneObject(o);
48
+ copy.x += 18;
49
+ copy.y += 18;
50
+ copy.z = topZ(slide.objects) + 1 + i;
51
+ return copy;
52
+ });
53
+ slide.objects.push(...pasted);
54
+ this.selectedIds = pasted.map((o) => o.id);
55
+ this.notifyChange();
56
+ }
57
+
58
+ function pasteText(text) {
59
+ const value = String(text || '');
60
+ if (!value.trim()) return;
61
+ const html = value.split(/\r?\n/).map((line) => `<div>${escapeHtml(line) || '<br>'}</div>`).join('');
62
+ const size = this.size;
63
+ const obj = createTextObject(Math.round(size.w * 0.1), Math.round(size.h * 0.1), topZ(this.currentSlide().objects) + 1);
64
+ obj.w = Math.min(640, Math.max(260, Math.round(size.w * 0.55)));
65
+ obj.h = Math.min(280, Math.max(80, value.split(/\n/).length * 34));
66
+ obj.props.html = html;
67
+ obj.props.fontSize = 20;
68
+ this.pushHistory();
69
+ this.currentSlide().objects.push(obj);
70
+ this.selectedIds = [obj.id];
71
+ this.notifyChange();
72
+ }
73
+
74
+ async function pastePlain() {
75
+ if (this.editing) {
76
+ try {
77
+ const text = await navigator.clipboard.readText();
78
+ document.execCommand('insertText', false, text);
79
+ this.syncEditing();
80
+ } catch {
81
+ notify.warning('浏览器未授予剪贴板读取权限');
82
+ }
83
+ return;
84
+ }
85
+ try {
86
+ const text = await navigator.clipboard.readText();
87
+ this.pasteText(text);
88
+ } catch {
89
+ notify.warning('浏览器未授予剪贴板读取权限,请直接用 Ctrl+V');
90
+ }
91
+ }
92
+
93
+ export const clipboardMethods = { canPaste, copySelected, cutSelected, paste, pasteText, pastePlain };
@@ -0,0 +1,243 @@
1
+ // [文件] gbpptx·slides·file —— 文件动作 —— 新建/打开/导入/保存/导出/重命名/关闭/后台视图
2
+
3
+ // [设计] 方法以独立函数导出,由 slides-app.js 末尾 Object.assign 装配到 SlidesApp.prototype:
4
+ // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
+
6
+ import { downloadBlob, stripExt } from 'guabiutils';
7
+ import { createDraft, createSlideWithLayout, normalizeSnapshot } from '../../../src/kernel/model.js';
8
+ import { buildPptxVerified } from '../../../src/kernel/roundtrip.js';
9
+ import { parsePptx } from '../../../src/kernel/read.js';
10
+ import { printSlides } from '../../../src/kernel/print.js';
11
+ import { notify } from '../ui/notify.js';
12
+ import { renderPage } from '../ui/page-view.js';
13
+ import { PPTX_MIME, ensureExt, isPptxFile, openPptx, readBytes, savePptx, savePptxAs } from '../ui/file-io.js';
14
+ import { openModal } from '../ui/dialogs.js';
15
+ import { savePrefs } from './shared.js';
16
+ function resetDoc(draft, name, handle = null) {
17
+ this.snapshot = draft;
18
+ this.doc = { name, handle, savedAt: 0 };
19
+ this.snapshot.title = name;
20
+ this.index = 0;
21
+ this.selectedIds = [];
22
+ this.editing = null;
23
+ this.history = [];
24
+ this.future = [];
25
+ this.revision = 0;
26
+ this.dirty = false;
27
+ this.lastBytes = null;
28
+ this.tableCursor = null;
29
+ this.notesSession = false;
30
+ this.view = 'normal';
31
+ this.closeFind();
32
+ this.renderAll();
33
+ this.titlebar.refresh();
34
+ }
35
+
36
+ async function confirmDiscard(action) {
37
+ if (!this.dirty) return true;
38
+ return new Promise((resolve) => {
39
+ let confirmed = false;
40
+ openModal({
41
+ title: action || '放弃更改?',
42
+ width: 420,
43
+ confirmText: '继续',
44
+ build: (body) => {
45
+ const message = document.createElement('p');
46
+ message.className = 'gbp-modal__message';
47
+ message.textContent = '当前演示有未保存的更改,继续将丢弃这些更改。';
48
+ body.appendChild(message);
49
+ },
50
+ onConfirm: () => {
51
+ confirmed = true;
52
+ },
53
+ onClose: () => resolve(confirmed),
54
+ });
55
+ });
56
+ }
57
+
58
+ function newDoc(layoutKey = '') {
59
+ this.confirmDiscard('新建演示文稿').then((ok) => {
60
+ if (!ok) return;
61
+ const draft = createDraft();
62
+ if (layoutKey) draft.slides = [createSlideWithLayout(layoutKey, draft.size)];
63
+ const seq = Number(this.prefs.docSeq) || 1;
64
+ this.prefs.docSeq = seq + 1;
65
+ savePrefs(this.prefs);
66
+ this.resetDoc(draft, `演示文稿${seq}`);
67
+ this.backstage.close();
68
+ notify.success('已新建空白演示');
69
+ });
70
+ }
71
+
72
+ async function openFile() {
73
+ if (!(await this.confirmDiscard('打开演示文稿'))) return;
74
+ try {
75
+ const picked = await openPptx();
76
+ if (!picked) return;
77
+ await this.applyBytes(picked.bytes, picked.name);
78
+ this.doc.handle = picked.handle;
79
+ this.doc.name = stripExt(picked.name) || '新建演示';
80
+ this.snapshot.title = this.doc.name;
81
+ this.titlebar.refresh();
82
+ this.backstage.close();
83
+ notify.success(`已打开 ${picked.name}`);
84
+ } catch (err) {
85
+ notify.error(`打开失败:${err.message || err}`);
86
+ }
87
+ }
88
+
89
+ async function importFile(file) {
90
+ if (!file) return;
91
+ if (!isPptxFile(file)) {
92
+ if (/^image\/(png|jpeg|gif)$/i.test(file.type || '')) return this.insertImageFile(file);
93
+ notify.error('请选择 .pptx 演示文稿或 PNG/JPEG/GIF 图片');
94
+ return;
95
+ }
96
+ if (!(await this.confirmDiscard('打开演示文稿'))) return;
97
+ try {
98
+ const bytes = await readBytes(file);
99
+ await this.applyBytes(bytes, file.name);
100
+ this.backstage.close();
101
+ notify.success(`已打开 ${file.name}`);
102
+ } catch (err) {
103
+ notify.error(`打开失败:${err.message || err}`);
104
+ }
105
+ }
106
+
107
+ async function applyBytes(bytes, name) {
108
+ const raw = await parsePptx(bytes);
109
+ const snap = normalizeSnapshot(raw);
110
+ if (!snap) throw new Error('文件内容无法识别');
111
+ this.snapshot = snap;
112
+ this.doc = { name: stripExt(name) || '新建演示', handle: null, savedAt: 0 };
113
+ this.snapshot.title = this.doc.name;
114
+ this.index = 0;
115
+ this.selectedIds = [];
116
+ this.editing = null;
117
+ this.history = [];
118
+ this.future = [];
119
+ this.revision = 0;
120
+ this.dirty = false;
121
+ this.lastBytes = bytes;
122
+ this.tableCursor = null;
123
+ this.notesSession = false;
124
+ this.view = 'normal';
125
+ this.closeFind();
126
+ this.renderAll();
127
+ this.fitToWindow();
128
+ const w = raw.warnings || {};
129
+ const parts = [];
130
+ if (w.groups) parts.push(`${w.groups} 个组合已摊平`);
131
+ if (w.charts) parts.push(`${w.charts} 个图表已跳过`);
132
+ if (w.media) parts.push(`${w.media} 个音视频已跳过`);
133
+ if (w.unknown) parts.push(`${w.unknown} 个未知元素已跳过`);
134
+ if (parts.length) notify.warning(`已导入;${parts.join('、')}`);
135
+ return snap;
136
+ }
137
+
138
+ async function save(silent = false) {
139
+ if (!this.snapshot.slides.length) return false;
140
+ if (!this.doc.handle) return this.saveAs(this.doc.name);
141
+ if (this.saving) return false;
142
+ this.saving = true;
143
+ const rev = this.revision;
144
+ this.statusbar.setStatus('正在保存…');
145
+ try {
146
+ this.snapshot.title = this.doc.name;
147
+ const bytes = await buildPptxVerified(this.snapshot);
148
+ await savePptx(bytes, ensureExt(this.doc.name, '.pptx'), this.doc.handle);
149
+ this.lastBytes = bytes;
150
+ this.doc.savedAt = Date.now();
151
+ if (this.revision === rev) this.setDirty(false);
152
+ this.statusbar.setStatus('已保存');
153
+ setTimeout(() => this.statusbar.setStatus(''), 1600);
154
+ if (!silent) notify.success('已保存');
155
+ return true;
156
+ } catch (err) {
157
+ this.statusbar.setStatus('保存失败');
158
+ notify.error(`保存失败:${err.message || err}`);
159
+ return false;
160
+ } finally {
161
+ this.saving = false;
162
+ }
163
+ }
164
+
165
+ async function saveAs(name) {
166
+ if (!this.snapshot.slides.length) return false;
167
+ if (this.saving) return false;
168
+ this.saving = true;
169
+ try {
170
+ const suggested = stripExt(name || this.doc.name || '新建演示') || '新建演示';
171
+ this.snapshot.title = suggested;
172
+ const bytes = await buildPptxVerified(this.snapshot);
173
+ const result = await savePptxAs(bytes, suggested);
174
+ if (!result.saved) return false;
175
+ this.doc = { name: stripExt(result.name || suggested), handle: result.handle, savedAt: Date.now() };
176
+ this.snapshot.title = this.doc.name;
177
+ this.lastBytes = bytes;
178
+ this.setDirty(false);
179
+ this.titlebar.refresh();
180
+ if (this.backstage.el.isConnected) this.backstage.go(this.backstage.tab);
181
+ notify.success('已另存为');
182
+ return true;
183
+ } catch (err) {
184
+ notify.error(`另存失败:${err.message || err}`);
185
+ return false;
186
+ } finally {
187
+ this.saving = false;
188
+ }
189
+ }
190
+
191
+ async function exportPptx() {
192
+ if (!this.snapshot.slides.length) return;
193
+ try {
194
+ this.snapshot.title = this.doc.name;
195
+ const bytes = await buildPptxVerified(this.snapshot);
196
+ this.lastBytes = bytes;
197
+ downloadBlob(new Blob([bytes], { type: PPTX_MIME }), ensureExt(this.doc.name || '新建演示', '.pptx'));
198
+ notify.success('已导出 .pptx');
199
+ } catch (err) {
200
+ notify.error(`导出失败:${err.message || err}`);
201
+ }
202
+ }
203
+
204
+ function exportPdf() {
205
+ this.commitEditing({ render: false });
206
+ printSlides(this.snapshot.slides, this.snapshot.theme, renderPage, this.size);
207
+ }
208
+
209
+ function renameDoc(name) {
210
+ const value = String(name || '').trim() || '新建演示';
211
+ this.doc.name = value;
212
+ this.snapshot.title = value;
213
+ this.touch();
214
+ this.titlebar.refresh();
215
+ }
216
+
217
+ async function closeDocument() {
218
+ if (!(await this.confirmDiscard('关闭演示文稿'))) return;
219
+ const seq = Number(this.prefs.docSeq) || 1;
220
+ this.prefs.docSeq = seq + 1;
221
+ savePrefs(this.prefs);
222
+ this.resetDoc(createDraft(), `演示文稿${seq}`);
223
+ this.backstage.close();
224
+ notify.success('演示文稿已关闭');
225
+ }
226
+
227
+ function openBackstage(tab = 'home') {
228
+ this.commitEditing({ render: false });
229
+ this.backstage.open(tab);
230
+ this.ribbon.setFileActive(true);
231
+ }
232
+
233
+ function closeBackstage() {
234
+ if (!this.backstage || this.backstage.el.hidden) return;
235
+ this.backstage.close();
236
+ }
237
+
238
+ function onBackstageClosed() {
239
+ this.ribbon.setFileActive(false);
240
+ this.ribbon.activate(this.ribbon.activeTab || 'home', { expand: false });
241
+ }
242
+
243
+ export const fileMethods = { resetDoc, confirmDiscard, newDoc, openFile, importFile, applyBytes, save, saveAs, exportPptx, exportPdf, renameDoc, closeDocument, openBackstage, closeBackstage, onBackstageClosed };
@@ -0,0 +1,199 @@
1
+ // [文件] gbpptx·slides·find —— 查找替换与字数统计
2
+
3
+ // [设计] 方法以独立函数导出,由 slides-app.js 末尾 Object.assign 装配到 SlidesApp.prototype:
4
+ // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
+
6
+ import { htmlToPlain } from '../../../src/kernel/model.js';
7
+ import { notify } from '../ui/notify.js';
8
+ import { field, openModal } from '../ui/dialogs.js';
9
+ import { icon } from '../ui/icons.js';
10
+ import { el, replaceInHtml, replaceInPlain } from './shared.js';
11
+ function openFind(replace = false) {
12
+ if (this.view !== 'normal') this.setView('normal');
13
+ this.commitEditing({ render: false });
14
+ if (!this.findEl) this.buildFindBar();
15
+ this.findEl.hidden = false;
16
+ this.findEl.classList.toggle('gbp-is-replace', replace);
17
+ this.findReplaceRow.hidden = !replace;
18
+ this.findState.replace = replace;
19
+ this.refreshMatches();
20
+ this.findInput.focus();
21
+ this.findInput.select();
22
+ }
23
+
24
+ function closeFind() {
25
+ if (!this.findEl) return;
26
+ this.findEl.hidden = true;
27
+ }
28
+
29
+ function buildFindBar() {
30
+ const bar = el('div', 'pp-findbar');
31
+ const top = el('div', 'pp-findbar__row');
32
+ this.findInput = el('input', 'pp-input pp-findbar__input');
33
+ this.findInput.type = 'text';
34
+ this.findInput.placeholder = '查找';
35
+ this.findCount = el('span', 'pp-findbar__count', '0/0');
36
+ const prev = el('button', 'pp-iconbtn', '');
37
+ prev.type = 'button';
38
+ prev.title = '上一个';
39
+ prev.innerHTML = icon('chevronUp', 15);
40
+ const next = el('button', 'pp-iconbtn', '');
41
+ next.type = 'button';
42
+ next.title = '下一个';
43
+ next.innerHTML = icon('chevronDown', 15);
44
+ const close = el('button', 'pp-iconbtn', '');
45
+ close.type = 'button';
46
+ close.title = '关闭';
47
+ close.innerHTML = icon('close', 15);
48
+ top.append(this.findInput, this.findCount, prev, next, close);
49
+
50
+ this.findReplaceRow = el('div', 'pp-findbar__row');
51
+ this.replaceInput = el('input', 'pp-input pp-findbar__input');
52
+ this.replaceInput.type = 'text';
53
+ this.replaceInput.placeholder = '替换为';
54
+ const replaceBtn = el('button', 'pp-chip', '替换');
55
+ replaceBtn.type = 'button';
56
+ const allBtn = el('button', 'pp-chip', '全部替换');
57
+ allBtn.type = 'button';
58
+ this.findReplaceRow.append(this.replaceInput, replaceBtn, allBtn);
59
+ bar.append(top, this.findReplaceRow);
60
+ this.center.appendChild(bar);
61
+ this.findEl = bar;
62
+ this.findState = { replace: false, matches: [], cursor: -1 };
63
+
64
+ prev.addEventListener('click', () => this.findNext(true));
65
+ next.addEventListener('click', () => this.findNext(false));
66
+ close.addEventListener('click', () => this.closeFind());
67
+ replaceBtn.addEventListener('click', () => this.replaceCurrent());
68
+ allBtn.addEventListener('click', () => this.replaceAll());
69
+ this.findInput.addEventListener('input', () => { this.refreshMatches(); this.findNext(false); });
70
+ this.findInput.addEventListener('keydown', (e) => {
71
+ if (e.key === 'Enter') { e.preventDefault(); this.findNext(e.shiftKey); }
72
+ if (e.key === 'Escape') { e.preventDefault(); this.closeFind(); }
73
+ });
74
+ this.replaceInput.addEventListener('keydown', (e) => {
75
+ if (e.key === 'Enter') { e.preventDefault(); this.replaceCurrent(); }
76
+ if (e.key === 'Escape') { e.preventDefault(); this.closeFind(); }
77
+ });
78
+ }
79
+
80
+ function objectTextFields(slide) {
81
+ const fields = [];
82
+ for (const o of slide.objects) {
83
+ if (o.type === 'text') fields.push({ obj: o, field: 'html', text: htmlToPlain(o.props.html) });
84
+ else if (o.type === 'shape') fields.push({ obj: o, field: 'text', text: o.props.text || '' });
85
+ else if (o.type === 'table') fields.push({ obj: o, field: 'table', text: (o.props.rows || []).flat().join('\n') });
86
+ }
87
+ return fields;
88
+ }
89
+
90
+ function refreshMatches() {
91
+ if (!this.findEl) return;
92
+ const q = this.findInput.value;
93
+ const matches = [];
94
+ if (q) {
95
+ this.snapshot.slides.forEach((slide, si) => {
96
+ for (const f of this.objectTextFields(slide)) {
97
+ if (f.text.toLowerCase().includes(q.toLowerCase())) matches.push({ si, objId: f.obj.id, field: f.field });
98
+ }
99
+ });
100
+ }
101
+ this.findState.matches = matches;
102
+ this.findState.cursor = matches.length ? Math.min(this.findState.cursor, matches.length - 1) : -1;
103
+ this.findCount.textContent = matches.length ? `${this.findState.cursor + 1}/${matches.length}` : '0/0';
104
+ }
105
+
106
+ function findNext(back = false) {
107
+ const state = this.findState;
108
+ if (!state?.matches?.length) return;
109
+ state.cursor = back
110
+ ? (state.cursor - 1 + state.matches.length) % state.matches.length
111
+ : (state.cursor + 1) % state.matches.length;
112
+ const match = state.matches[state.cursor];
113
+ this.findCount.textContent = `${state.cursor + 1}/${state.matches.length}`;
114
+ if (match.si !== this.index) this.selectSlide(match.si);
115
+ this.selectObjects([match.objId]);
116
+ this.canvas.flashObject(match.objId);
117
+ this.statusbar.setStatus(`找到于第 ${match.si + 1} 页`);
118
+ }
119
+
120
+ function replaceCurrent() {
121
+ const state = this.findState;
122
+ const match = state?.matches?.[state.cursor];
123
+ const q = this.findInput.value;
124
+ if (!match || !q) return;
125
+ const slide = this.snapshot.slides[match.si];
126
+ const obj = slide.objects.find((o) => o.id === match.objId);
127
+ if (!obj) return;
128
+ this.pushHistory();
129
+ const replacement = this.replaceInput.value;
130
+ if (match.field === 'html') obj.props.html = replaceInHtml(obj.props.html, q, replacement);
131
+ else if (match.field === 'text') obj.props.text = replaceInPlain(obj.props.text, q, replacement);
132
+ else obj.props.rows = obj.props.rows.map((row) => row.map((cell) => replaceInPlain(cell, q, replacement)));
133
+ this.notifyChange();
134
+ this.refreshMatches();
135
+ this.findNext(false);
136
+ }
137
+
138
+ function replaceAll() {
139
+ const q = this.findInput.value;
140
+ if (!q) return;
141
+ const replacement = this.replaceInput.value;
142
+ this.pushHistory();
143
+ for (const slide of this.snapshot.slides) {
144
+ for (const o of slide.objects) {
145
+ if (o.type === 'text') o.props.html = replaceInHtml(o.props.html, q, replacement, true);
146
+ else if (o.type === 'shape') o.props.text = replaceInPlain(o.props.text, q, replacement, true);
147
+ else if (o.type === 'table') o.props.rows = o.props.rows.map((row) => row.map((cell) => replaceInPlain(cell, q, replacement, true)));
148
+ }
149
+ }
150
+ this.notifyChange();
151
+ this.refreshMatches();
152
+ notify.success('已完成全部替换');
153
+ }
154
+
155
+ function showWordCount() {
156
+ let chars = 0;
157
+ let words = 0;
158
+ let textBoxes = 0;
159
+ let shapes = 0;
160
+ let images = 0;
161
+ let tables = 0;
162
+ const allText = [];
163
+ for (const slide of this.snapshot.slides) {
164
+ for (const o of slide.objects) {
165
+ if (o.type === 'text') { textBoxes += 1; allText.push(htmlToPlain(o.props.html)); }
166
+ else if (o.type === 'shape') { shapes += 1; allText.push(o.props.text || ''); }
167
+ else if (o.type === 'image') images += 1;
168
+ else if (o.type === 'table') { tables += 1; allText.push(...o.props.rows.flat()); }
169
+ else if (o.type === 'line') shapes += 1;
170
+ }
171
+ }
172
+ const text = allText.join('\n');
173
+ chars = text.replace(/\s/g, '').length;
174
+ words = (text.match(/[\u4e00-\u9fa5]|[A-Za-z0-9]+/g) || []).length;
175
+ openModal({
176
+ title: '字数统计',
177
+ width: 420,
178
+ confirmText: '关闭',
179
+ build: (body) => {
180
+ const grid = el('div', 'pp-info-grid');
181
+ for (const [k, v] of [
182
+ ['幻灯片', `${this.snapshot.slides.length} 页`],
183
+ ['文字框', textBoxes],
184
+ ['图形/线条', shapes],
185
+ ['图片', images],
186
+ ['表格', tables],
187
+ ['字数', words],
188
+ ['字符数(不计空格)', chars],
189
+ ]) {
190
+ const item = el('div', 'pp-info-grid__item');
191
+ item.append(el('span', '', k), el('strong', '', String(v)));
192
+ grid.appendChild(item);
193
+ }
194
+ body.appendChild(grid);
195
+ },
196
+ });
197
+ }
198
+
199
+ export const findMethods = { openFind, closeFind, buildFindBar, objectTextFields, refreshMatches, findNext, replaceCurrent, replaceAll, showWordCount };