@a200888213/gbdocx 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 (74) hide show
  1. package/package.json +1 -1
  2. package/src/app/file-io.js +122 -122
  3. package/src/app/main.js +9 -9
  4. package/src/app/word/catalog.js +52 -52
  5. package/src/app/word/comments.js +112 -112
  6. package/src/app/word/doc.js +113 -113
  7. package/src/app/word/edit.js +72 -72
  8. package/src/app/word/hf.js +76 -76
  9. package/src/app/word/layout.js +155 -155
  10. package/src/app/word/notes.js +110 -110
  11. package/src/app/word/shared.js +22 -22
  12. package/src/app/word-sheets.js +101 -101
  13. package/src/kernel/docx/codec/blocks.js +123 -123
  14. package/src/kernel/docx/codec/carry.js +129 -129
  15. package/src/kernel/docx/codec/comments.js +25 -25
  16. package/src/kernel/docx/codec/docx.js +198 -198
  17. package/src/kernel/docx/codec/docxStyles.js +177 -177
  18. package/src/kernel/docx/codec/fonts.js +195 -195
  19. package/src/kernel/docx/codec/helpers.js +161 -161
  20. package/src/kernel/docx/codec/hfHtml.js +152 -152
  21. package/src/kernel/docx/codec/html.js +739 -739
  22. package/src/kernel/docx/codec/losses.js +420 -420
  23. package/src/kernel/docx/codec/markdown.js +170 -170
  24. package/src/kernel/docx/codec/parts.js +249 -249
  25. package/src/kernel/docx/codec/read.js +603 -603
  26. package/src/kernel/docx/codec/render.js +1156 -1156
  27. package/src/kernel/docx/codec/roundtrip.js +236 -236
  28. package/src/kernel/docx/codec/write.js +833 -833
  29. package/src/kernel/docx/comments.js +14 -14
  30. package/src/kernel/docx/pageGeometry.js +123 -123
  31. package/src/kernel/docx/pagination.js +481 -481
  32. package/src/kernel/docx/watermark.js +45 -45
  33. package/src/kernel/editor/constants.js +8 -8
  34. package/src/kernel/editor/engine/blocks.js +594 -594
  35. package/src/kernel/editor/engine/blocksEnter.js +109 -109
  36. package/src/kernel/editor/engine/blocksInsert.js +254 -254
  37. package/src/kernel/editor/engine/blocksStructure.js +226 -226
  38. package/src/kernel/editor/engine/commands.js +181 -181
  39. package/src/kernel/editor/engine/dom.js +646 -646
  40. package/src/kernel/editor/engine/history.js +149 -149
  41. package/src/kernel/editor/engine/inline.js +656 -656
  42. package/src/kernel/editor/engine/input.js +554 -554
  43. package/src/kernel/editor/engine/interaction.js +137 -137
  44. package/src/kernel/editor/engine/pointer.js +39 -39
  45. package/src/kernel/editor/engine/revision.js +138 -138
  46. package/src/kernel/editor/engine/schema.js +417 -417
  47. package/src/kernel/editor/engine/selection.js +119 -119
  48. package/src/kernel/editor/engine/state.js +118 -118
  49. package/src/kernel/editor/engine/tableClip.js +154 -154
  50. package/src/kernel/editor/engine/tableGrid.js +55 -55
  51. package/src/kernel/editor/engine/tableInteraction.js +388 -388
  52. package/src/kernel/editor/engine/tableMenu.js +250 -250
  53. package/src/kernel/editor/engine/tableOps.js +174 -174
  54. package/src/kernel/editor/engine/tables.js +732 -732
  55. package/src/kernel/editor/overlayGeometry.js +20 -20
  56. package/src/kernel/editor/utils.js +48 -48
  57. package/src/kernel/keyboard.js +114 -114
  58. package/src/kernel/textStyles.js +84 -84
  59. package/src/kernel/util/imageFile.js +91 -91
  60. package/src/kernel/util/shortcutKey.js +33 -33
  61. package/src/surface/editor-surface.js +600 -600
  62. package/src/ui/color-panel.js +69 -69
  63. package/src/ui/context-menu.js +133 -133
  64. package/src/ui/find-bar.js +151 -151
  65. package/src/ui/menubar.js +28 -28
  66. package/src/ui/panels.js +115 -115
  67. package/src/ui/prompt.js +89 -89
  68. package/src/ui/ribbon.js +485 -485
  69. package/src/ui/special-chars.js +39 -39
  70. package/src/ui/statusbar.js +81 -81
  71. package/src/ui/toolbar.js +32 -32
  72. package/styles/editor-content.css +440 -440
  73. package/styles/tokens.css +154 -154
  74. package/styles/word-panel.css +1 -1
@@ -1,600 +1,600 @@
1
- // [文件] gbdocx·EditorSurface —— 富文本内核宿主(移植自 guabi EditorSurface.vue):挂载内核 / 防抖上报 / 表格浮件层 / 框选 / 图片缩放与放大 / 留白落点
2
- // 说明:Vue 槽位改回调装配(backdrop 由宿主填充),其余行为与 guabi 版逐条对齐。
3
-
4
- import { EditorCore } from '../kernel/editor/engine/editor.js';
5
- import { isRuntimeBlock } from '../kernel/editor/engine/dom.js';
6
- import { overlayOrigin, PROBE_WIDTH } from '../kernel/editor/overlayGeometry.js';
7
-
8
- /** 内容上报防抖(ms):按键只置脏,序列化交给拖尾防抖;失焦与卸载立即落地 */
9
- const EMIT_DEBOUNCE = 250;
10
- /** 桌面式框选升级阈值(px) */
11
- const MARQUEE_THRESHOLD = 4;
12
- const MIN_IMAGE_WIDTH = 60;
13
- const MIN_IMAGE_HEIGHT = 40;
14
- const RESIZE_DIRECTIONS = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
15
- /** 表格移动手柄尺寸(px)与距表左沿的间隙:落在纸的左边距里(Word 口径) */
16
- const TABLE_MOVE_W = 14;
17
- const TABLE_MOVE_H = 20;
18
- const TABLE_MOVE_GAP = 6;
19
- /** 拖表起手阈值(px):位移不足按单击处理(单击=选中整张表) */
20
- const TABLE_MOVE_THRESHOLD = 4;
21
- /** 分页运行期栏容器类名(与 pagination.js 同契约):落点要穿透到栏内正文块 */
22
- const COL_CLASS = 'wd-col';
23
- const ZOOM_ICON = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3M11 8v6M8 11h6"/></svg>';
24
- const MOVE_ICON = '<svg viewBox="0 0 10 18" width="10" height="18" fill="currentColor" aria-hidden="true"><circle cx="2.6" cy="4" r="1.25"/><circle cx="7.4" cy="4" r="1.25"/><circle cx="2.6" cy="9" r="1.25"/><circle cx="7.4" cy="9" r="1.25"/><circle cx="2.6" cy="14" r="1.25"/><circle cx="7.4" cy="14" r="1.25"/></svg>';
25
-
26
- export class EditorSurface {
27
- /**
28
- * @param {object} opts
29
- * @param {HTMLElement} opts.mount 挂载容器
30
- * @param {string} [opts.modelValue] 初始 HTML
31
- * @param {string} [opts.placeholder]
32
- * @param {boolean} [opts.editable=true]
33
- * @param {object} [opts.handlers] 额外内核事件处理器(与内置 update/blur/atom 合并)
34
- * @param {(host: HTMLElement) => void} [opts.backdrop] 背景层渲染(Word 纸面层填充);返回后由宿主 refreshBackdrop 触发
35
- */
36
- constructor(opts) {
37
- this.opts = opts;
38
- this.handlers = opts.handlers || {};
39
- this.editable = opts.editable !== false;
40
- this.backdropRender = opts.backdrop || null;
41
- this.lastEmittedHtml = '';
42
- this.emitTimer = 0;
43
- this.emitPending = false;
44
- this.build();
45
- this.createEditor(opts.modelValue || '');
46
- }
47
-
48
- /* ===================== DOM 装配 ===================== */
49
-
50
- build() {
51
- const root = document.createElement('div');
52
- root.className = 'rich-edit-surface gbd-is-fill';
53
- root.innerHTML = `
54
- <div class="re-scroll dt-scrollbar-thin">
55
- <div class="re-backdrop-host"></div>
56
- <span class="re-overlay-probe" aria-hidden="true"></span>
57
- <div class="re-content rich-text-content"></div>
58
- <div class="re-table-layer">
59
- <span class="re-table-select" hidden></span>
60
- <div class="re-table-handles" hidden>
61
- <button type="button" class="re-table-move" aria-label="拖动表格" title="拖动表格">${MOVE_ICON}</button>
62
- <button type="button" class="re-table-handle gbd-is-column" aria-label="在右侧插入一列">+</button>
63
- <button type="button" class="re-table-handle gbd-is-row" aria-label="在下方插入一行">+</button>
64
- </div>
65
- <span class="re-drop-line" hidden></span>
66
- <span class="re-col-line" hidden></span>
67
- </div>
68
- <div class="re-marquee" hidden></div>
69
- <div class="re-resize-box" hidden>
70
- <button type="button" class="re-zoom-btn" title="放大预览" aria-label="放大预览这张图片">${ZOOM_ICON}</button>
71
- ${RESIZE_DIRECTIONS.map((d) => `<span class="re-resize-handle gbd-is-${d}" data-dir="${d}"></span>`).join('')}
72
- </div>
73
- </div>
74
- <div class="re-image-viewer" hidden>
75
- <img alt="" />
76
- </div>`;
77
- this.el = root;
78
- this.scrollEl = root.querySelector('.re-scroll');
79
- this.backdropHost = root.querySelector('.re-backdrop-host');
80
- this.probeEl = root.querySelector('.re-overlay-probe');
81
- this.probeEl.style.width = `${PROBE_WIDTH}px`;
82
- this.contentEl = root.querySelector('.re-content');
83
- this.tableLayer = root.querySelector('.re-table-layer');
84
- this.selectBoxEl = root.querySelector('.re-table-select');
85
- this.handlesEl = root.querySelector('.re-table-handles');
86
- this.moveHandleEl = root.querySelector('.re-table-move');
87
- this.dropLineEl = root.querySelector('.re-drop-line');
88
- this.colLineEl = root.querySelector('.re-col-line');
89
- this.marqueeEl = root.querySelector('.re-marquee');
90
- this.resizeBoxEl = root.querySelector('.re-resize-box');
91
- this.viewerEl = root.querySelector('.re-image-viewer');
92
- this.opts.mount.appendChild(root);
93
- this.bindSurface();
94
- this.lastEmittedHtml = '';
95
- }
96
-
97
- /* ===================== 内核装配 ===================== */
98
-
99
- createEditor(modelValue) {
100
- const extra = this.handlers;
101
- const ed = new EditorCore({
102
- root: this.contentEl,
103
- placeholder: this.opts.placeholder || '',
104
- handlers: {
105
- ...extra,
106
- update: () => {
107
- this.scheduleEmit();
108
- this.scheduleOverlayUpdate();
109
- extra.update?.();
110
- },
111
- blur: () => {
112
- this.flushEmit();
113
- extra.blur?.();
114
- },
115
- atom: (el) => {
116
- this.selectedImage = el && el.tagName === 'IMG' ? el : null;
117
- this.scheduleOverlayUpdate();
118
- extra.atom?.(el);
119
- },
120
- },
121
- });
122
- ed.mount(modelValue);
123
- ed.setEditable(this.editable);
124
- this.editor = ed;
125
- this.lastEmittedHtml = ed.getHTML();
126
- ed.on('column-hover', () => this.refreshColLine());
127
- ed.on('cell-selection', () => this.refreshSelectBox());
128
- }
129
-
130
- /* ===================== 上报(防抖) ===================== */
131
-
132
- flushEmit() {
133
- if (this.emitTimer) {
134
- clearTimeout(this.emitTimer);
135
- this.emitTimer = 0;
136
- }
137
- if (!this.emitPending) return;
138
- this.emitPending = false;
139
- const ed = this.editor;
140
- if (!ed || ed.destroyed) return;
141
- this.lastEmittedHtml = ed.getHTML();
142
- }
143
-
144
- scheduleEmit() {
145
- this.emitPending = true;
146
- if (this.emitTimer) return;
147
- this.emitTimer = setTimeout(() => this.flushEmit(), EMIT_DEBOUNCE);
148
- }
149
-
150
- /** 落地并现读当前 HTML(外部提交前必须走这里,v-model 落后真实输入 ≤250ms) */
151
- flush() {
152
- this.flushEmit();
153
- return this.editor && !this.editor.destroyed ? this.editor.getHTML() : null;
154
- }
155
-
156
- /** 外部装载(换文档):直接 setHTML 并重置基线 */
157
- setHTML(html) {
158
- const ed = this.editor;
159
- if (!ed || ed.destroyed) return;
160
- if (html === ed.getHTML()) return;
161
- if (this.emitTimer) {
162
- clearTimeout(this.emitTimer);
163
- this.emitTimer = 0;
164
- }
165
- this.emitPending = false;
166
- ed.setHTML(html || '');
167
- this.lastEmittedHtml = ed.getHTML();
168
- }
169
-
170
- /* ===================== 编辑性 / 建议模式 ===================== */
171
-
172
- setEditable(on) {
173
- this.editable = !!on;
174
- this.editor?.setEditable(this.editable);
175
- if (!on) this.hideTableHandles();
176
- }
177
-
178
- setSuggesting(on) {
179
- this.editor?.setSuggesting(!!on);
180
- }
181
-
182
- insertImages(files) {
183
- return this.editor?.insertImageFiles(files);
184
- }
185
-
186
- /** 背景层(Word 纸面)重绘入口:分页/页数变化后调用 */
187
- refreshBackdrop() {
188
- if (this.backdropRender) this.backdropRender(this.backdropHost);
189
- }
190
-
191
- focus() {
192
- this.editor?.focus();
193
- }
194
-
195
- destroy() {
196
- this.flushEmit();
197
- this._resizeCleanup?.();
198
- this._tableMoveCleanup?.();
199
- this.editor?.destroy();
200
- this.editor = null;
201
- if (this.resizeRaf) cancelAnimationFrame(this.resizeRaf);
202
- document.removeEventListener('mousemove', this._mqMove);
203
- document.removeEventListener('mouseup', this._mqUp);
204
- this.el.remove();
205
- }
206
-
207
- /* ===================== 浮件坐标更新 ===================== */
208
-
209
- scheduleOverlayUpdate() {
210
- if (this.resizeRaf) return;
211
- this.resizeRaf = requestAnimationFrame(() => {
212
- this.resizeRaf = 0;
213
- this.updateResizeBox();
214
- if (this.hoveredTable) this.refreshTableHandles();
215
- this.refreshColLine();
216
- this.refreshSelectBox();
217
- });
218
- }
219
-
220
- /** 图片缩放浮层(选中图片时显示) */
221
- updateResizeBox() {
222
- const img = this.selectedImage;
223
- if (!img || !img.isConnected || !this.editable) {
224
- this.resizeBoxEl.hidden = true;
225
- return;
226
- }
227
- const base = overlayOrigin(this.probeEl);
228
- const rect = img.getBoundingClientRect();
229
- const box = {
230
- left: (rect.left - base.x) / base.z,
231
- top: (rect.top - base.y) / base.z,
232
- width: rect.width / base.z,
233
- height: rect.height / base.z,
234
- };
235
- this.resizeBoxEl.hidden = false;
236
- Object.assign(this.resizeBoxEl.style, {
237
- left: `${box.left}px`,
238
- top: `${box.top}px`,
239
- width: `${box.width}px`,
240
- height: `${box.height}px`,
241
- });
242
- }
243
-
244
- refreshTableHandles() {
245
- const table = this.hoveredTable;
246
- if (!table || !table.isConnected) {
247
- this.handlesEl.hidden = true;
248
- return;
249
- }
250
- const base = overlayOrigin(this.probeEl);
251
- const rect = table.getBoundingClientRect();
252
- const left = (rect.left - base.x) / base.z;
253
- const top = (rect.top - base.y) / base.z;
254
- const width = rect.width / base.z;
255
- const height = rect.height / base.z;
256
- const col = this.handlesEl.querySelector('.gbd-is-column');
257
- const row = this.handlesEl.querySelector('.gbd-is-row');
258
- Object.assign(col.style, { left: `${Math.round(left + width)}px`, top: `${Math.round(top)}px`, height: `${Math.round(height)}px` });
259
- Object.assign(row.style, { left: `${Math.round(left)}px`, top: `${Math.round(top + height)}px`, width: `${Math.round(width)}px` });
260
- // 移动手柄:贴表左上角、纵向对齐首行中线(表恰在版心首行时手柄自然落进纸的左边距)
261
- const rowH = (table.rows?.[0]?.getBoundingClientRect().height || 0) / base.z;
262
- Object.assign(this.moveHandleEl.style, {
263
- left: `${Math.round(left - TABLE_MOVE_W - TABLE_MOVE_GAP)}px`,
264
- top: `${Math.round(top + Math.max(0, (rowH - TABLE_MOVE_H) / 2))}px`,
265
- });
266
- this.handlesEl.hidden = false;
267
- }
268
-
269
- hideTableHandles() {
270
- this.hoveredTable = null;
271
- this.handlesEl.hidden = true;
272
- }
273
-
274
- refreshColLine() {
275
- const ed = this.editor;
276
- const info = ed && !ed.destroyed ? ed.columnBoundaryBox() : null;
277
- if (!info) {
278
- this.colLineEl.hidden = true;
279
- return;
280
- }
281
- const base = overlayOrigin(this.probeEl);
282
- this.colLineEl.hidden = false;
283
- Object.assign(this.colLineEl.style, {
284
- left: `${Math.round((info.boundaryX - base.x) / base.z)}px`,
285
- top: `${Math.round((info.top - base.y) / base.z)}px`,
286
- height: `${Math.round(info.height / base.z)}px`,
287
- });
288
- }
289
-
290
- refreshSelectBox() {
291
- const ed = this.editor;
292
- const geo = ed && !ed.destroyed ? ed.cellSelectionBox() : null;
293
- if (!geo) {
294
- this.selectBoxEl.hidden = true;
295
- return;
296
- }
297
- const base = overlayOrigin(this.probeEl);
298
- this.selectBoxEl.hidden = false;
299
- Object.assign(this.selectBoxEl.style, {
300
- left: `${Math.round((geo.left - base.x) / base.z)}px`,
301
- top: `${Math.round((geo.top - base.y) / base.z)}px`,
302
- width: `${Math.round(geo.width / base.z)}px`,
303
- height: `${Math.round(geo.height / base.z)}px`,
304
- });
305
- }
306
-
307
- /* ===================== 鼠标交互 ===================== */
308
-
309
- bindSurface() {
310
- const s = this.scrollEl;
311
- s.addEventListener('scroll', () => this.scheduleOverlayUpdate());
312
- s.addEventListener('mousemove', (e) => this.onSurfaceMouseMove(e));
313
- s.addEventListener('mouseleave', () => this.hideTableHandles());
314
- s.addEventListener('mousedown', () => this.onSurfaceMouseDownCapture(), true);
315
- s.addEventListener('mousedown', (e) => this.onBlankMouseDown(e));
316
- s.addEventListener('click', (e) => this.onContentClick(e));
317
- s.addEventListener('dblclick', (e) => this.onContentDblClick(e));
318
- this.resizeBoxEl.querySelector('.re-zoom-btn').addEventListener('mousedown', (e) => e.preventDefault());
319
- this.resizeBoxEl.querySelector('.re-zoom-btn').addEventListener('click', () => this.zoomSelected());
320
- this.resizeBoxEl.querySelectorAll('.re-resize-handle').forEach((h) => {
321
- h.addEventListener('mousedown', (e) => this.startResize(h.dataset.dir, e));
322
- });
323
- this.handlesEl.querySelector('.gbd-is-column').addEventListener('mousedown', (e) => this.startEdgeGesture('column', e));
324
- this.handlesEl.querySelector('.gbd-is-row').addEventListener('mousedown', (e) => this.startEdgeGesture('row', e));
325
- this.moveHandleEl.addEventListener('mousedown', (e) => this.startTableMove(e));
326
- this.viewerEl.addEventListener('click', () => this.closePreview());
327
- }
328
-
329
- onSurfaceMouseMove(event) {
330
- if (!this.editable) return;
331
- // 拖表手势期悬停目标已锁:再按指针重算会让手柄跟着别的表跳
332
- if (this._tableMoveCleanup) return;
333
- const target = event.target;
334
- if (!(target instanceof Element)) return;
335
- if (target.closest('.re-table-handles')) return;
336
- const table = target.closest('table');
337
- if (!table || !this.contentEl.contains(table)) {
338
- if (this.hoveredTable) this.hideTableHandles();
339
- return;
340
- }
341
- this.hoveredTable = table;
342
- this.refreshTableHandles();
343
- }
344
-
345
- startEdgeGesture(axis, event) {
346
- const ed = this.editor;
347
- const table = this.hoveredTable;
348
- if (!ed || !table || !table.isConnected) return;
349
- event.preventDefault();
350
- ed.root.focus({ preventScroll: true });
351
- ed.beginEdgeGesture(event, table, axis);
352
- }
353
-
354
- /**
355
- * 表格移动手柄手势:单击选中整表,拖拽把表搬到落点块前/后
356
- * [设计] 落点按正文块几何现算(不用 elementFromPoint):页间缝、栏容器、浮件都不是合法落点,
357
- * 指针划过页缝时取最近的正文块,落点线不会闪断;跨页续表由内核先并回首块再搬
358
- */
359
- startTableMove(event) {
360
- const ed = this.editor;
361
- const table = this.hoveredTable;
362
- if (!ed || ed.destroyed || !table?.isConnected || !this.editable || event.button !== 0) return;
363
- if (this._tableMoveCleanup) return;
364
- event.preventDefault();
365
- const startX = event.clientX;
366
- const startY = event.clientY;
367
- let dragging = false;
368
- let slot = null;
369
- const cleanup = () => {
370
- this._tableMoveCleanup = null;
371
- document.removeEventListener('mousemove', onMove);
372
- document.removeEventListener('mouseup', onUp);
373
- document.removeEventListener('keydown', onKey, true);
374
- this.el.classList.remove('gbd-is-table-moving');
375
- this.hideDropLine();
376
- };
377
- const onMove = (moveEvent) => {
378
- if (!dragging) {
379
- const moved = Math.abs(moveEvent.clientX - startX) + Math.abs(moveEvent.clientY - startY);
380
- if (moved < TABLE_MOVE_THRESHOLD) return;
381
- dragging = true;
382
- this.el.classList.add('gbd-is-table-moving');
383
- }
384
- slot = this.dropSlot(moveEvent.clientY, table);
385
- this.showDropLine(slot);
386
- };
387
- const onUp = () => {
388
- cleanup();
389
- // 拖到一半切只读 / 卸载:丢弃本次手势,不再落选区或改文档
390
- if (ed.destroyed || !this.editable) return;
391
- if (!dragging) {
392
- ed.selectTable(table);
393
- return;
394
- }
395
- if (slot) ed.exec('moveTableTo', table, slot.ref, slot.before);
396
- // 换位后旧框选(可能落在续表碎片上)与几何对不上:拖完即清,避免覆盖层画到错位置
397
- ed.clearCellSelection();
398
- // 表已换位(或未落点):悬停几何随旧位置作废,等下次移入表格再浮出
399
- this.hideTableHandles();
400
- };
401
- const onKey = (keyEvent) => {
402
- if (keyEvent.key !== 'Escape') return;
403
- keyEvent.preventDefault();
404
- cleanup();
405
- };
406
- this._tableMoveCleanup = cleanup;
407
- document.addEventListener('mousemove', onMove);
408
- document.addEventListener('mouseup', onUp);
409
- document.addEventListener('keydown', onKey, true);
410
- }
411
-
412
- /**
413
- * 拖表落点:指针纵坐标命中的正文块(拖动的表自身与它的祖先块不算)
414
- * @param {number} y 指针视口纵坐标
415
- * @param {HTMLElement} dragged 被拖的表
416
- * @returns {{ref:HTMLElement,before:boolean,rect:DOMRect}|null} 无正文块可落时 null
417
- */
418
- dropSlot(y, dragged) {
419
- const blocks = this.logicalBlocks().filter((el) => el !== dragged && !dragged.contains(el) && !el.contains(dragged));
420
- if (!blocks.length) return null;
421
- let last = null;
422
- for (const el of blocks) {
423
- const rect = el.getBoundingClientRect();
424
- last = { ref: el, rect };
425
- if (y < rect.bottom) return { ref: el, before: y < rect.top + rect.height / 2, rect };
426
- }
427
- return { ref: last.ref, before: false, rect: last.rect };
428
- }
429
-
430
- /** 正文本体块(文档序;穿透分页栏容器,页间缝与续表碎片不算块) */
431
- logicalBlocks() {
432
- const out = [];
433
- const walk = (parent) => {
434
- for (const el of parent.children) {
435
- if (isRuntimeBlock(el)) continue;
436
- if (el.classList.contains(COL_CLASS)) {
437
- walk(el);
438
- continue;
439
- }
440
- out.push(el);
441
- }
442
- };
443
- walk(this.contentEl);
444
- return out;
445
- }
446
-
447
- showDropLine(slot) {
448
- if (!slot) {
449
- this.hideDropLine();
450
- return;
451
- }
452
- const top = slot.before ? slot.rect.top : slot.rect.bottom;
453
- Object.assign(this.dropLineEl.style, toLocalRect({ left: slot.rect.left, top, width: slot.rect.width, height: 2 }, this.probeEl));
454
- this.dropLineEl.hidden = false;
455
- }
456
-
457
- hideDropLine() {
458
- this.dropLineEl.hidden = true;
459
- }
460
-
461
- onBlankMouseDown(event) {
462
- const ed = this.editor;
463
- const root = this.contentEl;
464
- if (event.button !== 0 || !ed || !this.editable) return;
465
- if (event.target.closest?.('.re-table-handles, .re-resize-handle, .re-zoom-btn, .re-table-select, .re-col-line')) return;
466
- if (event.target !== root && root.contains(event.target)) return;
467
- event.preventDefault();
468
- this.mqStart = { x: event.clientX, y: event.clientY };
469
- this.mqDragged = false;
470
- this._mqMove = (e) => this.onMarqueeMove(e);
471
- this._mqUp = () => this.onMarqueeUp();
472
- document.addEventListener('mousemove', this._mqMove);
473
- document.addEventListener('mouseup', this._mqUp);
474
- }
475
-
476
- onMarqueeMove(event) {
477
- if (!this.mqStart) return;
478
- if (!this.mqDragged && Math.abs(event.clientX - this.mqStart.x) + Math.abs(event.clientY - this.mqStart.y) < MARQUEE_THRESHOLD) return;
479
- const ed = this.editor;
480
- if (!ed || ed.destroyed) return;
481
- this.mqDragged = true;
482
- ed.blockMarqueeActive = true;
483
- ed.clearBlockSelection();
484
- const client = rectBetween(this.mqStart, { x: event.clientX, y: event.clientY });
485
- ed.marqueeSelect(client);
486
- this.marqueeEl.hidden = false;
487
- Object.assign(this.marqueeEl.style, toLocalRect(client, this.probeEl));
488
- }
489
-
490
- onMarqueeUp() {
491
- document.removeEventListener('mousemove', this._mqMove);
492
- document.removeEventListener('mouseup', this._mqUp);
493
- const ed = this.editor;
494
- if (!this.mqDragged && ed && !ed.destroyed && this.mqStart) ed.focusAt(this.mqStart.x, this.mqStart.y);
495
- this.marqueeEl.hidden = true;
496
- this.mqStart = null;
497
- this.mqDragged = false;
498
- }
499
-
500
- onSurfaceMouseDownCapture() {
501
- const ed = this.editor;
502
- if (ed && ed.blockMarqueeActive) {
503
- ed.blockMarqueeActive = false;
504
- ed.clearBlockSelection();
505
- }
506
- }
507
-
508
- /* ===================== 图片放大 ===================== */
509
-
510
- onContentClick(event) {
511
- if (this.editable) return;
512
- const img = event.target.closest?.('img');
513
- if (img) this.openPreview(img);
514
- }
515
-
516
- onContentDblClick(event) {
517
- if (!this.editable) return;
518
- const img = event.target.closest?.('img');
519
- if (!img) return;
520
- event.preventDefault();
521
- this.openPreview(img);
522
- }
523
-
524
- zoomSelected() {
525
- if (this.selectedImage) this.openPreview(this.selectedImage);
526
- }
527
-
528
- openPreview(img) {
529
- const viewer = this.viewerEl;
530
- const target = viewer.querySelector('img');
531
- target.src = img.src;
532
- viewer.hidden = false;
533
- }
534
-
535
- closePreview() {
536
- this.viewerEl.hidden = true;
537
- if (this.editable) requestAnimationFrame(() => this.editor?.focus());
538
- }
539
-
540
- startResize(direction, event) {
541
- const img = this.selectedImage;
542
- const ed = this.editor;
543
- if (!img || !ed) return;
544
- event.preventDefault();
545
- const rect = img.getBoundingClientRect();
546
- const ratio = rect.width / Math.max(1, rect.height);
547
- const scale = overlayOrigin(this.probeEl).z;
548
- const start = { x: event.clientX, width: rect.width };
549
- const horizontal = direction.endsWith('left') ? -1 : 1;
550
- let begun = false;
551
- const onMove = (moveEvent) => {
552
- if (!beginEditable()) return;
553
- const width = Math.max(MIN_IMAGE_WIDTH, Math.round((start.width + (moveEvent.clientX - start.x) * horizontal) / scale));
554
- const height = Math.max(MIN_IMAGE_HEIGHT, Math.round(width / ratio));
555
- // [坑] 逐帧 run 会灌满历史栈:拖拽只在首次移动时开一步,后续帧合入同一条撤销记录
556
- ed.run(() => {
557
- img.setAttribute('width', String(width));
558
- img.setAttribute('height', String(height));
559
- }, { coalesce: begun });
560
- begun = true;
561
- this.scheduleOverlayUpdate();
562
- };
563
- const beginEditable = () => {
564
- if (!img.isConnected || ed.destroyed) {
565
- onUp();
566
- return false;
567
- }
568
- return true;
569
- };
570
- const onUp = () => {
571
- this._resizeCleanup = null;
572
- document.removeEventListener('mousemove', onMove);
573
- document.removeEventListener('mouseup', onUp);
574
- };
575
- this._resizeCleanup = onUp;
576
- document.addEventListener('mousemove', onMove);
577
- document.addEventListener('mouseup', onUp);
578
- }
579
- }
580
-
581
- function rectBetween(a, b) {
582
- return {
583
- left: Math.min(a.x, b.x),
584
- top: Math.min(a.y, b.y),
585
- right: Math.max(a.x, b.x),
586
- bottom: Math.max(a.y, b.y),
587
- width: Math.abs(a.x - b.x),
588
- height: Math.abs(a.y - b.y),
589
- };
590
- }
591
-
592
- function toLocalRect(client, probe) {
593
- const base = overlayOrigin(probe);
594
- return {
595
- left: `${(client.left - base.x) / base.z}px`,
596
- top: `${(client.top - base.y) / base.z}px`,
597
- width: `${client.width / base.z}px`,
598
- height: `${client.height / base.z}px`,
599
- };
600
- }
1
+ // [文件] gbdocx·EditorSurface —— 富文本内核宿主(移植自 guabi EditorSurface.vue):挂载内核 / 防抖上报 / 表格浮件层 / 框选 / 图片缩放与放大 / 留白落点
2
+ // 说明:Vue 槽位改回调装配(backdrop 由宿主填充),其余行为与 guabi 版逐条对齐。
3
+
4
+ import { EditorCore } from '../kernel/editor/engine/editor.js';
5
+ import { isRuntimeBlock } from '../kernel/editor/engine/dom.js';
6
+ import { overlayOrigin, PROBE_WIDTH } from '../kernel/editor/overlayGeometry.js';
7
+
8
+ /** 内容上报防抖(ms):按键只置脏,序列化交给拖尾防抖;失焦与卸载立即落地 */
9
+ const EMIT_DEBOUNCE = 250;
10
+ /** 桌面式框选升级阈值(px) */
11
+ const MARQUEE_THRESHOLD = 4;
12
+ const MIN_IMAGE_WIDTH = 60;
13
+ const MIN_IMAGE_HEIGHT = 40;
14
+ const RESIZE_DIRECTIONS = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
15
+ /** 表格移动手柄尺寸(px)与距表左沿的间隙:落在纸的左边距里(Word 口径) */
16
+ const TABLE_MOVE_W = 14;
17
+ const TABLE_MOVE_H = 20;
18
+ const TABLE_MOVE_GAP = 6;
19
+ /** 拖表起手阈值(px):位移不足按单击处理(单击=选中整张表) */
20
+ const TABLE_MOVE_THRESHOLD = 4;
21
+ /** 分页运行期栏容器类名(与 pagination.js 同契约):落点要穿透到栏内正文块 */
22
+ const COL_CLASS = 'wd-col';
23
+ const ZOOM_ICON = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3M11 8v6M8 11h6"/></svg>';
24
+ const MOVE_ICON = '<svg viewBox="0 0 10 18" width="10" height="18" fill="currentColor" aria-hidden="true"><circle cx="2.6" cy="4" r="1.25"/><circle cx="7.4" cy="4" r="1.25"/><circle cx="2.6" cy="9" r="1.25"/><circle cx="7.4" cy="9" r="1.25"/><circle cx="2.6" cy="14" r="1.25"/><circle cx="7.4" cy="14" r="1.25"/></svg>';
25
+
26
+ export class EditorSurface {
27
+ /**
28
+ * @param {object} opts
29
+ * @param {HTMLElement} opts.mount 挂载容器
30
+ * @param {string} [opts.modelValue] 初始 HTML
31
+ * @param {string} [opts.placeholder]
32
+ * @param {boolean} [opts.editable=true]
33
+ * @param {object} [opts.handlers] 额外内核事件处理器(与内置 update/blur/atom 合并)
34
+ * @param {(host: HTMLElement) => void} [opts.backdrop] 背景层渲染(Word 纸面层填充);返回后由宿主 refreshBackdrop 触发
35
+ */
36
+ constructor(opts) {
37
+ this.opts = opts;
38
+ this.handlers = opts.handlers || {};
39
+ this.editable = opts.editable !== false;
40
+ this.backdropRender = opts.backdrop || null;
41
+ this.lastEmittedHtml = '';
42
+ this.emitTimer = 0;
43
+ this.emitPending = false;
44
+ this.build();
45
+ this.createEditor(opts.modelValue || '');
46
+ }
47
+
48
+ /* ===================== DOM 装配 ===================== */
49
+
50
+ build() {
51
+ const root = document.createElement('div');
52
+ root.className = 'rich-edit-surface gbd-is-fill';
53
+ root.innerHTML = `
54
+ <div class="re-scroll dt-scrollbar-thin">
55
+ <div class="re-backdrop-host"></div>
56
+ <span class="re-overlay-probe" aria-hidden="true"></span>
57
+ <div class="re-content rich-text-content"></div>
58
+ <div class="re-table-layer">
59
+ <span class="re-table-select" hidden></span>
60
+ <div class="re-table-handles" hidden>
61
+ <button type="button" class="re-table-move" aria-label="拖动表格" title="拖动表格">${MOVE_ICON}</button>
62
+ <button type="button" class="re-table-handle gbd-is-column" aria-label="在右侧插入一列">+</button>
63
+ <button type="button" class="re-table-handle gbd-is-row" aria-label="在下方插入一行">+</button>
64
+ </div>
65
+ <span class="re-drop-line" hidden></span>
66
+ <span class="re-col-line" hidden></span>
67
+ </div>
68
+ <div class="re-marquee" hidden></div>
69
+ <div class="re-resize-box" hidden>
70
+ <button type="button" class="re-zoom-btn" title="放大预览" aria-label="放大预览这张图片">${ZOOM_ICON}</button>
71
+ ${RESIZE_DIRECTIONS.map((d) => `<span class="re-resize-handle gbd-is-${d}" data-dir="${d}"></span>`).join('')}
72
+ </div>
73
+ </div>
74
+ <div class="re-image-viewer" hidden>
75
+ <img alt="" />
76
+ </div>`;
77
+ this.el = root;
78
+ this.scrollEl = root.querySelector('.re-scroll');
79
+ this.backdropHost = root.querySelector('.re-backdrop-host');
80
+ this.probeEl = root.querySelector('.re-overlay-probe');
81
+ this.probeEl.style.width = `${PROBE_WIDTH}px`;
82
+ this.contentEl = root.querySelector('.re-content');
83
+ this.tableLayer = root.querySelector('.re-table-layer');
84
+ this.selectBoxEl = root.querySelector('.re-table-select');
85
+ this.handlesEl = root.querySelector('.re-table-handles');
86
+ this.moveHandleEl = root.querySelector('.re-table-move');
87
+ this.dropLineEl = root.querySelector('.re-drop-line');
88
+ this.colLineEl = root.querySelector('.re-col-line');
89
+ this.marqueeEl = root.querySelector('.re-marquee');
90
+ this.resizeBoxEl = root.querySelector('.re-resize-box');
91
+ this.viewerEl = root.querySelector('.re-image-viewer');
92
+ this.opts.mount.appendChild(root);
93
+ this.bindSurface();
94
+ this.lastEmittedHtml = '';
95
+ }
96
+
97
+ /* ===================== 内核装配 ===================== */
98
+
99
+ createEditor(modelValue) {
100
+ const extra = this.handlers;
101
+ const ed = new EditorCore({
102
+ root: this.contentEl,
103
+ placeholder: this.opts.placeholder || '',
104
+ handlers: {
105
+ ...extra,
106
+ update: () => {
107
+ this.scheduleEmit();
108
+ this.scheduleOverlayUpdate();
109
+ extra.update?.();
110
+ },
111
+ blur: () => {
112
+ this.flushEmit();
113
+ extra.blur?.();
114
+ },
115
+ atom: (el) => {
116
+ this.selectedImage = el && el.tagName === 'IMG' ? el : null;
117
+ this.scheduleOverlayUpdate();
118
+ extra.atom?.(el);
119
+ },
120
+ },
121
+ });
122
+ ed.mount(modelValue);
123
+ ed.setEditable(this.editable);
124
+ this.editor = ed;
125
+ this.lastEmittedHtml = ed.getHTML();
126
+ ed.on('column-hover', () => this.refreshColLine());
127
+ ed.on('cell-selection', () => this.refreshSelectBox());
128
+ }
129
+
130
+ /* ===================== 上报(防抖) ===================== */
131
+
132
+ flushEmit() {
133
+ if (this.emitTimer) {
134
+ clearTimeout(this.emitTimer);
135
+ this.emitTimer = 0;
136
+ }
137
+ if (!this.emitPending) return;
138
+ this.emitPending = false;
139
+ const ed = this.editor;
140
+ if (!ed || ed.destroyed) return;
141
+ this.lastEmittedHtml = ed.getHTML();
142
+ }
143
+
144
+ scheduleEmit() {
145
+ this.emitPending = true;
146
+ if (this.emitTimer) return;
147
+ this.emitTimer = setTimeout(() => this.flushEmit(), EMIT_DEBOUNCE);
148
+ }
149
+
150
+ /** 落地并现读当前 HTML(外部提交前必须走这里,v-model 落后真实输入 ≤250ms) */
151
+ flush() {
152
+ this.flushEmit();
153
+ return this.editor && !this.editor.destroyed ? this.editor.getHTML() : null;
154
+ }
155
+
156
+ /** 外部装载(换文档):直接 setHTML 并重置基线 */
157
+ setHTML(html) {
158
+ const ed = this.editor;
159
+ if (!ed || ed.destroyed) return;
160
+ if (html === ed.getHTML()) return;
161
+ if (this.emitTimer) {
162
+ clearTimeout(this.emitTimer);
163
+ this.emitTimer = 0;
164
+ }
165
+ this.emitPending = false;
166
+ ed.setHTML(html || '');
167
+ this.lastEmittedHtml = ed.getHTML();
168
+ }
169
+
170
+ /* ===================== 编辑性 / 建议模式 ===================== */
171
+
172
+ setEditable(on) {
173
+ this.editable = !!on;
174
+ this.editor?.setEditable(this.editable);
175
+ if (!on) this.hideTableHandles();
176
+ }
177
+
178
+ setSuggesting(on) {
179
+ this.editor?.setSuggesting(!!on);
180
+ }
181
+
182
+ insertImages(files) {
183
+ return this.editor?.insertImageFiles(files);
184
+ }
185
+
186
+ /** 背景层(Word 纸面)重绘入口:分页/页数变化后调用 */
187
+ refreshBackdrop() {
188
+ if (this.backdropRender) this.backdropRender(this.backdropHost);
189
+ }
190
+
191
+ focus() {
192
+ this.editor?.focus();
193
+ }
194
+
195
+ destroy() {
196
+ this.flushEmit();
197
+ this._resizeCleanup?.();
198
+ this._tableMoveCleanup?.();
199
+ this.editor?.destroy();
200
+ this.editor = null;
201
+ if (this.resizeRaf) cancelAnimationFrame(this.resizeRaf);
202
+ document.removeEventListener('mousemove', this._mqMove);
203
+ document.removeEventListener('mouseup', this._mqUp);
204
+ this.el.remove();
205
+ }
206
+
207
+ /* ===================== 浮件坐标更新 ===================== */
208
+
209
+ scheduleOverlayUpdate() {
210
+ if (this.resizeRaf) return;
211
+ this.resizeRaf = requestAnimationFrame(() => {
212
+ this.resizeRaf = 0;
213
+ this.updateResizeBox();
214
+ if (this.hoveredTable) this.refreshTableHandles();
215
+ this.refreshColLine();
216
+ this.refreshSelectBox();
217
+ });
218
+ }
219
+
220
+ /** 图片缩放浮层(选中图片时显示) */
221
+ updateResizeBox() {
222
+ const img = this.selectedImage;
223
+ if (!img || !img.isConnected || !this.editable) {
224
+ this.resizeBoxEl.hidden = true;
225
+ return;
226
+ }
227
+ const base = overlayOrigin(this.probeEl);
228
+ const rect = img.getBoundingClientRect();
229
+ const box = {
230
+ left: (rect.left - base.x) / base.z,
231
+ top: (rect.top - base.y) / base.z,
232
+ width: rect.width / base.z,
233
+ height: rect.height / base.z,
234
+ };
235
+ this.resizeBoxEl.hidden = false;
236
+ Object.assign(this.resizeBoxEl.style, {
237
+ left: `${box.left}px`,
238
+ top: `${box.top}px`,
239
+ width: `${box.width}px`,
240
+ height: `${box.height}px`,
241
+ });
242
+ }
243
+
244
+ refreshTableHandles() {
245
+ const table = this.hoveredTable;
246
+ if (!table || !table.isConnected) {
247
+ this.handlesEl.hidden = true;
248
+ return;
249
+ }
250
+ const base = overlayOrigin(this.probeEl);
251
+ const rect = table.getBoundingClientRect();
252
+ const left = (rect.left - base.x) / base.z;
253
+ const top = (rect.top - base.y) / base.z;
254
+ const width = rect.width / base.z;
255
+ const height = rect.height / base.z;
256
+ const col = this.handlesEl.querySelector('.gbd-is-column');
257
+ const row = this.handlesEl.querySelector('.gbd-is-row');
258
+ Object.assign(col.style, { left: `${Math.round(left + width)}px`, top: `${Math.round(top)}px`, height: `${Math.round(height)}px` });
259
+ Object.assign(row.style, { left: `${Math.round(left)}px`, top: `${Math.round(top + height)}px`, width: `${Math.round(width)}px` });
260
+ // 移动手柄:贴表左上角、纵向对齐首行中线(表恰在版心首行时手柄自然落进纸的左边距)
261
+ const rowH = (table.rows?.[0]?.getBoundingClientRect().height || 0) / base.z;
262
+ Object.assign(this.moveHandleEl.style, {
263
+ left: `${Math.round(left - TABLE_MOVE_W - TABLE_MOVE_GAP)}px`,
264
+ top: `${Math.round(top + Math.max(0, (rowH - TABLE_MOVE_H) / 2))}px`,
265
+ });
266
+ this.handlesEl.hidden = false;
267
+ }
268
+
269
+ hideTableHandles() {
270
+ this.hoveredTable = null;
271
+ this.handlesEl.hidden = true;
272
+ }
273
+
274
+ refreshColLine() {
275
+ const ed = this.editor;
276
+ const info = ed && !ed.destroyed ? ed.columnBoundaryBox() : null;
277
+ if (!info) {
278
+ this.colLineEl.hidden = true;
279
+ return;
280
+ }
281
+ const base = overlayOrigin(this.probeEl);
282
+ this.colLineEl.hidden = false;
283
+ Object.assign(this.colLineEl.style, {
284
+ left: `${Math.round((info.boundaryX - base.x) / base.z)}px`,
285
+ top: `${Math.round((info.top - base.y) / base.z)}px`,
286
+ height: `${Math.round(info.height / base.z)}px`,
287
+ });
288
+ }
289
+
290
+ refreshSelectBox() {
291
+ const ed = this.editor;
292
+ const geo = ed && !ed.destroyed ? ed.cellSelectionBox() : null;
293
+ if (!geo) {
294
+ this.selectBoxEl.hidden = true;
295
+ return;
296
+ }
297
+ const base = overlayOrigin(this.probeEl);
298
+ this.selectBoxEl.hidden = false;
299
+ Object.assign(this.selectBoxEl.style, {
300
+ left: `${Math.round((geo.left - base.x) / base.z)}px`,
301
+ top: `${Math.round((geo.top - base.y) / base.z)}px`,
302
+ width: `${Math.round(geo.width / base.z)}px`,
303
+ height: `${Math.round(geo.height / base.z)}px`,
304
+ });
305
+ }
306
+
307
+ /* ===================== 鼠标交互 ===================== */
308
+
309
+ bindSurface() {
310
+ const s = this.scrollEl;
311
+ s.addEventListener('scroll', () => this.scheduleOverlayUpdate());
312
+ s.addEventListener('mousemove', (e) => this.onSurfaceMouseMove(e));
313
+ s.addEventListener('mouseleave', () => this.hideTableHandles());
314
+ s.addEventListener('mousedown', () => this.onSurfaceMouseDownCapture(), true);
315
+ s.addEventListener('mousedown', (e) => this.onBlankMouseDown(e));
316
+ s.addEventListener('click', (e) => this.onContentClick(e));
317
+ s.addEventListener('dblclick', (e) => this.onContentDblClick(e));
318
+ this.resizeBoxEl.querySelector('.re-zoom-btn').addEventListener('mousedown', (e) => e.preventDefault());
319
+ this.resizeBoxEl.querySelector('.re-zoom-btn').addEventListener('click', () => this.zoomSelected());
320
+ this.resizeBoxEl.querySelectorAll('.re-resize-handle').forEach((h) => {
321
+ h.addEventListener('mousedown', (e) => this.startResize(h.dataset.dir, e));
322
+ });
323
+ this.handlesEl.querySelector('.gbd-is-column').addEventListener('mousedown', (e) => this.startEdgeGesture('column', e));
324
+ this.handlesEl.querySelector('.gbd-is-row').addEventListener('mousedown', (e) => this.startEdgeGesture('row', e));
325
+ this.moveHandleEl.addEventListener('mousedown', (e) => this.startTableMove(e));
326
+ this.viewerEl.addEventListener('click', () => this.closePreview());
327
+ }
328
+
329
+ onSurfaceMouseMove(event) {
330
+ if (!this.editable) return;
331
+ // 拖表手势期悬停目标已锁:再按指针重算会让手柄跟着别的表跳
332
+ if (this._tableMoveCleanup) return;
333
+ const target = event.target;
334
+ if (!(target instanceof Element)) return;
335
+ if (target.closest('.re-table-handles')) return;
336
+ const table = target.closest('table');
337
+ if (!table || !this.contentEl.contains(table)) {
338
+ if (this.hoveredTable) this.hideTableHandles();
339
+ return;
340
+ }
341
+ this.hoveredTable = table;
342
+ this.refreshTableHandles();
343
+ }
344
+
345
+ startEdgeGesture(axis, event) {
346
+ const ed = this.editor;
347
+ const table = this.hoveredTable;
348
+ if (!ed || !table || !table.isConnected) return;
349
+ event.preventDefault();
350
+ ed.root.focus({ preventScroll: true });
351
+ ed.beginEdgeGesture(event, table, axis);
352
+ }
353
+
354
+ /**
355
+ * 表格移动手柄手势:单击选中整表,拖拽把表搬到落点块前/后
356
+ * [设计] 落点按正文块几何现算(不用 elementFromPoint):页间缝、栏容器、浮件都不是合法落点,
357
+ * 指针划过页缝时取最近的正文块,落点线不会闪断;跨页续表由内核先并回首块再搬
358
+ */
359
+ startTableMove(event) {
360
+ const ed = this.editor;
361
+ const table = this.hoveredTable;
362
+ if (!ed || ed.destroyed || !table?.isConnected || !this.editable || event.button !== 0) return;
363
+ if (this._tableMoveCleanup) return;
364
+ event.preventDefault();
365
+ const startX = event.clientX;
366
+ const startY = event.clientY;
367
+ let dragging = false;
368
+ let slot = null;
369
+ const cleanup = () => {
370
+ this._tableMoveCleanup = null;
371
+ document.removeEventListener('mousemove', onMove);
372
+ document.removeEventListener('mouseup', onUp);
373
+ document.removeEventListener('keydown', onKey, true);
374
+ this.el.classList.remove('gbd-is-table-moving');
375
+ this.hideDropLine();
376
+ };
377
+ const onMove = (moveEvent) => {
378
+ if (!dragging) {
379
+ const moved = Math.abs(moveEvent.clientX - startX) + Math.abs(moveEvent.clientY - startY);
380
+ if (moved < TABLE_MOVE_THRESHOLD) return;
381
+ dragging = true;
382
+ this.el.classList.add('gbd-is-table-moving');
383
+ }
384
+ slot = this.dropSlot(moveEvent.clientY, table);
385
+ this.showDropLine(slot);
386
+ };
387
+ const onUp = () => {
388
+ cleanup();
389
+ // 拖到一半切只读 / 卸载:丢弃本次手势,不再落选区或改文档
390
+ if (ed.destroyed || !this.editable) return;
391
+ if (!dragging) {
392
+ ed.selectTable(table);
393
+ return;
394
+ }
395
+ if (slot) ed.exec('moveTableTo', table, slot.ref, slot.before);
396
+ // 换位后旧框选(可能落在续表碎片上)与几何对不上:拖完即清,避免覆盖层画到错位置
397
+ ed.clearCellSelection();
398
+ // 表已换位(或未落点):悬停几何随旧位置作废,等下次移入表格再浮出
399
+ this.hideTableHandles();
400
+ };
401
+ const onKey = (keyEvent) => {
402
+ if (keyEvent.key !== 'Escape') return;
403
+ keyEvent.preventDefault();
404
+ cleanup();
405
+ };
406
+ this._tableMoveCleanup = cleanup;
407
+ document.addEventListener('mousemove', onMove);
408
+ document.addEventListener('mouseup', onUp);
409
+ document.addEventListener('keydown', onKey, true);
410
+ }
411
+
412
+ /**
413
+ * 拖表落点:指针纵坐标命中的正文块(拖动的表自身与它的祖先块不算)
414
+ * @param {number} y 指针视口纵坐标
415
+ * @param {HTMLElement} dragged 被拖的表
416
+ * @returns {{ref:HTMLElement,before:boolean,rect:DOMRect}|null} 无正文块可落时 null
417
+ */
418
+ dropSlot(y, dragged) {
419
+ const blocks = this.logicalBlocks().filter((el) => el !== dragged && !dragged.contains(el) && !el.contains(dragged));
420
+ if (!blocks.length) return null;
421
+ let last = null;
422
+ for (const el of blocks) {
423
+ const rect = el.getBoundingClientRect();
424
+ last = { ref: el, rect };
425
+ if (y < rect.bottom) return { ref: el, before: y < rect.top + rect.height / 2, rect };
426
+ }
427
+ return { ref: last.ref, before: false, rect: last.rect };
428
+ }
429
+
430
+ /** 正文本体块(文档序;穿透分页栏容器,页间缝与续表碎片不算块) */
431
+ logicalBlocks() {
432
+ const out = [];
433
+ const walk = (parent) => {
434
+ for (const el of parent.children) {
435
+ if (isRuntimeBlock(el)) continue;
436
+ if (el.classList.contains(COL_CLASS)) {
437
+ walk(el);
438
+ continue;
439
+ }
440
+ out.push(el);
441
+ }
442
+ };
443
+ walk(this.contentEl);
444
+ return out;
445
+ }
446
+
447
+ showDropLine(slot) {
448
+ if (!slot) {
449
+ this.hideDropLine();
450
+ return;
451
+ }
452
+ const top = slot.before ? slot.rect.top : slot.rect.bottom;
453
+ Object.assign(this.dropLineEl.style, toLocalRect({ left: slot.rect.left, top, width: slot.rect.width, height: 2 }, this.probeEl));
454
+ this.dropLineEl.hidden = false;
455
+ }
456
+
457
+ hideDropLine() {
458
+ this.dropLineEl.hidden = true;
459
+ }
460
+
461
+ onBlankMouseDown(event) {
462
+ const ed = this.editor;
463
+ const root = this.contentEl;
464
+ if (event.button !== 0 || !ed || !this.editable) return;
465
+ if (event.target.closest?.('.re-table-handles, .re-resize-handle, .re-zoom-btn, .re-table-select, .re-col-line')) return;
466
+ if (event.target !== root && root.contains(event.target)) return;
467
+ event.preventDefault();
468
+ this.mqStart = { x: event.clientX, y: event.clientY };
469
+ this.mqDragged = false;
470
+ this._mqMove = (e) => this.onMarqueeMove(e);
471
+ this._mqUp = () => this.onMarqueeUp();
472
+ document.addEventListener('mousemove', this._mqMove);
473
+ document.addEventListener('mouseup', this._mqUp);
474
+ }
475
+
476
+ onMarqueeMove(event) {
477
+ if (!this.mqStart) return;
478
+ if (!this.mqDragged && Math.abs(event.clientX - this.mqStart.x) + Math.abs(event.clientY - this.mqStart.y) < MARQUEE_THRESHOLD) return;
479
+ const ed = this.editor;
480
+ if (!ed || ed.destroyed) return;
481
+ this.mqDragged = true;
482
+ ed.blockMarqueeActive = true;
483
+ ed.clearBlockSelection();
484
+ const client = rectBetween(this.mqStart, { x: event.clientX, y: event.clientY });
485
+ ed.marqueeSelect(client);
486
+ this.marqueeEl.hidden = false;
487
+ Object.assign(this.marqueeEl.style, toLocalRect(client, this.probeEl));
488
+ }
489
+
490
+ onMarqueeUp() {
491
+ document.removeEventListener('mousemove', this._mqMove);
492
+ document.removeEventListener('mouseup', this._mqUp);
493
+ const ed = this.editor;
494
+ if (!this.mqDragged && ed && !ed.destroyed && this.mqStart) ed.focusAt(this.mqStart.x, this.mqStart.y);
495
+ this.marqueeEl.hidden = true;
496
+ this.mqStart = null;
497
+ this.mqDragged = false;
498
+ }
499
+
500
+ onSurfaceMouseDownCapture() {
501
+ const ed = this.editor;
502
+ if (ed && ed.blockMarqueeActive) {
503
+ ed.blockMarqueeActive = false;
504
+ ed.clearBlockSelection();
505
+ }
506
+ }
507
+
508
+ /* ===================== 图片放大 ===================== */
509
+
510
+ onContentClick(event) {
511
+ if (this.editable) return;
512
+ const img = event.target.closest?.('img');
513
+ if (img) this.openPreview(img);
514
+ }
515
+
516
+ onContentDblClick(event) {
517
+ if (!this.editable) return;
518
+ const img = event.target.closest?.('img');
519
+ if (!img) return;
520
+ event.preventDefault();
521
+ this.openPreview(img);
522
+ }
523
+
524
+ zoomSelected() {
525
+ if (this.selectedImage) this.openPreview(this.selectedImage);
526
+ }
527
+
528
+ openPreview(img) {
529
+ const viewer = this.viewerEl;
530
+ const target = viewer.querySelector('img');
531
+ target.src = img.src;
532
+ viewer.hidden = false;
533
+ }
534
+
535
+ closePreview() {
536
+ this.viewerEl.hidden = true;
537
+ if (this.editable) requestAnimationFrame(() => this.editor?.focus());
538
+ }
539
+
540
+ startResize(direction, event) {
541
+ const img = this.selectedImage;
542
+ const ed = this.editor;
543
+ if (!img || !ed) return;
544
+ event.preventDefault();
545
+ const rect = img.getBoundingClientRect();
546
+ const ratio = rect.width / Math.max(1, rect.height);
547
+ const scale = overlayOrigin(this.probeEl).z;
548
+ const start = { x: event.clientX, width: rect.width };
549
+ const horizontal = direction.endsWith('left') ? -1 : 1;
550
+ let begun = false;
551
+ const onMove = (moveEvent) => {
552
+ if (!beginEditable()) return;
553
+ const width = Math.max(MIN_IMAGE_WIDTH, Math.round((start.width + (moveEvent.clientX - start.x) * horizontal) / scale));
554
+ const height = Math.max(MIN_IMAGE_HEIGHT, Math.round(width / ratio));
555
+ // [坑] 逐帧 run 会灌满历史栈:拖拽只在首次移动时开一步,后续帧合入同一条撤销记录
556
+ ed.run(() => {
557
+ img.setAttribute('width', String(width));
558
+ img.setAttribute('height', String(height));
559
+ }, { coalesce: begun });
560
+ begun = true;
561
+ this.scheduleOverlayUpdate();
562
+ };
563
+ const beginEditable = () => {
564
+ if (!img.isConnected || ed.destroyed) {
565
+ onUp();
566
+ return false;
567
+ }
568
+ return true;
569
+ };
570
+ const onUp = () => {
571
+ this._resizeCleanup = null;
572
+ document.removeEventListener('mousemove', onMove);
573
+ document.removeEventListener('mouseup', onUp);
574
+ };
575
+ this._resizeCleanup = onUp;
576
+ document.addEventListener('mousemove', onMove);
577
+ document.addEventListener('mouseup', onUp);
578
+ }
579
+ }
580
+
581
+ function rectBetween(a, b) {
582
+ return {
583
+ left: Math.min(a.x, b.x),
584
+ top: Math.min(a.y, b.y),
585
+ right: Math.max(a.x, b.x),
586
+ bottom: Math.max(a.y, b.y),
587
+ width: Math.abs(a.x - b.x),
588
+ height: Math.abs(a.y - b.y),
589
+ };
590
+ }
591
+
592
+ function toLocalRect(client, probe) {
593
+ const base = overlayOrigin(probe);
594
+ return {
595
+ left: `${(client.left - base.x) / base.z}px`,
596
+ top: `${(client.top - base.y) / base.z}px`,
597
+ width: `${client.width / base.z}px`,
598
+ height: `${client.height / base.z}px`,
599
+ };
600
+ }