gbpptx 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,247 +1,557 @@
1
- // [文件] gbpptx·画布 —— 交互式编辑面(选中/拖动/缩放/旋转/双击改文字与表格/空白处取消选择)
2
- import { SLIDE_H, SLIDE_W, objectBoxStyle, objectRect } from '../../../src/kernel/model.js';
1
+ // [文件] gbpptx·画布 —— Office 式编辑面(多选/框选/吸附/组缩放/旋转/就地文本与表格编辑/缩放)
2
+
3
+ import { SLIDE_H, SLIDE_W, objectBoxStyle, objectRect, unionRect } from '../../../src/kernel/model.js';
3
4
  import { renderPage } from './page-view.js';
5
+ import { animateSlideFrame } from './transition.js';
4
6
 
5
7
  const MIN_SIZE = 8;
6
- const ROT_HANDLE_DIST = 26;
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, '\\$&'));
7
12
 
8
13
  export class Canvas {
9
14
  constructor(app) {
10
15
  this.app = app;
11
16
  this.el = document.createElement('div');
12
- this.el.className = 'sl-stage-wrap';
13
- this.stage = document.createElement('div');
14
- this.stage.className = 'sl-stage';
17
+ this.el.className = 'pp-canvas';
18
+ this.scroll = document.createElement('div');
19
+ this.scroll.className = 'pp-canvas__scroll';
15
20
  this.holder = document.createElement('div');
16
- this.holder.className = 'sl-canvas-holder';
21
+ this.holder.className = 'pp-canvas__holder';
17
22
  this.inner = document.createElement('div');
18
- this.inner.style.cssText = `position:relative;width:${SLIDE_W}px;height:${SLIDE_H}px;transform-origin:0 0`;
23
+ this.inner.className = 'pp-canvas__inner';
19
24
  this.holder.appendChild(this.inner);
20
- this.stage.appendChild(this.holder);
21
- this.el.appendChild(this.stage);
25
+ this.scroll.appendChild(this.holder);
26
+ this.el.appendChild(this.scroll);
27
+
22
28
  this.sel = document.createElement('div');
23
- this.sel.className = 'sl-sel';
29
+ this.sel.className = 'pp-sel';
24
30
  this.sel.hidden = true;
25
- this.buildSelHandles();
26
- this.bindStage();
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();
27
40
  }
28
41
 
29
42
  get scale() {
30
43
  return this.app.zoom / 100;
31
44
  }
32
45
 
33
- buildSelHandles() {
34
- for (const dir of ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']) {
35
- const h = document.createElement('span');
36
- h.className = 'sl-sel__handle';
37
- h.dataset.dir = dir;
38
- h.addEventListener('mousedown', (e) => this.startResize(dir, e));
39
- this.sel.appendChild(h);
40
- }
41
- const rot = document.createElement('span');
42
- rot.className = 'sl-sel__rotate';
43
- rot.title = '旋转';
44
- rot.addEventListener('mousedown', (e) => this.startRotate(e));
45
- this.sel.appendChild(rot);
46
+ get size() {
47
+ return this.app.size;
46
48
  }
47
49
 
50
+ /* ===================== 渲染 ===================== */
51
+
48
52
  render() {
49
53
  const app = this.app;
50
54
  const slide = app.currentSlide();
51
- const scale = this.scale;
52
- this.inner.replaceChildren();
53
- const page = renderPage(slide, app.snapshot.theme, { interactive: true });
55
+ const page = renderPage(slide, app.snapshot.theme, { interactive: true, size: this.size });
54
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);
55
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);
56
71
  this.inner.appendChild(this.sel);
57
- this.inner.style.transform = `scale(${scale})`;
58
- this.holder.style.width = `${SLIDE_W * scale}px`;
59
- this.holder.style.height = `${SLIDE_H * scale}px`;
72
+ this.guides.replaceChildren();
73
+ this.applyScale();
60
74
  page.querySelectorAll('[data-obj-id]').forEach((el) => {
61
- el.addEventListener('mousedown', (e) => this.startDrag(el.dataset.objId, e));
62
- el.addEventListener('dblclick', (e) => this.startEdit(e, el.dataset.objId));
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
+ }
63
81
  });
64
82
  this.syncSelection();
65
83
  }
66
84
 
67
- /** 选中框定位(单选显示手柄;多选只画并集框) */
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
+ /** 选中框定位(单选显示手柄 + 旋转;多选显示并集框与组缩放) */
68
118
  syncSelection() {
69
119
  const app = this.app;
70
120
  const ids = app.selectedIds;
71
- if (!ids.length) {
72
- this.sel.hidden = true;
73
- return;
74
- }
75
121
  const objs = app.currentSlide().objects.filter((o) => ids.includes(o.id));
76
122
  if (!objs.length) {
77
123
  this.sel.hidden = true;
78
124
  return;
79
125
  }
80
- const rects = objs.map(objectRect);
81
- const left = Math.min(...rects.map((r) => r.left));
82
- const top = Math.min(...rects.map((r) => r.top));
83
- const right = Math.max(...rects.map((r) => r.left + r.width));
84
- const bottom = Math.max(...rects.map((r) => r.top + r.height));
126
+ const rect = unionRect(objs);
127
+ const w = Math.max(1, rect.width);
128
+ const h = Math.max(1, rect.height);
85
129
  this.sel.hidden = false;
86
- Object.assign(this.sel.style, {
87
- left: `${left}px`, top: `${top}px`, width: `${right - left}px`, height: `${bottom - top}px`,
88
- });
130
+ Object.assign(this.sel.style, { left: `${rect.left}px`, top: `${rect.top}px`, width: `${w}px`, height: `${h}px` });
89
131
  const single = objs.length === 1;
90
- for (const h of this.sel.querySelectorAll('.sl-sel__handle, .sl-sel__rotate')) h.hidden = !single;
91
- if (single && objs[0].rot) this.sel.style.transform = `rotate(${objs[0].rot}deg)`;
92
- else this.sel.style.transform = '';
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);
93
161
  }
94
162
 
95
- bindStage() {
96
- this.stage.addEventListener('mousedown', (e) => {
97
- if (e.target === this.stage || e.target === this.holder) this.app.clearSelection();
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);
98
196
  });
99
- this.stage.addEventListener('scroll', () => this.syncSelection());
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);
100
205
  }
101
206
 
102
207
  /** 客户端坐标 → 页面逻辑坐标 */
103
208
  toPage(e) {
104
- const r = this.inner.getBoundingClientRect();
209
+ const rect = this.inner.getBoundingClientRect();
105
210
  const z = this.scale || 1;
106
- return { x: (e.clientX - r.left) / z, y: (e.clientY - r.top) / z };
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);
107
226
  }
108
227
 
228
+ /* ===================== 拖动 ===================== */
229
+
109
230
  startDrag(id, e) {
110
- if (e.button !== 0) return;
111
231
  const app = this.app;
112
232
  const additive = e.shiftKey || e.ctrlKey || e.metaKey;
113
- if (additive) app.toggleSelect(id);
114
- else if (!app.selectedIds.includes(id)) app.selectObjects([id]);
115
- if (e.target.closest('.sl-sel__handle, .sl-sel__rotate')) return;
116
- if (app.selectedIds.length !== 1) return;
117
- e.preventDefault();
118
- e.stopPropagation();
119
- const obj = app.selectedById(id);
120
- const start = this.toPage(e);
121
- const origin = { x: obj.x, y: obj.y };
122
- const el = this.page.querySelector(`[data-obj-id="${id}"]`);
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;
123
244
  const move = (ev) => {
124
245
  const p = this.toPage(ev);
125
- obj.x = Math.round(origin.x + (p.x - start.x));
126
- obj.y = Math.round(origin.y + (p.y - start.y));
127
- Object.assign(el.style, objectBoxStyle(obj));
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
+ }
128
267
  this.syncSelection();
268
+ app.updateGestureStatus?.();
129
269
  };
130
270
  const up = () => {
131
271
  document.removeEventListener('mousemove', move);
132
272
  document.removeEventListener('mouseup', up);
133
- app.notifyChange();
273
+ this.clearGuides();
274
+ if (moved) app.notifyChange();
275
+ else if (begun) app.renderAll();
134
276
  };
135
277
  document.addEventListener('mousemove', move);
136
278
  document.addEventListener('mouseup', up);
137
279
  }
138
280
 
281
+ /* ===================== 缩放 ===================== */
282
+
139
283
  startResize(dir, e) {
140
284
  e.preventDefault();
141
285
  e.stopPropagation();
142
286
  const app = this.app;
143
- const obj = app.firstSelected();
144
- if (!obj) return;
145
- const start = this.toPage(e);
146
- const o = { x: obj.x, y: obj.y, w: obj.w, h: obj.h };
147
- const el = this.page.querySelector(`[data-obj-id="${obj.id}"]`);
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;
148
296
  const move = (ev) => {
149
297
  const p = this.toPage(ev);
150
- const dx = p.x - start.x;
151
- const dy = p.y - start.y;
152
- let { x, y, w, h } = o;
153
- if (dir.includes('e')) w = o.w + dx;
154
- if (dir.includes('s')) h = o.h + dy;
155
- if (dir.includes('w')) { w = o.w - dx; x = o.x + dx; }
156
- if (dir.includes('n')) { h = o.h - dy; y = o.y + dy; }
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:保持原比例
157
313
  if (ev.shiftKey && dir.length === 2) {
158
- const ratio = Math.abs(o.w / (o.h || 1));
159
- h = Math.sign(h) * Math.abs(w / ratio);
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);
160
348
  }
161
- obj.x = Math.round(x); obj.y = Math.round(y);
162
- obj.w = Math.round(Math.abs(w) < MIN_SIZE ? Math.sign(w || 1) * MIN_SIZE : w);
163
- obj.h = Math.round(Math.abs(h) < MIN_SIZE ? Math.sign(h || 1) * MIN_SIZE : h);
164
- Object.assign(el.style, objectBoxStyle(obj));
165
349
  this.syncSelection();
350
+ app.updateGestureStatus?.();
166
351
  };
167
352
  const up = () => {
168
353
  document.removeEventListener('mousemove', move);
169
354
  document.removeEventListener('mouseup', up);
170
- app.notifyChange();
355
+ this.clearGuides();
356
+ if (moved) app.notifyChange();
171
357
  };
172
358
  document.addEventListener('mousemove', move);
173
359
  document.addEventListener('mouseup', up);
174
360
  }
175
361
 
362
+ /* ===================== 旋转 ===================== */
363
+
176
364
  startRotate(e) {
177
365
  e.preventDefault();
178
366
  e.stopPropagation();
179
367
  const app = this.app;
180
368
  const obj = app.firstSelected();
181
369
  if (!obj) return;
182
- const r = this.inner.getBoundingClientRect();
183
- const z = this.scale || 1;
184
- const cx = r.left + (objectRect(obj).left + objectRect(obj).width / 2) * z;
185
- const cy = r.top + (objectRect(obj).top + objectRect(obj).height / 2) * z;
186
- const el = this.page.querySelector(`[data-obj-id="${obj.id}"]`);
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;
187
378
  const move = (ev) => {
188
- const ang = (Math.atan2(ev.clientY - cy, ev.clientX - cx) * 180) / Math.PI + 90;
189
- obj.rot = Math.round(ang);
190
- Object.assign(el.style, objectBoxStyle(obj));
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);
191
385
  this.syncSelection();
386
+ app.updateGestureStatus?.();
192
387
  };
193
388
  const up = () => {
194
389
  document.removeEventListener('mousemove', move);
195
390
  document.removeEventListener('mouseup', up);
196
- app.notifyChange();
391
+ if (moved) app.notifyChange();
197
392
  };
198
393
  document.addEventListener('mousemove', move);
199
394
  document.addEventListener('mouseup', up);
200
395
  }
201
396
 
202
- /** 双击:文本框/图形内文字就地编辑;表格单元格就地编辑 */
203
- startEdit(e, id) {
204
- e.preventDefault();
205
- e.stopPropagation();
397
+ /* ===================== 框选 ===================== */
398
+
399
+ startMarquee(e) {
206
400
  const app = this.app;
207
- const obj = app.selectedById(id);
208
- if (!obj) return;
209
- const el = this.page.querySelector(`[data-obj-id="${id}"]`);
210
- if (obj.type === 'table') {
211
- const td = e.target.closest('td');
212
- if (!td) return;
213
- this.editCell(obj, el, td);
214
- return;
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
+ }
215
461
  }
216
- if (obj.type === 'text') {
217
- this.editText(obj, el.querySelector('.sl-text'), el);
218
- } else if (obj.type === 'shape') {
219
- this.editText(obj, el.querySelector('.sl-shape-text'), el, 'shape');
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
+ }
220
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 };
221
472
  }
222
473
 
223
- editText(obj, node, el, kind = 'text') {
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');
224
525
  if (!node) return;
225
- const app = this.app;
526
+ if (this.app.editing) this.app.commitEditing({ render: false });
226
527
  el.classList.add('is-editing');
528
+ el.querySelector('.pp-empty-hint')?.remove();
529
+ const placeholder = obj.type === 'text' && !(node.textContent || '').trim();
227
530
  node.contentEditable = 'true';
228
- node.focus();
229
- const sel = window.getSelection();
230
- const range = document.createRange();
231
- range.selectNodeContents(node);
232
- range.collapse(false);
233
- sel?.removeAllRanges();
234
- sel?.addRange(range);
235
- const commit = () => {
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);
236
551
  node.contentEditable = 'false';
237
552
  el.classList.remove('is-editing');
238
- node.removeEventListener('blur', commit);
239
- node.removeEventListener('keydown', onKey);
240
- if (kind === 'shape') {
241
- app.updateProps(obj.id, { text: node.innerText.replace(/\n+$/, '') });
242
- } else {
243
- app.updateProps(obj.id, { html: node.innerHTML });
244
- }
553
+ // 不用立刻整页重绘:否则点缩略图时 DOM 被替换,click 会丢;下一次结构变化再渲染
554
+ this.app.commitEditing({ node, render: false });
245
555
  };
246
556
  const onKey = (ev) => {
247
557
  if (ev.key === 'Escape') {
@@ -249,29 +559,197 @@ export class Canvas {
249
559
  node.blur();
250
560
  }
251
561
  };
252
- node.addEventListener('blur', commit);
562
+ node.addEventListener('input', onInput);
563
+ node.addEventListener('blur', onBlur);
253
564
  node.addEventListener('keydown', onKey);
254
565
  }
255
566
 
256
- editCell(obj, el, td) {
257
- const app = this.app;
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 });
258
587
  const tr = td.parentElement;
259
- const ri = Array.from(tr.parentElement.children).indexOf(tr);
588
+ const tbody = tr.parentElement;
589
+ const ri = Array.from(tbody.children).indexOf(tr);
260
590
  const ci = Array.from(tr.children).indexOf(td);
261
591
  td.contentEditable = 'true';
262
- td.focus();
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
+
263
602
  const commit = () => {
264
603
  td.contentEditable = 'false';
265
604
  td.removeEventListener('blur', commit);
266
605
  td.removeEventListener('keydown', onKey);
267
- const rows = obj.props.rows.map((row) => [...row]);
268
- rows[ri][ci] = td.innerText.replace(/\n+$/, '');
269
- app.updateProps(obj.id, { rows });
606
+ td.removeEventListener('input', onInput);
607
+ this.app.commitEditing({ node: td, render: false });
270
608
  };
609
+ const onInput = () => this.app.syncEditing();
271
610
  const onKey = (ev) => {
272
- if (ev.key === 'Escape') { ev.preventDefault(); td.blur(); }
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
+ }
273
635
  };
636
+ td.addEventListener('input', onInput);
274
637
  td.addEventListener('blur', commit);
275
638
  td.addEventListener('keydown', onKey);
276
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
+ }
277
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 };