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