gbpptx 0.6.1 → 0.6.2

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 (50) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +253 -253
  3. package/package.json +48 -47
  4. package/src/index.js +29 -29
  5. package/src/kernel/model.js +651 -651
  6. package/src/kernel/parts.js +173 -173
  7. package/src/kernel/pptx.js +72 -72
  8. package/src/kernel/print.js +76 -76
  9. package/src/kernel/read.js +1018 -1018
  10. package/src/kernel/roundtrip.js +174 -174
  11. package/src/kernel/text.js +278 -278
  12. package/src/kernel/write.js +385 -385
  13. package/web/app/main.js +8 -8
  14. package/web/app/slides/arrange.js +101 -101
  15. package/web/app/slides/clipboard.js +93 -93
  16. package/web/app/slides/file.js +240 -240
  17. package/web/app/slides/find.js +201 -201
  18. package/web/app/slides/history.js +100 -100
  19. package/web/app/slides/keys.js +187 -187
  20. package/web/app/slides/menus.js +105 -105
  21. package/web/app/slides/objects.js +254 -254
  22. package/web/app/slides/render.js +183 -183
  23. package/web/app/slides/shared.js +85 -85
  24. package/web/app/slides/slides.js +103 -103
  25. package/web/app/slides/table.js +102 -102
  26. package/web/app/slides/text.js +418 -418
  27. package/web/app/slides/view.js +182 -182
  28. package/web/app/slides-app.js +354 -354
  29. package/web/app/ui/canvas.js +769 -769
  30. package/web/app/ui/color-panel.js +58 -58
  31. package/web/app/ui/dialogs.js +120 -120
  32. package/web/app/ui/file-io.js +116 -116
  33. package/web/app/ui/format-pane.js +427 -427
  34. package/web/app/ui/icons.js +241 -133
  35. package/web/app/ui/menu.js +77 -75
  36. package/web/app/ui/notify.js +45 -45
  37. package/web/app/ui/page-view.js +221 -221
  38. package/web/app/ui/popup.js +80 -80
  39. package/web/app/ui/present.js +292 -292
  40. package/web/app/ui/ribbon.js +855 -855
  41. package/web/app/ui/slide-pane.js +197 -197
  42. package/web/app/ui/statusbar.js +93 -93
  43. package/web/app/ui/text-styles.js +84 -84
  44. package/web/app/ui/titlebar.js +253 -253
  45. package/web/app/ui/transition.js +30 -30
  46. package/web/index.html +30 -29
  47. package/web/serve.mjs +26 -23
  48. package/web/styles/office.css +463 -463
  49. package/web/styles/slides.css +97 -97
  50. package/web/styles/tokens.css +154 -154
@@ -1,769 +1,769 @@
1
- // [文件] gbpptx·画布 —— Office 式编辑面(多选/框选/吸附/组缩放/旋转/就地文本与表格编辑/缩放)
2
-
3
- import { SLIDE_H, SLIDE_W, objectBoxStyle, objectRect, unionRect } from '../../../src/kernel/model.js';
4
- import { bindCtrlWheelZoom } from 'guabiutils';
5
- import { renderPage } from './page-view.js';
6
- import { animateSlideFrame } from './transition.js';
7
-
8
- const MIN_SIZE = 8;
9
- const SNAP_PX = 6;
10
- const ROTATE_HANDLE_GAP = 28;
11
-
12
- const cssEscape = (s) => (window.CSS?.escape ? CSS.escape(String(s)) : String(s).replace(/["\\]/g, '\\$&'));
13
-
14
- export class Canvas {
15
- constructor(app) {
16
- this.app = app;
17
- this.el = document.createElement('div');
18
- this.el.className = 'pp-canvas';
19
- this.scroll = document.createElement('div');
20
- this.scroll.className = 'pp-canvas__scroll';
21
- this.holder = document.createElement('div');
22
- this.holder.className = 'pp-canvas__holder';
23
- this.inner = document.createElement('div');
24
- this.inner.className = 'pp-canvas__inner';
25
- this.holder.appendChild(this.inner);
26
- this.scroll.appendChild(this.holder);
27
- this.el.appendChild(this.scroll);
28
-
29
- this.sel = document.createElement('div');
30
- this.sel.className = 'pp-sel';
31
- this.sel.hidden = true;
32
- this.buildHandles();
33
-
34
- this.guides = document.createElement('div');
35
- this.guides.className = 'pp-guides';
36
- this.marquee = document.createElement('div');
37
- this.marquee.className = 'pp-marquee';
38
- this.marquee.hidden = true;
39
-
40
- this.bind();
41
- }
42
-
43
- get scale() {
44
- return this.app.zoom / 100;
45
- }
46
-
47
- get size() {
48
- return this.app.size;
49
- }
50
-
51
- /* ===================== 渲染 ===================== */
52
-
53
- render() {
54
- const app = this.app;
55
- const slide = app.currentSlide();
56
- const page = renderPage(slide, app.snapshot.theme, { interactive: true, size: this.size });
57
- this.page = page;
58
- this.inner.replaceChildren();
59
- const grid = document.createElement('div');
60
- grid.className = 'pp-grid';
61
- grid.hidden = !app.gridVisible;
62
- this.inner.appendChild(grid);
63
- this.inner.appendChild(page);
64
- if (app.guidesVisible) {
65
- const staticGuides = document.createElement('div');
66
- staticGuides.className = 'pp-static-guides';
67
- staticGuides.innerHTML = '<i class="pp-static-guides__v"></i><i class="pp-static-guides__h"></i>';
68
- this.inner.appendChild(staticGuides);
69
- }
70
- this.inner.appendChild(this.guides);
71
- this.inner.appendChild(this.marquee);
72
- this.inner.appendChild(this.sel);
73
- this.guides.replaceChildren();
74
- this.applyScale();
75
- page.querySelectorAll('[data-obj-id]').forEach((el) => {
76
- if (el.dataset.objType === 'text' && !(el.querySelector('.sl-text')?.textContent || '').trim()) {
77
- const hint = document.createElement('div');
78
- hint.className = 'pp-empty-hint';
79
- hint.textContent = '单击此处添加文本';
80
- el.appendChild(hint);
81
- }
82
- });
83
- this.syncSelection();
84
- }
85
-
86
- applyScale() {
87
- const scale = this.scale;
88
- const { w, h } = this.size;
89
- this.inner.style.width = `${w}px`;
90
- this.inner.style.height = `${h}px`;
91
- this.inner.style.transform = `scale(${scale})`;
92
- this.holder.style.width = `${w * scale}px`;
93
- this.holder.style.height = `${h * scale}px`;
94
- this.sel.style.setProperty('--gbp-pp-inv', String(1 / scale));
95
- }
96
-
97
- /** 缩放/视图变化时只更新 transform,不重建内容 */
98
- rescale() {
99
- this.applyScale();
100
- this.syncSelection();
101
- }
102
-
103
- nodeFor(id) {
104
- return this.page?.querySelector(`[data-obj-id="${cssEscape(id)}"]`) || null;
105
- }
106
-
107
- updateNode(obj) {
108
- const node = this.nodeFor(obj.id);
109
- if (!node) return;
110
- const style = objectBoxStyle(obj);
111
- if (obj.type === 'line') {
112
- style.width = `${Math.max(1, parseFloat(style.width))}px`;
113
- style.height = `${Math.max(1, parseFloat(style.height))}px`;
114
- }
115
- Object.assign(node.style, style);
116
- }
117
-
118
- /** 选中框定位(单选显示手柄 + 旋转;多选显示并集框与组缩放) */
119
- syncSelection() {
120
- const app = this.app;
121
- const ids = app.selectedIds;
122
- const objs = app.currentSlide().objects.filter((o) => ids.includes(o.id));
123
- if (!objs.length) {
124
- this.sel.hidden = true;
125
- return;
126
- }
127
- const rect = unionRect(objs);
128
- const w = Math.max(1, rect.width);
129
- const h = Math.max(1, rect.height);
130
- this.sel.hidden = false;
131
- Object.assign(this.sel.style, { left: `${rect.left}px`, top: `${rect.top}px`, width: `${w}px`, height: `${h}px` });
132
- const single = objs.length === 1;
133
- for (const handle of this.sel.querySelectorAll('.pp-sel__handle')) handle.hidden = false;
134
- const rotate = this.sel.querySelector('.pp-sel__rotate');
135
- rotate.hidden = !single;
136
- this.sel.classList.toggle('gbp-is-multi', !single);
137
- if (single && objs[0].rot) {
138
- const center = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
139
- this.sel.style.transform = `rotate(${objs[0].rot}deg)`;
140
- this.sel.style.transformOrigin = `${center.x - rect.left}px ${center.y - rect.top}px`;
141
- rotate.style.top = `${-ROTATE_HANDLE_GAP / this.scale}px`;
142
- } else {
143
- this.sel.style.transform = '';
144
- this.sel.style.transformOrigin = '';
145
- rotate.style.top = `${-ROTATE_HANDLE_GAP / this.scale}px`;
146
- }
147
- }
148
-
149
- buildHandles() {
150
- for (const dir of ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']) {
151
- const h = document.createElement('span');
152
- h.className = 'pp-sel__handle';
153
- h.dataset.dir = dir;
154
- h.addEventListener('mousedown', (e) => this.startResize(dir, e));
155
- this.sel.appendChild(h);
156
- }
157
- const rot = document.createElement('span');
158
- rot.className = 'pp-sel__rotate';
159
- rot.title = '旋转';
160
- rot.addEventListener('mousedown', (e) => this.startRotate(e));
161
- this.sel.appendChild(rot);
162
- }
163
-
164
- /* ===================== 事件 ===================== */
165
-
166
- bind() {
167
- this.inner.addEventListener('mousedown', (e) => {
168
- if (e.button !== 0) return;
169
- const target = e.target;
170
- if (this.app.editing?.node && this.app.editing.node.contains(target)) return;
171
- if (this.app.editing) this.app.commitEditing({ render: false });
172
- if (target.closest('[contenteditable="true"]')) return;
173
- const objEl = target.closest('[data-obj-id]');
174
- if (objEl) {
175
- this.startDrag(objEl.dataset.objId, e);
176
- return;
177
- }
178
- if (target.closest('.pp-sel')) return;
179
- this.startMarquee(e);
180
- });
181
-
182
- this.inner.addEventListener('dblclick', (e) => this.onDoubleClick(e));
183
-
184
- this.scroll.addEventListener('mousedown', (e) => {
185
- if (e.target !== this.scroll && e.target !== this.holder) return;
186
- if (this.app.editing) this.app.commitEditing({ render: false });
187
- this.app.clearSelection();
188
- });
189
-
190
- this.el.addEventListener('contextmenu', (e) => {
191
- e.preventDefault();
192
- const objEl = e.target.closest('[data-obj-id]');
193
- if (objEl && !this.app.selectedIds.includes(objEl.dataset.objId)) {
194
- this.app.selectObjects([objEl.dataset.objId]);
195
- }
196
- this.app.openCanvasMenu(e.clientX, e.clientY);
197
- });
198
-
199
- this.unbindWheel = bindCtrlWheelZoom({
200
- target: this.el,
201
- scrollEl: this.scroll,
202
- scrollMode: 'scaled',
203
- getScale: () => this.app.zoom / 100,
204
- zoomStep: (direction) => {
205
- const before = this.app.zoom;
206
- this.app.setZoom(before + direction * 10);
207
- return this.app.zoom !== before;
208
- },
209
- });
210
-
211
- this.el.addEventListener('scroll', () => this.syncSelection(), true);
212
- }
213
-
214
- /** 客户端坐标 → 页面逻辑坐标 */
215
- toPage(e) {
216
- const rect = this.inner.getBoundingClientRect();
217
- const z = this.scale || 1;
218
- return { x: (e.clientX - rect.left) / z, y: (e.clientY - rect.top) / z };
219
- }
220
-
221
- onDoubleClick(e) {
222
- if (this.app.readOnly) return;
223
- const el = e.target.closest('[data-obj-id]');
224
- if (!el) return;
225
- const obj = this.app.selectedById(el.dataset.objId);
226
- if (!obj) return;
227
- e.preventDefault();
228
- if (obj.type === 'table') {
229
- const td = e.target.closest('td');
230
- if (td) this.startCellEdit(obj, td);
231
- return;
232
- }
233
- if (obj.type === 'text' || obj.type === 'shape') this.startTextEdit(obj, el, e);
234
- }
235
-
236
- /* ===================== 拖动 ===================== */
237
-
238
- startDrag(id, e) {
239
- const app = this.app;
240
- const additive = e.shiftKey || e.ctrlKey || e.metaKey;
241
- if (additive) {
242
- app.toggleSelect(id);
243
- return;
244
- }
245
- if (!app.selectedIds.includes(id)) app.selectObjects([id]);
246
- // 只读档仍可选中对象,但不启动会改坐标的拖拽手势
247
- if (app.readOnly) return;
248
- const origin = this.toPage(e);
249
- const starts = app.selectedObjects().map((o) => ({ obj: o, x: o.x, y: o.y }));
250
- if (!starts.length) return;
251
- const box = unionRect(starts.map((s) => s.obj));
252
- let moved = false;
253
- let begun = false;
254
- const move = (ev) => {
255
- const p = this.toPage(ev);
256
- let dx = p.x - origin.x;
257
- let dy = p.y - origin.y;
258
- if (!moved && Math.abs(dx) + Math.abs(dy) < 2) return;
259
- if (!moved) {
260
- moved = true;
261
- begun = true;
262
- app.beginGesture();
263
- }
264
- if (ev.shiftKey) {
265
- if (Math.abs(dx) > Math.abs(dy)) dy = 0;
266
- else dx = 0;
267
- }
268
- const snapped = this.snapMove(box, dx, dy, new Set(starts.map((s) => s.obj.id)));
269
- dx = snapped.dx;
270
- dy = snapped.dy;
271
- this.drawGuides(snapped.guides);
272
- for (const s of starts) {
273
- s.obj.x = Math.round(s.x + dx);
274
- s.obj.y = Math.round(s.y + dy);
275
- this.updateNode(s.obj);
276
- }
277
- this.syncSelection();
278
- app.updateGestureStatus?.();
279
- };
280
- const up = () => {
281
- document.removeEventListener('mousemove', move);
282
- document.removeEventListener('mouseup', up);
283
- this.clearGuides();
284
- if (moved) app.notifyChange();
285
- else if (begun) app.renderAll();
286
- };
287
- document.addEventListener('mousemove', move);
288
- document.addEventListener('mouseup', up);
289
- }
290
-
291
- /* ===================== 缩放 ===================== */
292
-
293
- startResize(dir, e) {
294
- if (this.app.readOnly) return;
295
- e.preventDefault();
296
- e.stopPropagation();
297
- const app = this.app;
298
- const objs = app.selectedObjects();
299
- if (!objs.length) return;
300
- const starts = objs.map((o) => {
301
- const r = objectRect(o);
302
- return { obj: o, rect: r, x: o.x, y: o.y, w: o.w, h: o.h };
303
- });
304
- const box = unionRect(objs);
305
- const origin = this.toPage(e);
306
- let moved = false;
307
- const move = (ev) => {
308
- const p = this.toPage(ev);
309
- let dx = p.x - origin.x;
310
- let dy = p.y - origin.y;
311
- if (!moved && Math.abs(dx) + Math.abs(dy) < 2) return;
312
- if (!moved) { moved = true; app.beginGesture(); }
313
-
314
- let left = box.left;
315
- let top = box.top;
316
- let right = box.left + box.width;
317
- let bottom = box.top + box.height;
318
- if (dir.includes('e')) right = Math.max(left + MIN_SIZE, right + dx);
319
- if (dir.includes('s')) bottom = Math.max(top + MIN_SIZE, bottom + dy);
320
- if (dir.includes('w')) left = Math.min(right - MIN_SIZE, left + dx);
321
- if (dir.includes('n')) top = Math.min(bottom - MIN_SIZE, top + dy);
322
-
323
- // 角手柄 + Shift:保持原比例
324
- if (ev.shiftKey && dir.length === 2) {
325
- const ratio = box.width / Math.max(1, box.height);
326
- const nw = right - left;
327
- const nh = bottom - top;
328
- if (Math.abs(nw / ratio) > nh) {
329
- const wantH = nw / ratio;
330
- if (dir.includes('s')) bottom = top + wantH;
331
- else if (dir.includes('n')) top = bottom - wantH;
332
- } else {
333
- const wantW = nh * ratio;
334
- if (dir.includes('e')) right = left + wantW;
335
- else if (dir.includes('w')) left = right - wantW;
336
- }
337
- }
338
-
339
- const snapped = this.snapResize(dir, { left, top, right, bottom }, new Set(objs.map((o) => o.id)));
340
- left = snapped.left; top = snapped.top; right = snapped.right; bottom = snapped.bottom;
341
- this.drawGuides(snapped.guides);
342
-
343
- const sx = (right - left) / Math.max(1, box.width);
344
- const sy = (bottom - top) / Math.max(1, box.height);
345
- for (const s of starts) {
346
- const o = s.obj;
347
- const mayGrowX = Math.abs(s.w) > 0 || dir.includes('e') || dir.includes('w');
348
- const mayGrowY = Math.abs(s.h) > 0 || dir.includes('n') || dir.includes('s');
349
- const nw = mayGrowX ? Math.max(MIN_SIZE, Math.round(s.rect.width * sx)) : 0;
350
- const nh = mayGrowY ? Math.max(MIN_SIZE, Math.round(s.rect.height * sy)) : 0;
351
- const nl = Math.round(left + (s.rect.left - box.left) * sx);
352
- const nt = Math.round(top + (s.rect.top - box.top) * sy);
353
- // 线条用「起点 + 向量」表达方向,负向量对象的起点在视觉右/下侧
354
- o.x = s.w < 0 ? nl + nw : nl;
355
- o.y = s.h < 0 ? nt + nh : nt;
356
- o.w = s.w < 0 ? -nw : nw;
357
- o.h = s.h < 0 ? -nh : nh;
358
- this.updateNode(o);
359
- }
360
- this.syncSelection();
361
- app.updateGestureStatus?.();
362
- };
363
- const up = () => {
364
- document.removeEventListener('mousemove', move);
365
- document.removeEventListener('mouseup', up);
366
- this.clearGuides();
367
- if (moved) app.notifyChange();
368
- };
369
- document.addEventListener('mousemove', move);
370
- document.addEventListener('mouseup', up);
371
- }
372
-
373
- /* ===================== 旋转 ===================== */
374
-
375
- startRotate(e) {
376
- if (this.app.readOnly) return;
377
- e.preventDefault();
378
- e.stopPropagation();
379
- const app = this.app;
380
- const obj = app.firstSelected();
381
- if (!obj) return;
382
- const r = objectRect(obj);
383
- const rect = this.inner.getBoundingClientRect();
384
- const scale = this.scale;
385
- const cx = rect.left + (r.left + r.width / 2) * scale;
386
- const cy = rect.top + (r.top + r.height / 2) * scale;
387
- const startAngle = Math.atan2(e.clientY - cy, e.clientX - cx) * 180 / Math.PI;
388
- const startRot = obj.rot || 0;
389
- let moved = false;
390
- const move = (ev) => {
391
- if (!moved) { moved = true; app.beginGesture(); }
392
- const angle = Math.atan2(ev.clientY - cy, ev.clientX - cx) * 180 / Math.PI;
393
- let rot = startRot + angle - startAngle;
394
- if (ev.shiftKey) rot = Math.round(rot / 15) * 15;
395
- obj.rot = ((Math.round(rot) % 360) + 360) % 360;
396
- this.updateNode(obj);
397
- this.syncSelection();
398
- app.updateGestureStatus?.();
399
- };
400
- const up = () => {
401
- document.removeEventListener('mousemove', move);
402
- document.removeEventListener('mouseup', up);
403
- if (moved) app.notifyChange();
404
- };
405
- document.addEventListener('mousemove', move);
406
- document.addEventListener('mouseup', up);
407
- }
408
-
409
- /* ===================== 框选 ===================== */
410
-
411
- startMarquee(e) {
412
- const app = this.app;
413
- const start = this.toPage(e);
414
- const additive = e.shiftKey || e.ctrlKey || e.metaKey;
415
- const base = additive ? [...app.selectedIds] : [];
416
- if (!additive) app.clearSelection();
417
- let moved = false;
418
- Object.assign(this.marquee.style, { left: `${start.x}px`, top: `${start.y}px`, width: '0px', height: '0px' });
419
- this.marquee.hidden = false;
420
- const move = (ev) => {
421
- const p = this.toPage(ev);
422
- const left = Math.min(start.x, p.x);
423
- const top = Math.min(start.y, p.y);
424
- const width = Math.abs(p.x - start.x);
425
- const height = Math.abs(p.y - start.y);
426
- if (width + height > 3) moved = true;
427
- Object.assign(this.marquee.style, { left: `${left}px`, top: `${top}px`, width: `${width}px`, height: `${height}px` });
428
- const hits = app.currentSlide().objects
429
- .filter((o) => {
430
- const r = objectRect(o);
431
- return r.left < left + width && r.left + r.width > left && r.top < top + height && r.top + r.height > top;
432
- })
433
- .map((o) => o.id);
434
- app.selectObjects([...new Set([...base, ...hits])]);
435
- };
436
- const up = () => {
437
- document.removeEventListener('mousemove', move);
438
- document.removeEventListener('mouseup', up);
439
- this.marquee.hidden = true;
440
- if (!moved) app.clearSelection();
441
- };
442
- document.addEventListener('mousemove', move);
443
- document.addEventListener('mouseup', up);
444
- }
445
-
446
- /* ===================== 吸附 ===================== */
447
-
448
- snapTargets(exclude) {
449
- const { w, h } = this.size;
450
- const xs = [0, w / 2, w];
451
- const ys = [0, h / 2, h];
452
- for (const o of this.app.currentSlide().objects) {
453
- if (exclude.has(o.id)) continue;
454
- const r = objectRect(o);
455
- xs.push(r.left, r.left + r.width / 2, r.left + r.width);
456
- ys.push(r.top, r.top + r.height / 2, r.top + r.height);
457
- }
458
- return { xs, ys };
459
- }
460
-
461
- snapMove(box, dx, dy, exclude) {
462
- const { xs, ys } = this.snapTargets(exclude);
463
- const th = SNAP_PX / this.scale;
464
- const edgesX = [box.left + dx, box.left + dx + box.width / 2, box.left + dx + box.width];
465
- const edgesY = [box.top + dy, box.top + dy + box.height / 2, box.top + dy + box.height];
466
- let bestX = null;
467
- let bestY = null;
468
- for (const edge of edgesX) {
469
- for (const target of xs) {
470
- const d = target - edge;
471
- if (Math.abs(d) <= th && (!bestX || Math.abs(d) < Math.abs(bestX.d))) bestX = { d, pos: target };
472
- }
473
- }
474
- for (const edge of edgesY) {
475
- for (const target of ys) {
476
- const d = target - edge;
477
- if (Math.abs(d) <= th && (!bestY || Math.abs(d) < Math.abs(bestY.d))) bestY = { d, pos: target };
478
- }
479
- }
480
- const guides = [];
481
- if (bestX) { dx += bestX.d; guides.push({ axis: 'v', pos: bestX.pos }); }
482
- if (bestY) { dy += bestY.d; guides.push({ axis: 'h', pos: bestY.pos }); }
483
- return { dx, dy, guides };
484
- }
485
-
486
- snapResize(dir, box, exclude) {
487
- const { xs, ys } = this.snapTargets(exclude);
488
- const th = SNAP_PX / this.scale;
489
- const guides = [];
490
- if (dir.includes('e')) {
491
- const hit = nearest(xs, box.right, th);
492
- if (hit !== null) { box.right = hit; guides.push({ axis: 'v', pos: hit }); }
493
- }
494
- if (dir.includes('w')) {
495
- const hit = nearest(xs, box.left, th);
496
- if (hit !== null) { box.left = hit; guides.push({ axis: 'v', pos: hit }); }
497
- }
498
- if (dir.includes('s')) {
499
- const hit = nearest(ys, box.bottom, th);
500
- if (hit !== null) { box.bottom = hit; guides.push({ axis: 'h', pos: hit }); }
501
- }
502
- if (dir.includes('n')) {
503
- const hit = nearest(ys, box.top, th);
504
- if (hit !== null) { box.top = hit; guides.push({ axis: 'h', pos: hit }); }
505
- }
506
- return { ...box, guides };
507
- }
508
-
509
- drawGuides(guides) {
510
- this.guides.replaceChildren();
511
- for (const g of guides || []) {
512
- const line = document.createElement('div');
513
- line.className = `pp-guide pp-guide--${g.axis}`;
514
- if (g.axis === 'v') {
515
- line.style.left = `${g.pos}px`;
516
- line.style.top = '0';
517
- line.style.height = `${this.size.h}px`;
518
- } else {
519
- line.style.top = `${g.pos}px`;
520
- line.style.left = '0';
521
- line.style.width = `${this.size.w}px`;
522
- }
523
- this.guides.appendChild(line);
524
- }
525
- this.guides.hidden = !(guides && guides.length);
526
- }
527
-
528
- clearGuides() {
529
- this.guides.replaceChildren();
530
- this.guides.hidden = true;
531
- }
532
-
533
- /* ===================== 文本编辑 ===================== */
534
-
535
- startTextEdit(obj, el, e) {
536
- if (this.app.readOnly) return;
537
- const node = obj.type === 'text' ? el.querySelector('.sl-text') : el.querySelector('.sl-shape-text');
538
- if (!node) return;
539
- if (this.app.editing) this.app.commitEditing({ render: false });
540
- el.classList.add('gbp-is-editing');
541
- el.querySelector('.pp-empty-hint')?.remove();
542
- const placeholder = obj.type === 'text' && !(node.textContent || '').trim();
543
- node.contentEditable = 'true';
544
- node.spellcheck = false;
545
- this.app.beginTextEdit(obj, node, obj.type === 'text' ? 'text' : 'shape');
546
- node.focus({ preventScroll: true });
547
- if (placeholder) {
548
- const range = document.createRange();
549
- range.selectNodeContents(node);
550
- range.collapse(false);
551
- const sel = window.getSelection();
552
- sel?.removeAllRanges();
553
- sel?.addRange(range);
554
- } else {
555
- this.placeCaret(node, e.clientX, e.clientY);
556
- }
557
- const onInput = () => this.app.syncEditing();
558
- const onBlur = (ev) => {
559
- // 焦点进入浮层(色板/菜单/对话框)时不结束编辑,选完颜色还能回到原选区
560
- if (ev?.relatedTarget?.closest?.('.gbp-popup, .gbp-modal-overlay')) return;
561
- node.removeEventListener('blur', onBlur);
562
- node.removeEventListener('keydown', onKey);
563
- node.removeEventListener('input', onInput);
564
- node.contentEditable = 'false';
565
- el.classList.remove('gbp-is-editing');
566
- // 不用立刻整页重绘:否则点缩略图时 DOM 被替换,click 会丢;下一次结构变化再渲染
567
- this.app.commitEditing({ node, render: false });
568
- };
569
- const onKey = (ev) => {
570
- if (ev.key === 'Escape') {
571
- ev.preventDefault();
572
- node.blur();
573
- }
574
- };
575
- node.addEventListener('input', onInput);
576
- node.addEventListener('blur', onBlur);
577
- node.addEventListener('keydown', onKey);
578
- }
579
-
580
- placeCaret(node, x, y) {
581
- const doc = node.ownerDocument;
582
- const range = doc.caretRangeFromPoint?.(x, y) || null;
583
- const sel = window.getSelection();
584
- if (range && node.contains(range.startContainer)) {
585
- sel?.removeAllRanges();
586
- sel?.addRange(range);
587
- return;
588
- }
589
- const fallback = document.createRange();
590
- fallback.selectNodeContents(node);
591
- fallback.collapse(false);
592
- sel?.removeAllRanges();
593
- sel?.addRange(fallback);
594
- }
595
-
596
- /* ===================== 表格编辑 ===================== */
597
-
598
- startCellEdit(obj, td) {
599
- if (this.app.readOnly) return;
600
- if (this.app.editing) this.app.commitEditing({ render: false });
601
- const tr = td.parentElement;
602
- const tbody = tr.parentElement;
603
- const ri = Array.from(tbody.children).indexOf(tr);
604
- const ci = Array.from(tr.children).indexOf(td);
605
- td.contentEditable = 'true';
606
- td.spellcheck = false;
607
- this.app.beginTextEdit(obj, td, 'cell', { ri, ci });
608
- td.focus({ preventScroll: true });
609
- const range = document.createRange();
610
- range.selectNodeContents(td);
611
- range.collapse(false);
612
- const sel = window.getSelection();
613
- sel?.removeAllRanges();
614
- sel?.addRange(range);
615
-
616
- const commit = () => {
617
- td.contentEditable = 'false';
618
- td.removeEventListener('blur', commit);
619
- td.removeEventListener('keydown', onKey);
620
- td.removeEventListener('input', onInput);
621
- this.app.commitEditing({ node: td, render: false });
622
- };
623
- const onInput = () => this.app.syncEditing();
624
- const onKey = (ev) => {
625
- if (ev.key === 'Escape') {
626
- ev.preventDefault();
627
- td.blur();
628
- return;
629
- }
630
- if (ev.key === 'Tab' || ev.key === 'Enter') {
631
- ev.preventDefault();
632
- const rows = obj.props.rows;
633
- let nr = ri;
634
- let nc = ci;
635
- if (ev.key === 'Tab') {
636
- nc += 1;
637
- if (nc >= (rows[0]?.length || 1)) {
638
- nc = 0;
639
- nr += 1;
640
- }
641
- } else {
642
- nr += 1;
643
- }
644
- td.blur();
645
- if (nr < rows.length && nc < (rows[0]?.length || 1)) {
646
- setTimeout(() => this.app.editCellAt(obj.id, nr, nc), 0);
647
- }
648
- }
649
- };
650
- td.addEventListener('input', onInput);
651
- td.addEventListener('blur', commit);
652
- td.addEventListener('keydown', onKey);
653
- }
654
-
655
- /** 把焦点和保存的选区还给正在编辑的文本(Ribbon 命令执行前调用) */
656
- focusEditing() {
657
- const e = this.app.editing;
658
- if (!e?.node) return;
659
- e.node.focus({ preventScroll: true });
660
- if (e.range) {
661
- const sel = window.getSelection();
662
- sel?.removeAllRanges();
663
- sel?.addRange(e.range);
664
- }
665
- }
666
-
667
- /** 从大纲/命令直接进入编辑(不依赖鼠标坐标) */
668
- editObject(id) {
669
- const obj = this.app.selectedById(id);
670
- const el = this.nodeFor(id);
671
- if (!obj || !el) return false;
672
- if (obj.type === 'table') return false;
673
- const rect = el.getBoundingClientRect();
674
- this.startTextEdit(obj, el, { clientX: rect.left + 24, clientY: rect.top + 20 });
675
- return true;
676
- }
677
-
678
- /** 打开指定单元格的编辑态(表格 Tab/Enter 导航与插入行列后复用) */
679
- editCell(obj, ri, ci) {
680
- const node = this.nodeFor(obj.id);
681
- if (!node) return false;
682
- const tr = node.querySelectorAll('tbody tr')[ri];
683
- const td = tr?.children[ci];
684
- if (!td) return false;
685
- this.startCellEdit(obj, td);
686
- return true;
687
- }
688
-
689
- /** 在画布上预览当前页切换动画 */
690
- previewTransition(tr) {
691
- if (!this.page) return;
692
- animateSlideFrame(this.page, tr);
693
- }
694
-
695
- flashObject(id) {
696
- const node = this.nodeFor(id);
697
- if (!node) return;
698
- node.classList.remove('gbp-is-flash');
699
- void node.offsetWidth;
700
- node.classList.add('gbp-is-flash');
701
- setTimeout(() => node.classList.remove('gbp-is-flash'), 900);
702
- }
703
-
704
- /**
705
- * 把当前文本选区包进带内联样式的 span(字体/字号/颜色用;多段落选区逐文本节点处理)
706
- * @param {object} styles 形如 { fontFamily, fontSize, color }
707
- * @returns {boolean} 是否命中非空选区
708
- */
709
- wrapSelection(styles) {
710
- const editing = this.app.editing;
711
- if (!editing?.node) return false;
712
- const root = editing.node;
713
- root.focus({ preventScroll: true });
714
- let range = editing.range?.cloneRange() || null;
715
- if (!range) {
716
- const sel = window.getSelection();
717
- if (sel?.rangeCount && root.contains(sel.anchorNode)) range = sel.getRangeAt(0).cloneRange();
718
- }
719
- if (!range || range.collapsed) return false;
720
- if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return false;
721
-
722
- const targets = [];
723
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
724
- let textNode = walker.nextNode();
725
- while (textNode) {
726
- if (textNode.data && range.intersectsNode(textNode)) {
727
- const start = textNode === range.startContainer ? range.startOffset : 0;
728
- const end = textNode === range.endContainer ? range.endOffset : textNode.data.length;
729
- if (end > start) targets.push({ node: textNode, start, end });
730
- }
731
- textNode = walker.nextNode();
732
- }
733
- if (!targets.length) return false;
734
-
735
- const spans = [];
736
- for (const t of targets) {
737
- const r = document.createRange();
738
- r.setStart(t.node, t.start);
739
- r.setEnd(t.node, t.end);
740
- const span = document.createElement('span');
741
- Object.assign(span.style, styles);
742
- span.appendChild(r.extractContents());
743
- r.insertNode(span);
744
- spans.push(span);
745
- }
746
- if (spans.length) {
747
- const sel = window.getSelection();
748
- const after = document.createRange();
749
- after.setStartBefore(spans[0]);
750
- after.setEndAfter(spans[spans.length - 1]);
751
- sel?.removeAllRanges();
752
- sel?.addRange(after);
753
- editing.range = after.cloneRange();
754
- }
755
- this.app.syncEditing();
756
- return true;
757
- }
758
- }
759
-
760
- function nearest(values, target, threshold) {
761
- let best = null;
762
- for (const v of values) {
763
- if (Math.abs(v - target) <= threshold && (best === null || Math.abs(v - target) < Math.abs(best - target))) best = v;
764
- }
765
- return best;
766
- }
767
-
768
- // 供外部布局计算使用(保持与渲染层同口径)
769
- export const canvasDefaults = { minSize: MIN_SIZE, snap: SNAP_PX, width: SLIDE_W, height: SLIDE_H };
1
+ // [文件] gbpptx·画布 —— Office 式编辑面(多选/框选/吸附/组缩放/旋转/就地文本与表格编辑/缩放)
2
+
3
+ import { SLIDE_H, SLIDE_W, objectBoxStyle, objectRect, unionRect } from '../../../src/kernel/model.js';
4
+ import { bindCtrlWheelZoom } from 'guabiutils';
5
+ import { renderPage } from './page-view.js';
6
+ import { animateSlideFrame } from './transition.js';
7
+
8
+ const MIN_SIZE = 8;
9
+ const SNAP_PX = 6;
10
+ const ROTATE_HANDLE_GAP = 28;
11
+
12
+ const cssEscape = (s) => (window.CSS?.escape ? CSS.escape(String(s)) : String(s).replace(/["\\]/g, '\\$&'));
13
+
14
+ export class Canvas {
15
+ constructor(app) {
16
+ this.app = app;
17
+ this.el = document.createElement('div');
18
+ this.el.className = 'pp-canvas';
19
+ this.scroll = document.createElement('div');
20
+ this.scroll.className = 'pp-canvas__scroll';
21
+ this.holder = document.createElement('div');
22
+ this.holder.className = 'pp-canvas__holder';
23
+ this.inner = document.createElement('div');
24
+ this.inner.className = 'pp-canvas__inner';
25
+ this.holder.appendChild(this.inner);
26
+ this.scroll.appendChild(this.holder);
27
+ this.el.appendChild(this.scroll);
28
+
29
+ this.sel = document.createElement('div');
30
+ this.sel.className = 'pp-sel';
31
+ this.sel.hidden = true;
32
+ this.buildHandles();
33
+
34
+ this.guides = document.createElement('div');
35
+ this.guides.className = 'pp-guides';
36
+ this.marquee = document.createElement('div');
37
+ this.marquee.className = 'pp-marquee';
38
+ this.marquee.hidden = true;
39
+
40
+ this.bind();
41
+ }
42
+
43
+ get scale() {
44
+ return this.app.zoom / 100;
45
+ }
46
+
47
+ get size() {
48
+ return this.app.size;
49
+ }
50
+
51
+ /* ===================== 渲染 ===================== */
52
+
53
+ render() {
54
+ const app = this.app;
55
+ const slide = app.currentSlide();
56
+ const page = renderPage(slide, app.snapshot.theme, { interactive: true, size: this.size });
57
+ this.page = page;
58
+ this.inner.replaceChildren();
59
+ const grid = document.createElement('div');
60
+ grid.className = 'pp-grid';
61
+ grid.hidden = !app.gridVisible;
62
+ this.inner.appendChild(grid);
63
+ this.inner.appendChild(page);
64
+ if (app.guidesVisible) {
65
+ const staticGuides = document.createElement('div');
66
+ staticGuides.className = 'pp-static-guides';
67
+ staticGuides.innerHTML = '<i class="pp-static-guides__v"></i><i class="pp-static-guides__h"></i>';
68
+ this.inner.appendChild(staticGuides);
69
+ }
70
+ this.inner.appendChild(this.guides);
71
+ this.inner.appendChild(this.marquee);
72
+ this.inner.appendChild(this.sel);
73
+ this.guides.replaceChildren();
74
+ this.applyScale();
75
+ page.querySelectorAll('[data-obj-id]').forEach((el) => {
76
+ if (el.dataset.objType === 'text' && !(el.querySelector('.sl-text')?.textContent || '').trim()) {
77
+ const hint = document.createElement('div');
78
+ hint.className = 'pp-empty-hint';
79
+ hint.textContent = '单击此处添加文本';
80
+ el.appendChild(hint);
81
+ }
82
+ });
83
+ this.syncSelection();
84
+ }
85
+
86
+ applyScale() {
87
+ const scale = this.scale;
88
+ const { w, h } = this.size;
89
+ this.inner.style.width = `${w}px`;
90
+ this.inner.style.height = `${h}px`;
91
+ this.inner.style.transform = `scale(${scale})`;
92
+ this.holder.style.width = `${w * scale}px`;
93
+ this.holder.style.height = `${h * scale}px`;
94
+ this.sel.style.setProperty('--gbp-pp-inv', String(1 / scale));
95
+ }
96
+
97
+ /** 缩放/视图变化时只更新 transform,不重建内容 */
98
+ rescale() {
99
+ this.applyScale();
100
+ this.syncSelection();
101
+ }
102
+
103
+ nodeFor(id) {
104
+ return this.page?.querySelector(`[data-obj-id="${cssEscape(id)}"]`) || null;
105
+ }
106
+
107
+ updateNode(obj) {
108
+ const node = this.nodeFor(obj.id);
109
+ if (!node) return;
110
+ const style = objectBoxStyle(obj);
111
+ if (obj.type === 'line') {
112
+ style.width = `${Math.max(1, parseFloat(style.width))}px`;
113
+ style.height = `${Math.max(1, parseFloat(style.height))}px`;
114
+ }
115
+ Object.assign(node.style, style);
116
+ }
117
+
118
+ /** 选中框定位(单选显示手柄 + 旋转;多选显示并集框与组缩放) */
119
+ syncSelection() {
120
+ const app = this.app;
121
+ const ids = app.selectedIds;
122
+ const objs = app.currentSlide().objects.filter((o) => ids.includes(o.id));
123
+ if (!objs.length) {
124
+ this.sel.hidden = true;
125
+ return;
126
+ }
127
+ const rect = unionRect(objs);
128
+ const w = Math.max(1, rect.width);
129
+ const h = Math.max(1, rect.height);
130
+ this.sel.hidden = false;
131
+ Object.assign(this.sel.style, { left: `${rect.left}px`, top: `${rect.top}px`, width: `${w}px`, height: `${h}px` });
132
+ const single = objs.length === 1;
133
+ for (const handle of this.sel.querySelectorAll('.pp-sel__handle')) handle.hidden = false;
134
+ const rotate = this.sel.querySelector('.pp-sel__rotate');
135
+ rotate.hidden = !single;
136
+ this.sel.classList.toggle('gbp-is-multi', !single);
137
+ if (single && objs[0].rot) {
138
+ const center = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
139
+ this.sel.style.transform = `rotate(${objs[0].rot}deg)`;
140
+ this.sel.style.transformOrigin = `${center.x - rect.left}px ${center.y - rect.top}px`;
141
+ rotate.style.top = `${-ROTATE_HANDLE_GAP / this.scale}px`;
142
+ } else {
143
+ this.sel.style.transform = '';
144
+ this.sel.style.transformOrigin = '';
145
+ rotate.style.top = `${-ROTATE_HANDLE_GAP / this.scale}px`;
146
+ }
147
+ }
148
+
149
+ buildHandles() {
150
+ for (const dir of ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']) {
151
+ const h = document.createElement('span');
152
+ h.className = 'pp-sel__handle';
153
+ h.dataset.dir = dir;
154
+ h.addEventListener('mousedown', (e) => this.startResize(dir, e));
155
+ this.sel.appendChild(h);
156
+ }
157
+ const rot = document.createElement('span');
158
+ rot.className = 'pp-sel__rotate';
159
+ rot.title = '旋转';
160
+ rot.addEventListener('mousedown', (e) => this.startRotate(e));
161
+ this.sel.appendChild(rot);
162
+ }
163
+
164
+ /* ===================== 事件 ===================== */
165
+
166
+ bind() {
167
+ this.inner.addEventListener('mousedown', (e) => {
168
+ if (e.button !== 0) return;
169
+ const target = e.target;
170
+ if (this.app.editing?.node && this.app.editing.node.contains(target)) return;
171
+ if (this.app.editing) this.app.commitEditing({ render: false });
172
+ if (target.closest('[contenteditable="true"]')) return;
173
+ const objEl = target.closest('[data-obj-id]');
174
+ if (objEl) {
175
+ this.startDrag(objEl.dataset.objId, e);
176
+ return;
177
+ }
178
+ if (target.closest('.pp-sel')) return;
179
+ this.startMarquee(e);
180
+ });
181
+
182
+ this.inner.addEventListener('dblclick', (e) => this.onDoubleClick(e));
183
+
184
+ this.scroll.addEventListener('mousedown', (e) => {
185
+ if (e.target !== this.scroll && e.target !== this.holder) return;
186
+ if (this.app.editing) this.app.commitEditing({ render: false });
187
+ this.app.clearSelection();
188
+ });
189
+
190
+ this.el.addEventListener('contextmenu', (e) => {
191
+ e.preventDefault();
192
+ const objEl = e.target.closest('[data-obj-id]');
193
+ if (objEl && !this.app.selectedIds.includes(objEl.dataset.objId)) {
194
+ this.app.selectObjects([objEl.dataset.objId]);
195
+ }
196
+ this.app.openCanvasMenu(e.clientX, e.clientY);
197
+ });
198
+
199
+ this.unbindWheel = bindCtrlWheelZoom({
200
+ target: this.el,
201
+ scrollEl: this.scroll,
202
+ scrollMode: 'scaled',
203
+ getScale: () => this.app.zoom / 100,
204
+ zoomStep: (direction) => {
205
+ const before = this.app.zoom;
206
+ this.app.setZoom(before + direction * 10);
207
+ return this.app.zoom !== before;
208
+ },
209
+ });
210
+
211
+ this.el.addEventListener('scroll', () => this.syncSelection(), true);
212
+ }
213
+
214
+ /** 客户端坐标 → 页面逻辑坐标 */
215
+ toPage(e) {
216
+ const rect = this.inner.getBoundingClientRect();
217
+ const z = this.scale || 1;
218
+ return { x: (e.clientX - rect.left) / z, y: (e.clientY - rect.top) / z };
219
+ }
220
+
221
+ onDoubleClick(e) {
222
+ if (this.app.readOnly) return;
223
+ const el = e.target.closest('[data-obj-id]');
224
+ if (!el) return;
225
+ const obj = this.app.selectedById(el.dataset.objId);
226
+ if (!obj) return;
227
+ e.preventDefault();
228
+ if (obj.type === 'table') {
229
+ const td = e.target.closest('td');
230
+ if (td) this.startCellEdit(obj, td);
231
+ return;
232
+ }
233
+ if (obj.type === 'text' || obj.type === 'shape') this.startTextEdit(obj, el, e);
234
+ }
235
+
236
+ /* ===================== 拖动 ===================== */
237
+
238
+ startDrag(id, e) {
239
+ const app = this.app;
240
+ const additive = e.shiftKey || e.ctrlKey || e.metaKey;
241
+ if (additive) {
242
+ app.toggleSelect(id);
243
+ return;
244
+ }
245
+ if (!app.selectedIds.includes(id)) app.selectObjects([id]);
246
+ // 只读档仍可选中对象,但不启动会改坐标的拖拽手势
247
+ if (app.readOnly) return;
248
+ const origin = this.toPage(e);
249
+ const starts = app.selectedObjects().map((o) => ({ obj: o, x: o.x, y: o.y }));
250
+ if (!starts.length) return;
251
+ const box = unionRect(starts.map((s) => s.obj));
252
+ let moved = false;
253
+ let begun = false;
254
+ const move = (ev) => {
255
+ const p = this.toPage(ev);
256
+ let dx = p.x - origin.x;
257
+ let dy = p.y - origin.y;
258
+ if (!moved && Math.abs(dx) + Math.abs(dy) < 2) return;
259
+ if (!moved) {
260
+ moved = true;
261
+ begun = true;
262
+ app.beginGesture();
263
+ }
264
+ if (ev.shiftKey) {
265
+ if (Math.abs(dx) > Math.abs(dy)) dy = 0;
266
+ else dx = 0;
267
+ }
268
+ const snapped = this.snapMove(box, dx, dy, new Set(starts.map((s) => s.obj.id)));
269
+ dx = snapped.dx;
270
+ dy = snapped.dy;
271
+ this.drawGuides(snapped.guides);
272
+ for (const s of starts) {
273
+ s.obj.x = Math.round(s.x + dx);
274
+ s.obj.y = Math.round(s.y + dy);
275
+ this.updateNode(s.obj);
276
+ }
277
+ this.syncSelection();
278
+ app.updateGestureStatus?.();
279
+ };
280
+ const up = () => {
281
+ document.removeEventListener('mousemove', move);
282
+ document.removeEventListener('mouseup', up);
283
+ this.clearGuides();
284
+ if (moved) app.notifyChange();
285
+ else if (begun) app.renderAll();
286
+ };
287
+ document.addEventListener('mousemove', move);
288
+ document.addEventListener('mouseup', up);
289
+ }
290
+
291
+ /* ===================== 缩放 ===================== */
292
+
293
+ startResize(dir, e) {
294
+ if (this.app.readOnly) return;
295
+ e.preventDefault();
296
+ e.stopPropagation();
297
+ const app = this.app;
298
+ const objs = app.selectedObjects();
299
+ if (!objs.length) return;
300
+ const starts = objs.map((o) => {
301
+ const r = objectRect(o);
302
+ return { obj: o, rect: r, x: o.x, y: o.y, w: o.w, h: o.h };
303
+ });
304
+ const box = unionRect(objs);
305
+ const origin = this.toPage(e);
306
+ let moved = false;
307
+ const move = (ev) => {
308
+ const p = this.toPage(ev);
309
+ let dx = p.x - origin.x;
310
+ let dy = p.y - origin.y;
311
+ if (!moved && Math.abs(dx) + Math.abs(dy) < 2) return;
312
+ if (!moved) { moved = true; app.beginGesture(); }
313
+
314
+ let left = box.left;
315
+ let top = box.top;
316
+ let right = box.left + box.width;
317
+ let bottom = box.top + box.height;
318
+ if (dir.includes('e')) right = Math.max(left + MIN_SIZE, right + dx);
319
+ if (dir.includes('s')) bottom = Math.max(top + MIN_SIZE, bottom + dy);
320
+ if (dir.includes('w')) left = Math.min(right - MIN_SIZE, left + dx);
321
+ if (dir.includes('n')) top = Math.min(bottom - MIN_SIZE, top + dy);
322
+
323
+ // 角手柄 + Shift:保持原比例
324
+ if (ev.shiftKey && dir.length === 2) {
325
+ const ratio = box.width / Math.max(1, box.height);
326
+ const nw = right - left;
327
+ const nh = bottom - top;
328
+ if (Math.abs(nw / ratio) > nh) {
329
+ const wantH = nw / ratio;
330
+ if (dir.includes('s')) bottom = top + wantH;
331
+ else if (dir.includes('n')) top = bottom - wantH;
332
+ } else {
333
+ const wantW = nh * ratio;
334
+ if (dir.includes('e')) right = left + wantW;
335
+ else if (dir.includes('w')) left = right - wantW;
336
+ }
337
+ }
338
+
339
+ const snapped = this.snapResize(dir, { left, top, right, bottom }, new Set(objs.map((o) => o.id)));
340
+ left = snapped.left; top = snapped.top; right = snapped.right; bottom = snapped.bottom;
341
+ this.drawGuides(snapped.guides);
342
+
343
+ const sx = (right - left) / Math.max(1, box.width);
344
+ const sy = (bottom - top) / Math.max(1, box.height);
345
+ for (const s of starts) {
346
+ const o = s.obj;
347
+ const mayGrowX = Math.abs(s.w) > 0 || dir.includes('e') || dir.includes('w');
348
+ const mayGrowY = Math.abs(s.h) > 0 || dir.includes('n') || dir.includes('s');
349
+ const nw = mayGrowX ? Math.max(MIN_SIZE, Math.round(s.rect.width * sx)) : 0;
350
+ const nh = mayGrowY ? Math.max(MIN_SIZE, Math.round(s.rect.height * sy)) : 0;
351
+ const nl = Math.round(left + (s.rect.left - box.left) * sx);
352
+ const nt = Math.round(top + (s.rect.top - box.top) * sy);
353
+ // 线条用「起点 + 向量」表达方向,负向量对象的起点在视觉右/下侧
354
+ o.x = s.w < 0 ? nl + nw : nl;
355
+ o.y = s.h < 0 ? nt + nh : nt;
356
+ o.w = s.w < 0 ? -nw : nw;
357
+ o.h = s.h < 0 ? -nh : nh;
358
+ this.updateNode(o);
359
+ }
360
+ this.syncSelection();
361
+ app.updateGestureStatus?.();
362
+ };
363
+ const up = () => {
364
+ document.removeEventListener('mousemove', move);
365
+ document.removeEventListener('mouseup', up);
366
+ this.clearGuides();
367
+ if (moved) app.notifyChange();
368
+ };
369
+ document.addEventListener('mousemove', move);
370
+ document.addEventListener('mouseup', up);
371
+ }
372
+
373
+ /* ===================== 旋转 ===================== */
374
+
375
+ startRotate(e) {
376
+ if (this.app.readOnly) return;
377
+ e.preventDefault();
378
+ e.stopPropagation();
379
+ const app = this.app;
380
+ const obj = app.firstSelected();
381
+ if (!obj) return;
382
+ const r = objectRect(obj);
383
+ const rect = this.inner.getBoundingClientRect();
384
+ const scale = this.scale;
385
+ const cx = rect.left + (r.left + r.width / 2) * scale;
386
+ const cy = rect.top + (r.top + r.height / 2) * scale;
387
+ const startAngle = Math.atan2(e.clientY - cy, e.clientX - cx) * 180 / Math.PI;
388
+ const startRot = obj.rot || 0;
389
+ let moved = false;
390
+ const move = (ev) => {
391
+ if (!moved) { moved = true; app.beginGesture(); }
392
+ const angle = Math.atan2(ev.clientY - cy, ev.clientX - cx) * 180 / Math.PI;
393
+ let rot = startRot + angle - startAngle;
394
+ if (ev.shiftKey) rot = Math.round(rot / 15) * 15;
395
+ obj.rot = ((Math.round(rot) % 360) + 360) % 360;
396
+ this.updateNode(obj);
397
+ this.syncSelection();
398
+ app.updateGestureStatus?.();
399
+ };
400
+ const up = () => {
401
+ document.removeEventListener('mousemove', move);
402
+ document.removeEventListener('mouseup', up);
403
+ if (moved) app.notifyChange();
404
+ };
405
+ document.addEventListener('mousemove', move);
406
+ document.addEventListener('mouseup', up);
407
+ }
408
+
409
+ /* ===================== 框选 ===================== */
410
+
411
+ startMarquee(e) {
412
+ const app = this.app;
413
+ const start = this.toPage(e);
414
+ const additive = e.shiftKey || e.ctrlKey || e.metaKey;
415
+ const base = additive ? [...app.selectedIds] : [];
416
+ if (!additive) app.clearSelection();
417
+ let moved = false;
418
+ Object.assign(this.marquee.style, { left: `${start.x}px`, top: `${start.y}px`, width: '0px', height: '0px' });
419
+ this.marquee.hidden = false;
420
+ const move = (ev) => {
421
+ const p = this.toPage(ev);
422
+ const left = Math.min(start.x, p.x);
423
+ const top = Math.min(start.y, p.y);
424
+ const width = Math.abs(p.x - start.x);
425
+ const height = Math.abs(p.y - start.y);
426
+ if (width + height > 3) moved = true;
427
+ Object.assign(this.marquee.style, { left: `${left}px`, top: `${top}px`, width: `${width}px`, height: `${height}px` });
428
+ const hits = app.currentSlide().objects
429
+ .filter((o) => {
430
+ const r = objectRect(o);
431
+ return r.left < left + width && r.left + r.width > left && r.top < top + height && r.top + r.height > top;
432
+ })
433
+ .map((o) => o.id);
434
+ app.selectObjects([...new Set([...base, ...hits])]);
435
+ };
436
+ const up = () => {
437
+ document.removeEventListener('mousemove', move);
438
+ document.removeEventListener('mouseup', up);
439
+ this.marquee.hidden = true;
440
+ if (!moved) app.clearSelection();
441
+ };
442
+ document.addEventListener('mousemove', move);
443
+ document.addEventListener('mouseup', up);
444
+ }
445
+
446
+ /* ===================== 吸附 ===================== */
447
+
448
+ snapTargets(exclude) {
449
+ const { w, h } = this.size;
450
+ const xs = [0, w / 2, w];
451
+ const ys = [0, h / 2, h];
452
+ for (const o of this.app.currentSlide().objects) {
453
+ if (exclude.has(o.id)) continue;
454
+ const r = objectRect(o);
455
+ xs.push(r.left, r.left + r.width / 2, r.left + r.width);
456
+ ys.push(r.top, r.top + r.height / 2, r.top + r.height);
457
+ }
458
+ return { xs, ys };
459
+ }
460
+
461
+ snapMove(box, dx, dy, exclude) {
462
+ const { xs, ys } = this.snapTargets(exclude);
463
+ const th = SNAP_PX / this.scale;
464
+ const edgesX = [box.left + dx, box.left + dx + box.width / 2, box.left + dx + box.width];
465
+ const edgesY = [box.top + dy, box.top + dy + box.height / 2, box.top + dy + box.height];
466
+ let bestX = null;
467
+ let bestY = null;
468
+ for (const edge of edgesX) {
469
+ for (const target of xs) {
470
+ const d = target - edge;
471
+ if (Math.abs(d) <= th && (!bestX || Math.abs(d) < Math.abs(bestX.d))) bestX = { d, pos: target };
472
+ }
473
+ }
474
+ for (const edge of edgesY) {
475
+ for (const target of ys) {
476
+ const d = target - edge;
477
+ if (Math.abs(d) <= th && (!bestY || Math.abs(d) < Math.abs(bestY.d))) bestY = { d, pos: target };
478
+ }
479
+ }
480
+ const guides = [];
481
+ if (bestX) { dx += bestX.d; guides.push({ axis: 'v', pos: bestX.pos }); }
482
+ if (bestY) { dy += bestY.d; guides.push({ axis: 'h', pos: bestY.pos }); }
483
+ return { dx, dy, guides };
484
+ }
485
+
486
+ snapResize(dir, box, exclude) {
487
+ const { xs, ys } = this.snapTargets(exclude);
488
+ const th = SNAP_PX / this.scale;
489
+ const guides = [];
490
+ if (dir.includes('e')) {
491
+ const hit = nearest(xs, box.right, th);
492
+ if (hit !== null) { box.right = hit; guides.push({ axis: 'v', pos: hit }); }
493
+ }
494
+ if (dir.includes('w')) {
495
+ const hit = nearest(xs, box.left, th);
496
+ if (hit !== null) { box.left = hit; guides.push({ axis: 'v', pos: hit }); }
497
+ }
498
+ if (dir.includes('s')) {
499
+ const hit = nearest(ys, box.bottom, th);
500
+ if (hit !== null) { box.bottom = hit; guides.push({ axis: 'h', pos: hit }); }
501
+ }
502
+ if (dir.includes('n')) {
503
+ const hit = nearest(ys, box.top, th);
504
+ if (hit !== null) { box.top = hit; guides.push({ axis: 'h', pos: hit }); }
505
+ }
506
+ return { ...box, guides };
507
+ }
508
+
509
+ drawGuides(guides) {
510
+ this.guides.replaceChildren();
511
+ for (const g of guides || []) {
512
+ const line = document.createElement('div');
513
+ line.className = `pp-guide pp-guide--${g.axis}`;
514
+ if (g.axis === 'v') {
515
+ line.style.left = `${g.pos}px`;
516
+ line.style.top = '0';
517
+ line.style.height = `${this.size.h}px`;
518
+ } else {
519
+ line.style.top = `${g.pos}px`;
520
+ line.style.left = '0';
521
+ line.style.width = `${this.size.w}px`;
522
+ }
523
+ this.guides.appendChild(line);
524
+ }
525
+ this.guides.hidden = !(guides && guides.length);
526
+ }
527
+
528
+ clearGuides() {
529
+ this.guides.replaceChildren();
530
+ this.guides.hidden = true;
531
+ }
532
+
533
+ /* ===================== 文本编辑 ===================== */
534
+
535
+ startTextEdit(obj, el, e) {
536
+ if (this.app.readOnly) return;
537
+ const node = obj.type === 'text' ? el.querySelector('.sl-text') : el.querySelector('.sl-shape-text');
538
+ if (!node) return;
539
+ if (this.app.editing) this.app.commitEditing({ render: false });
540
+ el.classList.add('gbp-is-editing');
541
+ el.querySelector('.pp-empty-hint')?.remove();
542
+ const placeholder = obj.type === 'text' && !(node.textContent || '').trim();
543
+ node.contentEditable = 'true';
544
+ node.spellcheck = false;
545
+ this.app.beginTextEdit(obj, node, obj.type === 'text' ? 'text' : 'shape');
546
+ node.focus({ preventScroll: true });
547
+ if (placeholder) {
548
+ const range = document.createRange();
549
+ range.selectNodeContents(node);
550
+ range.collapse(false);
551
+ const sel = window.getSelection();
552
+ sel?.removeAllRanges();
553
+ sel?.addRange(range);
554
+ } else {
555
+ this.placeCaret(node, e.clientX, e.clientY);
556
+ }
557
+ const onInput = () => this.app.syncEditing();
558
+ const onBlur = (ev) => {
559
+ // 焦点进入浮层(色板/菜单/对话框)时不结束编辑,选完颜色还能回到原选区
560
+ if (ev?.relatedTarget?.closest?.('.gbp-popup, .gbp-modal-overlay')) return;
561
+ node.removeEventListener('blur', onBlur);
562
+ node.removeEventListener('keydown', onKey);
563
+ node.removeEventListener('input', onInput);
564
+ node.contentEditable = 'false';
565
+ el.classList.remove('gbp-is-editing');
566
+ // 不用立刻整页重绘:否则点缩略图时 DOM 被替换,click 会丢;下一次结构变化再渲染
567
+ this.app.commitEditing({ node, render: false });
568
+ };
569
+ const onKey = (ev) => {
570
+ if (ev.key === 'Escape') {
571
+ ev.preventDefault();
572
+ node.blur();
573
+ }
574
+ };
575
+ node.addEventListener('input', onInput);
576
+ node.addEventListener('blur', onBlur);
577
+ node.addEventListener('keydown', onKey);
578
+ }
579
+
580
+ placeCaret(node, x, y) {
581
+ const doc = node.ownerDocument;
582
+ const range = doc.caretRangeFromPoint?.(x, y) || null;
583
+ const sel = window.getSelection();
584
+ if (range && node.contains(range.startContainer)) {
585
+ sel?.removeAllRanges();
586
+ sel?.addRange(range);
587
+ return;
588
+ }
589
+ const fallback = document.createRange();
590
+ fallback.selectNodeContents(node);
591
+ fallback.collapse(false);
592
+ sel?.removeAllRanges();
593
+ sel?.addRange(fallback);
594
+ }
595
+
596
+ /* ===================== 表格编辑 ===================== */
597
+
598
+ startCellEdit(obj, td) {
599
+ if (this.app.readOnly) return;
600
+ if (this.app.editing) this.app.commitEditing({ render: false });
601
+ const tr = td.parentElement;
602
+ const tbody = tr.parentElement;
603
+ const ri = Array.from(tbody.children).indexOf(tr);
604
+ const ci = Array.from(tr.children).indexOf(td);
605
+ td.contentEditable = 'true';
606
+ td.spellcheck = false;
607
+ this.app.beginTextEdit(obj, td, 'cell', { ri, ci });
608
+ td.focus({ preventScroll: true });
609
+ const range = document.createRange();
610
+ range.selectNodeContents(td);
611
+ range.collapse(false);
612
+ const sel = window.getSelection();
613
+ sel?.removeAllRanges();
614
+ sel?.addRange(range);
615
+
616
+ const commit = () => {
617
+ td.contentEditable = 'false';
618
+ td.removeEventListener('blur', commit);
619
+ td.removeEventListener('keydown', onKey);
620
+ td.removeEventListener('input', onInput);
621
+ this.app.commitEditing({ node: td, render: false });
622
+ };
623
+ const onInput = () => this.app.syncEditing();
624
+ const onKey = (ev) => {
625
+ if (ev.key === 'Escape') {
626
+ ev.preventDefault();
627
+ td.blur();
628
+ return;
629
+ }
630
+ if (ev.key === 'Tab' || ev.key === 'Enter') {
631
+ ev.preventDefault();
632
+ const rows = obj.props.rows;
633
+ let nr = ri;
634
+ let nc = ci;
635
+ if (ev.key === 'Tab') {
636
+ nc += 1;
637
+ if (nc >= (rows[0]?.length || 1)) {
638
+ nc = 0;
639
+ nr += 1;
640
+ }
641
+ } else {
642
+ nr += 1;
643
+ }
644
+ td.blur();
645
+ if (nr < rows.length && nc < (rows[0]?.length || 1)) {
646
+ setTimeout(() => this.app.editCellAt(obj.id, nr, nc), 0);
647
+ }
648
+ }
649
+ };
650
+ td.addEventListener('input', onInput);
651
+ td.addEventListener('blur', commit);
652
+ td.addEventListener('keydown', onKey);
653
+ }
654
+
655
+ /** 把焦点和保存的选区还给正在编辑的文本(Ribbon 命令执行前调用) */
656
+ focusEditing() {
657
+ const e = this.app.editing;
658
+ if (!e?.node) return;
659
+ e.node.focus({ preventScroll: true });
660
+ if (e.range) {
661
+ const sel = window.getSelection();
662
+ sel?.removeAllRanges();
663
+ sel?.addRange(e.range);
664
+ }
665
+ }
666
+
667
+ /** 从大纲/命令直接进入编辑(不依赖鼠标坐标) */
668
+ editObject(id) {
669
+ const obj = this.app.selectedById(id);
670
+ const el = this.nodeFor(id);
671
+ if (!obj || !el) return false;
672
+ if (obj.type === 'table') return false;
673
+ const rect = el.getBoundingClientRect();
674
+ this.startTextEdit(obj, el, { clientX: rect.left + 24, clientY: rect.top + 20 });
675
+ return true;
676
+ }
677
+
678
+ /** 打开指定单元格的编辑态(表格 Tab/Enter 导航与插入行列后复用) */
679
+ editCell(obj, ri, ci) {
680
+ const node = this.nodeFor(obj.id);
681
+ if (!node) return false;
682
+ const tr = node.querySelectorAll('tbody tr')[ri];
683
+ const td = tr?.children[ci];
684
+ if (!td) return false;
685
+ this.startCellEdit(obj, td);
686
+ return true;
687
+ }
688
+
689
+ /** 在画布上预览当前页切换动画 */
690
+ previewTransition(tr) {
691
+ if (!this.page) return;
692
+ animateSlideFrame(this.page, tr);
693
+ }
694
+
695
+ flashObject(id) {
696
+ const node = this.nodeFor(id);
697
+ if (!node) return;
698
+ node.classList.remove('gbp-is-flash');
699
+ void node.offsetWidth;
700
+ node.classList.add('gbp-is-flash');
701
+ setTimeout(() => node.classList.remove('gbp-is-flash'), 900);
702
+ }
703
+
704
+ /**
705
+ * 把当前文本选区包进带内联样式的 span(字体/字号/颜色用;多段落选区逐文本节点处理)
706
+ * @param {object} styles 形如 { fontFamily, fontSize, color }
707
+ * @returns {boolean} 是否命中非空选区
708
+ */
709
+ wrapSelection(styles) {
710
+ const editing = this.app.editing;
711
+ if (!editing?.node) return false;
712
+ const root = editing.node;
713
+ root.focus({ preventScroll: true });
714
+ let range = editing.range?.cloneRange() || null;
715
+ if (!range) {
716
+ const sel = window.getSelection();
717
+ if (sel?.rangeCount && root.contains(sel.anchorNode)) range = sel.getRangeAt(0).cloneRange();
718
+ }
719
+ if (!range || range.collapsed) return false;
720
+ if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return false;
721
+
722
+ const targets = [];
723
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
724
+ let textNode = walker.nextNode();
725
+ while (textNode) {
726
+ if (textNode.data && range.intersectsNode(textNode)) {
727
+ const start = textNode === range.startContainer ? range.startOffset : 0;
728
+ const end = textNode === range.endContainer ? range.endOffset : textNode.data.length;
729
+ if (end > start) targets.push({ node: textNode, start, end });
730
+ }
731
+ textNode = walker.nextNode();
732
+ }
733
+ if (!targets.length) return false;
734
+
735
+ const spans = [];
736
+ for (const t of targets) {
737
+ const r = document.createRange();
738
+ r.setStart(t.node, t.start);
739
+ r.setEnd(t.node, t.end);
740
+ const span = document.createElement('span');
741
+ Object.assign(span.style, styles);
742
+ span.appendChild(r.extractContents());
743
+ r.insertNode(span);
744
+ spans.push(span);
745
+ }
746
+ if (spans.length) {
747
+ const sel = window.getSelection();
748
+ const after = document.createRange();
749
+ after.setStartBefore(spans[0]);
750
+ after.setEndAfter(spans[spans.length - 1]);
751
+ sel?.removeAllRanges();
752
+ sel?.addRange(after);
753
+ editing.range = after.cloneRange();
754
+ }
755
+ this.app.syncEditing();
756
+ return true;
757
+ }
758
+ }
759
+
760
+ function nearest(values, target, threshold) {
761
+ let best = null;
762
+ for (const v of values) {
763
+ if (Math.abs(v - target) <= threshold && (best === null || Math.abs(v - target) < Math.abs(best - target))) best = v;
764
+ }
765
+ return best;
766
+ }
767
+
768
+ // 供外部布局计算使用(保持与渲染层同口径)
769
+ export const canvasDefaults = { minSize: MIN_SIZE, snap: SNAP_PX, width: SLIDE_W, height: SLIDE_H };