@a200888213/gbdocx 0.3.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.
package/README.md CHANGED
@@ -36,7 +36,7 @@ npm start # node serve.mjs,默认 http://localhost:5273/
36
36
 
37
37
  页面本身只有 `index.html`,它加载四个样式表(顺序有意义):`tokens.css` → `editor-content.css` → `word-panel.css` → `app.css`。自己装配页面时请全部引入,否则正文排版和面板都会走形。
38
38
 
39
- `index.html` 里有一条 importmap,把裸标识符 `gbooxml` / `guabiutils` 映射到 `/vendor/*`,而 `serve.mjs` 把 `/vendor/gbooxml/*`、`/vendor/guabiutils/*` 指向**同级目录**的源码。这意味着这个自带 demo 只在仓库的 monorepo 布局下能跑;从 npm 单独安装后要用 demo 页面,请自行把 `gbooxml` 映射到 `node_modules/gbooxml/src/index.js`。
39
+ `index.html` 里有一条 importmap,把裸标识符 `gbooxml` / `guabiutils` 映射到 `/vendor/*`,而 `serve.mjs` 把 `/vendor/gbooxml/*`、`/vendor/gbofficeui/*` 指向 `packages/gboffice/` 下的同级源码,把 `/vendor/guabiutils/*` 指向仓库的 `packages/guabiutils/src`。这意味着这个自带 demo 只在仓库的 monorepo 布局下能跑;从 npm 单独安装后要用 demo 页面,请自行把 `gbooxml` 映射到 `node_modules/gbooxml/src/index.js`,并按下方顺序引入四份样式(顶栏皮肤来自 `gbofficeui`)。
40
40
 
41
41
  ## 嵌入到自己的页面
42
42
 
@@ -46,6 +46,7 @@ import '@a200888213/gbdocx/styles/tokens.css';
46
46
  import '@a200888213/gbdocx/styles/editor-content.css';
47
47
  import '@a200888213/gbdocx/styles/word-panel.css';
48
48
  import '@a200888213/gbdocx/styles/app.css';
49
+ import 'gbofficeui/styles/office-chrome.css'; // 菜单栏/文档头/功能区/状态栏共享皮肤
49
50
 
50
51
  const app = new WordApp(document.getElementById('app'));
51
52
  await app.start();
@@ -199,7 +200,7 @@ const { parseDocx } = await import('@a200888213/gbdocx/kernel/docx/codec/docx');
199
200
  2. `new WordApp(mount)` 的挂载元素必须已在文档中,构造期间就会测量布局;先 `append` 再 `new`。
200
201
  3. `WordApp` 不对外派发任何事件,它只消费编辑器内核的事件总线。要做联动,取 `app.editor` 后 `app.editor.on('state' | 'selection', fn)`。
201
202
  4. 偏好(缩放、面板开关)持久化在 `localStorage['gbdocx.prefs']`,SSR 环境请在客户端实例化。
202
- 5. 自带 demo 的 `/vendor/gbooxml` 依赖仓库同级目录布局,从 npm 单独安装需自己改 importmap。
203
+ 5. 自带 demo 的 `/vendor/gbooxml` 依赖仓库 `packages/gboffice/` 的分组布局,从 npm 单独安装需自己改 importmap。
203
204
 
204
205
  ## 许可
205
206
 
package/index.html CHANGED
@@ -7,7 +7,8 @@
7
7
  <link rel="stylesheet" href="/styles/tokens.css" />
8
8
  <link rel="stylesheet" href="/styles/editor-content.css" />
9
9
  <link rel="stylesheet" href="/styles/word-panel.css" />
10
- <link rel="stylesheet" href="/styles/app.css" />
10
+ <link rel="stylesheet" href="/styles/app.css" />
11
+ <link rel="stylesheet" href="/vendor/gbofficeui/office-chrome.css" />
11
12
  <script type="importmap">
12
13
  {
13
14
  "imports": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a200888213/gbdocx",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "挂逼文档:独立 .docx 编辑器(内核移植自 guabi office/docx 编解码 + 自研 contenteditable 编辑器内核,UI 用原生 HTML 重写),只依赖 gbooxml。",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -36,6 +36,7 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "gbooxml": "^0.1.1",
39
+ "gbofficeui": "^0.1.0",
39
40
  "guabiutils": "^0.3.0"
40
41
  },
41
42
  "devDependencies": {
package/serve.mjs CHANGED
@@ -4,7 +4,8 @@ import { fileURLToPath } from 'node:url';
4
4
  import { startStaticServer } from 'guabiutils/dev-server';
5
5
 
6
6
  const ooxmlRoot = fileURLToPath(new URL('../gbooxml/', import.meta.url));
7
- const utilsSrc = fileURLToPath(new URL('../guabiutils/src/', import.meta.url));
7
+ const utilsSrc = fileURLToPath(new URL('../../guabiutils/src/', import.meta.url));
8
+ const officeChrome = fileURLToPath(new URL('../gbofficeui/styles/', import.meta.url));
8
9
 
9
10
  const { origin } = await startStaticServer({
10
11
  root: fileURLToPath(new URL('.', import.meta.url)),
@@ -13,6 +14,7 @@ const { origin } = await startStaticServer({
13
14
  mounts: [
14
15
  { prefix: '/vendor/gbooxml/', dir: ooxmlRoot },
15
16
  { prefix: '/vendor/guabiutils/', dir: utilsSrc },
17
+ { prefix: '/vendor/gbofficeui/', dir: officeChrome },
16
18
  ],
17
19
  });
18
20
 
@@ -18,7 +18,7 @@ function setEditMode(mode) {
18
18
  this.surface.setEditable(mode !== 'readonly');
19
19
  this.surface.setSuggesting(mode === 'suggest');
20
20
  this.statusBar.setMode(mode);
21
- this.toolbar.refresh();
21
+ this.ribbon?.refresh();
22
22
  }
23
23
 
24
24
  function refreshStats() {
@@ -61,7 +61,7 @@ function insertLink() {
61
61
 
62
62
  function openTableSpec(e) {
63
63
  if (this.editMode === 'readonly') return;
64
- const anchor = e?.currentTarget || e?.target || this.toolbar;
64
+ const anchor = e?.currentTarget || e?.target || this.headEl;
65
65
  openMenu({
66
66
  anchor,
67
67
  items: [2, 3, 4, 5].map((n) => ({ label: `${n} × ${n} 表格`, onClick: () => this.run('insertTable', { rows: n, cols: n, withHeaderRow: true }) })),
@@ -3,7 +3,7 @@
3
3
  // [设计] 方法以独立函数导出,由 word-app.js 末尾 Object.assign 装配到 WordApp.prototype:
4
4
  // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
5
 
6
- import { pageGeometry, layoutOf, GUTTER, fromSheetTop, pageNumberStyle, bandStyle, sheetStyle } from '../../kernel/docx/pageGeometry.js';
6
+ import { pageGeometry, layoutOf, GUTTER, SHEET_TOP_GAP, fromSheetTop, pageNumberStyle, bandStyle, sheetStyle } from '../../kernel/docx/pageGeometry.js';
7
7
  import { repaginate } from '../../kernel/docx/pagination.js';
8
8
  import { savePrefs } from './shared.js';
9
9
  function geo() { return pageGeometry(this.state.page); }
@@ -53,6 +53,7 @@ function applyEditorGeometry() {
53
53
  const geo = this.geo();
54
54
  const layout = this.layout();
55
55
  this.editorWrap.style.zoom = String(this.zoom / 100);
56
+ this.editorWrap.style.setProperty('--gbd-wd-sheet-top', `${SHEET_TOP_GAP}px`);
56
57
  const style = {
57
58
  '--gbd-re-content-w': `${geo.w}mm`,
58
59
  '--gbd-re-content-m': '0 auto',
@@ -145,7 +146,9 @@ function refreshScroll() {
145
146
  const pageH = this.layout().pageH;
146
147
  if (!pageH) return;
147
148
  const step = pageH + GUTTER;
148
- this.visiblePage = Math.max(1, Math.min(this.pageCount, Math.floor(this.surface.scrollEl.scrollTop / step) + 1));
149
+ // 第一页不从滚动原点起:扣掉纸层顶部留白再折算页序,否则页数会提前一页翻
150
+ const offset = this.surface.scrollEl.scrollTop - SHEET_TOP_GAP;
151
+ this.visiblePage = Math.max(1, Math.min(this.pageCount, Math.floor(Math.max(0, offset) / step) + 1));
149
152
  this.statusBar.setPage(this.visiblePage, this.pageCount);
150
153
  }
151
154
 
@@ -6,6 +6,35 @@
6
6
  import { cleanHfHtml } from '../../kernel/docx/codec/helpers.js';
7
7
  import { openColumnDialog as openColumnDialogUI, openMarginDialog as openMarginDialogUI, openPageSetupDialog as openPageSetupDialogUI } from '../../ui/dialogs.js';
8
8
  import { savePrefs } from './shared.js';
9
+
10
+ /** 预览模式:只读 + 收起编辑界面;按钮留在文件头行原位,再点或按 Esc 退出 */
11
+ function setPreview(on) {
12
+ const next = !!on;
13
+ if (next === this.preview) return;
14
+ if (next) {
15
+ this.previewRestore = { readOnly: this.readOnly, mode: this.editMode, menuBar: this.menuBarVisible };
16
+ this.preview = true;
17
+ this.root.classList.add('gb-is-preview');
18
+ this.previewBtn.setAttribute('aria-pressed', 'true');
19
+ this.previewBtn.title = '退出预览';
20
+ this.previewBtn.querySelector('span').textContent = '退出预览';
21
+ this.setReadOnly(true);
22
+ this.setMenuBarVisible(false);
23
+ } else {
24
+ const restore = this.previewRestore || { readOnly: false, mode: 'edit', menuBar: true };
25
+ this.preview = false;
26
+ this.root.classList.remove('gb-is-preview');
27
+ this.previewBtn.setAttribute('aria-pressed', 'false');
28
+ this.previewBtn.title = '预览模式';
29
+ this.previewBtn.querySelector('span').textContent = '预览';
30
+ this.setReadOnly(restore.readOnly);
31
+ if (!restore.readOnly) this.setEditMode(restore.mode);
32
+ this.setMenuBarVisible(restore.menuBar);
33
+ this.previewRestore = null;
34
+ }
35
+ this.previewBtn.blur();
36
+ }
37
+
9
38
  function setView(key, on) {
10
39
  const next = on === undefined ? !this.flags[key] : !!on;
11
40
  this.flags = { ...this.flags, [key]: next };
@@ -85,4 +114,4 @@ function openColumnDialog() {
85
114
  });
86
115
  }
87
116
 
88
- export const viewMethods = { setView, applyView, renderPanels, renderHead, openPageSetupDialog, openMarginDialog, openColumnDialog };
117
+ export const viewMethods = { setView, applyView, renderPanels, renderHead, openPageSetupDialog, openMarginDialog, openColumnDialog, setPreview };
@@ -18,7 +18,8 @@ import { notify } from '../kernel/notify.js';
18
18
  import { useKeyboard, KEY_PRIORITY } from '../kernel/keyboard.js';
19
19
  import { buildMenuBar } from '../ui/menubar.js';
20
20
  import { closeAll } from '../ui/popup.js';
21
- import { buildToolbar } from '../ui/toolbar.js';
21
+ import { buildRibbon } from '../ui/ribbon.js';
22
+ import { icon } from '../ui/icons.js';
22
23
  import { StatusBar } from '../ui/statusbar.js';
23
24
  import { CatalogPanel, CommentsPanel } from '../ui/panels.js';
24
25
  import { PromptPopover } from '../ui/prompt.js';
@@ -83,6 +84,8 @@ export class WordApp {
83
84
  this.pageCount = 1;
84
85
  this.visiblePage = 1;
85
86
  this.editMode = 'edit';
87
+ this.preview = false;
88
+ this.previewRestore = null;
86
89
  this.dirty = false;
87
90
  this.saving = false;
88
91
  this.suggestionCount = 0;
@@ -117,10 +120,13 @@ export class WordApp {
117
120
  <span class="word-head__path"></span>
118
121
  <span class="word-head__dirty" hidden>●</span>
119
122
  <span class="word-head__spacer"></span>
120
- <label class="word-head__auto"><input type="checkbox" class="word-head__autosave" />自动保存</label>
121
- <button type="button" class="gbd-btn" data-act="open">打开</button>
122
- <button type="button" class="gbd-btn" data-act="save">保存</button>
123
- <button type="button" class="gbd-btn" data-act="export">导出副本</button>
123
+ <span class="word-head__actions">
124
+ <label class="word-head__auto"><input type="checkbox" class="word-head__autosave" />自动保存</label>
125
+ <button type="button" class="gbd-btn" data-act="open">打开</button>
126
+ <button type="button" class="gbd-btn" data-act="save">保存</button>
127
+ <button type="button" class="gbd-btn" data-act="export">导出副本</button>
128
+ </span>
129
+ <button type="button" class="gbd-btn word-head__preview" data-act="preview" title="预览模式" aria-pressed="false">${icon('eye')}<span>预览</span></button>
124
130
  </div>
125
131
  <div class="gbd-toolbar-host"></div>
126
132
  <div class="word-main">
@@ -134,12 +140,15 @@ export class WordApp {
134
140
  this.menubarHost = root.querySelector('.gbd-menubar-host');
135
141
  this.headEl = root.querySelector('.word-head');
136
142
  this.toolbarHost = root.querySelector('.gbd-toolbar-host');
137
- this.guard = createReadOnlyGuard(root, { editZones: () => [this.headEl, this.toolbarHost] });
143
+ this.headActionsEl = root.querySelector('.word-head__actions');
144
+ // 预览按钮不随只读被 inert:它要能在预览档里继续点「退出预览」
145
+ this.guard = createReadOnlyGuard(root, { editZones: () => [this.headActionsEl, this.toolbarHost] });
138
146
  this.editorWrap = root.querySelector('.word-editor');
139
147
  this.titleEl = root.querySelector('.word-head__title');
140
148
  this.pathEl = root.querySelector('.word-head__path');
141
149
  this.dirtyEl = root.querySelector('.word-head__dirty');
142
150
  this.autosaveEl = root.querySelector('.word-head__autosave');
151
+ this.previewBtn = root.querySelector('[data-act="preview"]');
143
152
 
144
153
  this.catalogPanel = new CatalogPanel((key) => this.locateCatalog(key));
145
154
  this.commentsPanel = new CommentsPanel({
@@ -161,17 +170,22 @@ export class WordApp {
161
170
  });
162
171
  this.editorState = this.editor.state();
163
172
 
164
- this.toolbar = buildToolbar({
165
- getEditor: () => this.editor,
166
- getState: () => this.editorState,
173
+ // 选项卡栏(WPS 风格):tab 行 + 各页分组工具面板,完全接管原图标工具栏
174
+ this.ribbon = buildRibbon({
175
+ getState: () => ({ ...this.editorState, ...this.menuCtx().state }),
176
+ getCtx: () => this.menuCtx(),
167
177
  isDisabled: () => this.editMode === 'readonly',
178
+ run: (name, ...args) => this.run(name, ...args),
168
179
  actions: {
169
180
  insertTable: (e) => this.openTableSpec(e),
170
181
  insertImage: () => this.pickImage(),
171
182
  insertLink: () => this.insertLink(),
172
183
  },
184
+ find: (replace) => this.findBar.open(!!replace),
185
+ openMargin: () => this.openMarginDialog(),
186
+ openColumn: () => this.openColumnDialog(),
173
187
  });
174
- root.querySelector('.gbd-toolbar-host').appendChild(this.toolbar);
188
+ this.toolbarHost.appendChild(this.ribbon);
175
189
 
176
190
  this.statusBar = new StatusBar({
177
191
  onMode: (m) => this.setEditMode(m),
@@ -236,6 +250,7 @@ export class WordApp {
236
250
  bind('open', 'open', this.openFile);
237
251
  bind('save', 'save', this.save);
238
252
  bind('export', 'exportCopy', this.exportDocx);
253
+ this.previewBtn.addEventListener('click', () => this.setPreview(!this.preview));
239
254
  this.autosaveEl.addEventListener('change', () => {
240
255
  const on = this.autosaveEl.checked;
241
256
  if (this.embed && this.io?.setAutosave) return this.io.setAutosave(on);
@@ -276,7 +291,7 @@ export class WordApp {
276
291
  // 编辑器状态刷新 → 工具栏/状态栏
277
292
  const refresh = () => {
278
293
  this.editorState = this.editor.state();
279
- this.toolbar.refresh();
294
+ this.ribbon.refresh();
280
295
  this.statusBar.setCaret(this.editorState.line || 0, this.editorState.column || 0);
281
296
  };
282
297
  this.editor.on('state', refresh);
@@ -288,6 +303,10 @@ export class WordApp {
288
303
  // 嵌入模式:非激活页签不消费任何快捷键(多页签同页共存时键盘归属只看 active)
289
304
  if (this.isActive && !this.isActive()) return false;
290
305
  if (!e.ctrlKey && !e.metaKey) {
306
+ if (e.key === 'Escape' && this.preview) {
307
+ this.setPreview(false);
308
+ return true;
309
+ }
291
310
  if (e.key === 'Escape' && !this.charsPop.hidden) {
292
311
  this.charsPop.hidden = true;
293
312
  return true;
@@ -7,6 +7,8 @@ import { clamp } from 'guabiutils';
7
7
 
8
8
  /** 纸间缝(px):屏幕态一张张纸分开,打印态由 --wd-gutter 归零连排 */
9
9
  export const GUTTER = 14;
10
+ /** 纸层顶部留白(px):屏幕态第一页上沿与滚动原点之间露出画布,纸的上边缘与阴影才看得见(打印态归零) */
11
+ export const SHEET_TOP_GAP = 26;
10
12
  /** 页眉页脚距纸张边缘的缺省值(mm):与后端 pgMar 的 720 twips 同为 Word 默认 */
11
13
  const DEFAULT_HF_MM = 12.7;
12
14
 
@@ -1,5 +1,5 @@
1
1
  // [文件] web·editor-kernel·blocks·结构操作 —— 复制/删除/移动/缩进出缩/光标拆块(含块收尾 settleBlock)
2
- import { blockLength, blockOf, charOffset, domPoint, hasBlockBody, isBlockEmpty, isCell, isCodeContent, isRuntimeBlock, isTaskItem, rangeOf, moveChildren, setCaret } from './dom.js';
2
+ import { blockLength, blockOf, charOffset, domPoint, hasBlockBody, isBlockEmpty, isCell, isCodeContent, isRuntimeBlock, isTaskItem, mergeSplitFamily, rangeOf, moveChildren, setCaret, RUNTIME_SPLIT_ATTR } from './dom.js';
3
3
  import { copyBlockStyle, liftOneOutOf, listItemOf, liveTarget, makeCheckbox, noteContainerOf, lastContainerBlock, pruneEmpty, quoteOf, releaseListItem, structureTargets, taskContentHost } from './blocks.js';
4
4
  import { emptyParagraph } from './blocksInsert.js';
5
5
  import { insertHardBreak, insertNewlineInCode } from './blocksEnter.js';
@@ -72,6 +72,24 @@ export function moveBlockTo(el, ref, before) {
72
72
  return true;
73
73
  }
74
74
 
75
+ /**
76
+ * 表格拖拽落点:跨页续表先并回首块再搬家
77
+ * [坑] 只搬当前碎片会丢行序:下次重排 flatten 按文档序并回,被搬走的碎片若落到尾块之后,
78
+ * 接续行会被并到错误的表上——必须先整家族并回,用首块整体搬
79
+ * @param {HTMLElement} root 编辑面根
80
+ * @param {HTMLElement} table 命中的表(可能是续表碎片)
81
+ * @param {HTMLElement} ref 落点块
82
+ * @param {boolean} before true=插到 ref 前,false=插到 ref 后
83
+ */
84
+ export function moveTableTo(root, table, ref, before) {
85
+ if (!table?.isConnected || !ref?.isConnected) return false;
86
+ if (table === ref || table.contains(ref) || ref.contains(table)) return false;
87
+ // 落点还是同一家族的续表碎片:并回后它会消失,等于搬了个空——先拒绝
88
+ const split = table.getAttribute(RUNTIME_SPLIT_ATTR);
89
+ if (split && ref.getAttribute(RUNTIME_SPLIT_ATTR) === split) return false;
90
+ return moveBlockTo(mergeSplitFamily(root, table), ref, before);
91
+ }
92
+
75
93
  /* ===================== 列表升降级(Tab / Shift+Tab) ===================== */
76
94
 
77
95
  export function sinkListItem(li) {
@@ -133,6 +133,7 @@ export const COMMANDS = {
133
133
  moveBlockUp: { run: (ed, el) => B.moveBlock(ed.root, el, -1) },
134
134
  moveBlockDown: { run: (ed, el) => B.moveBlock(ed.root, el, 1) },
135
135
  moveBlockTo: { run: (ed, el, ref, before) => B.moveBlockTo(el, ref, before) },
136
+ moveTableTo: { run: (ed, table, ref, before) => B.moveTableTo(ed.root, table, ref, before) },
136
137
  deleteRange: {
137
138
  run: (ed, { block, from, to }) => {
138
139
  if (!block?.isConnected) return false;
@@ -52,7 +52,7 @@ const ANCHOR_SELECTOR = '[data-attach],[data-ref-doc]';
52
52
  * 占位/分隔元素整块删除;栏容器拆壳留内容;行级拆分块按家族标记并回首个块 */
53
53
  export const RUNTIME_ELEMENT_SELECTOR = '.wd-page-gap, .wd-col-sep';
54
54
  const RUNTIME_UNWRAP_SELECTOR = '.wd-col';
55
- const RUNTIME_SPLIT_ATTR = 'data-wd-split';
55
+ export const RUNTIME_SPLIT_ATTR = 'data-wd-split';
56
56
 
57
57
  /**
58
58
  * 运行期布局产物判据(Word 分页的页间缝 / 栏分隔 / 跨页拆分的段落碎片):不是正文块。
@@ -62,6 +62,46 @@ const RUNTIME_SPLIT_ATTR = 'data-wd-split';
62
62
  export const isRuntimeBlock = (el) =>
63
63
  el?.nodeType === Node.ELEMENT_NODE && (el.matches(RUNTIME_ELEMENT_SELECTOR) || el.hasAttribute(RUNTIME_SPLIT_ATTR));
64
64
 
65
+ /**
66
+ * 拆分家族并回首块
67
+ * @param {HTMLElement} first 首块(文档序最先的碎片)
68
+ * @param {HTMLElement[]} rest 其余碎片
69
+ * @returns {HTMLElement} 首块
70
+ */
71
+ function mergeSplitGroup(first, rest) {
72
+ rest.forEach((el) => {
73
+ // 表格家族:续表只有「重复表头 + 接续行」两块——表头是克隆(丢弃),接续行并回首表最后一个 tbody
74
+ if (first.tagName === 'TABLE') {
75
+ // [坑] 通用「appendChild 全部子节点」会把续表的 thead / tbody 直接挂到首表尾部(多出一个 tbody),
76
+ // 表格结构当场坏掉:行级分页只认 tBodies 里的行,行数由此少算,超高表被误判「装得下」而永不拆行
77
+ const host = first.tBodies[first.tBodies.length - 1] || first.appendChild(document.createElement('tbody'));
78
+ Array.from(el.tBodies).forEach((tb) => Array.from(tb.rows).forEach((row) => host.appendChild(row)));
79
+ el.remove();
80
+ return;
81
+ }
82
+ moveChildren(el, first);
83
+ el.remove();
84
+ });
85
+ first.removeAttribute(RUNTIME_SPLIT_ATTR);
86
+ return first;
87
+ }
88
+
89
+ /**
90
+ * 把 el 所在的跨页拆分家族并回首块(悬停/拖拽命中的可能是续表碎片)
91
+ * [设计] 只并本家族,不动其它分页产物:宿主拖表要在同一次历史提交里先并回再搬家,这一步不能等重排
92
+ * @param {HTMLElement} container 编辑面根(家族查找范围)
93
+ * @param {HTMLElement} el 家族任一成员
94
+ * @returns {HTMLElement} 首块(无拆分标记时原样返回)
95
+ */
96
+ export function mergeSplitFamily(container, el) {
97
+ const id = el?.getAttribute?.(RUNTIME_SPLIT_ATTR);
98
+ if (!id || !container?.querySelectorAll || !container.contains?.(el)) return el;
99
+ const members = Array.from(container.querySelectorAll(`[${RUNTIME_SPLIT_ATTR}]`))
100
+ .filter((node) => node.getAttribute(RUNTIME_SPLIT_ATTR) === id);
101
+ if (!members.length) return el;
102
+ return mergeSplitGroup(members[0], members.slice(1));
103
+ }
104
+
65
105
  /**
66
106
  * 把运行期布局结构还原成单流正文(装载时防御性调用、序列化前必须调用):
67
107
  * 拆分块并回、栏容器拆壳、占位元素删除——三者的顺序不可调换
@@ -75,23 +115,7 @@ export function restoreRuntimeStructures(container) {
75
115
  if (!groups.has(id)) groups.set(id, []);
76
116
  groups.get(id).push(el);
77
117
  });
78
- groups.forEach((els) => {
79
- const first = els[0];
80
- els.slice(1).forEach((el) => {
81
- // 表格家族:续表只有「重复表头 + 接续行」两块——表头是克隆(丢弃),接续行并回首表最后一个 tbody
82
- if (first.tagName === 'TABLE') {
83
- // [坑] 通用「appendChild 全部子节点」会把续表的 thead / tbody 直接挂到首表尾部(多出一个 tbody),
84
- // 表格结构当场坏掉:行级分页只认 tBodies 里的行,行数由此少算,超高表被误判「装得下」而永不拆行
85
- const host = first.tBodies[first.tBodies.length - 1] || first.appendChild(document.createElement('tbody'));
86
- Array.from(el.tBodies).forEach((tb) => Array.from(tb.rows).forEach((row) => host.appendChild(row)));
87
- el.remove();
88
- return;
89
- }
90
- moveChildren(el, first);
91
- el.remove();
92
- });
93
- first.removeAttribute(RUNTIME_SPLIT_ATTR);
94
- });
118
+ groups.forEach((els) => mergeSplitGroup(els[0], els.slice(1)));
95
119
  // 2) 栏容器拆壳:里面装的是正文本体,删了就丢内容
96
120
  container.querySelectorAll(RUNTIME_UNWRAP_SELECTOR).forEach((el) => unwrapElement(el));
97
121
  // 3) 占位/分隔元素整块删除
@@ -16,6 +16,23 @@ export const TABLE_INTERACTION_HANDLERS = ['onMouseDown', 'onHoverColumn', 'onLe
16
16
 
17
17
  /** 表格框选与列宽方法(装配到 EditorCore.prototype;this 为内核实例) */
18
18
  export const tableInteractionMethods = {
19
+ /**
20
+ * 整表转成单元格框选(移动手柄单击 / 菜单「选择整个表格」共用)
21
+ * @param {HTMLTableElement} table 目标表
22
+ * @returns {boolean} 是否落地
23
+ */
24
+ selectTable(table) {
25
+ if (!table?.isConnected || !this.root.contains(table)) return false;
26
+ const grid = this.cachedGrid(table);
27
+ if (!grid.width || !grid.height) return false;
28
+ this.cellRect = { table, rect: { r1: 0, c1: 0, r2: grid.height - 1, c2: grid.width - 1 } };
29
+ // 紧接着的表格菜单动作按命中格取上下文:锚到左上格,整表操作才不会静默失效
30
+ this.contextCell = grid.matrix[0]?.[0]?.el || null;
31
+ this.notifyCellSelection();
32
+ this.syncState();
33
+ return true;
34
+ },
35
+
19
36
  /**
20
37
  * 拖列边设列宽:落点在「格右边界 ± COL_RESIZE_HIT/2」的命中带内即接管
21
38
  * 中间列的右边界 = 与右邻列的共享线(两列守恒转移,表宽不变);最后一列的右边界 = 表右边界
@@ -81,11 +81,7 @@ export const tableOpsMethods = {
81
81
  /** 全选表格单元格(菜单「选择整个表格」):转成框选态,后续合并/删除按整表走 */
82
82
  selectAllCells() {
83
83
  const ctx = this.tableContext();
84
- if (!ctx) return false;
85
- const rect = { r1: 0, c1: 0, r2: ctx.grid.height - 1, c2: ctx.grid.width - 1 };
86
- this.cellRect = { table: ctx.table, rect };
87
- this.notifyCellSelection();
88
- return true;
84
+ return ctx ? this.selectTable(ctx.table) : false;
89
85
  },
90
86
 
91
87
  /**
@@ -2,6 +2,7 @@
2
2
  // 说明:Vue 槽位改回调装配(backdrop 由宿主填充),其余行为与 guabi 版逐条对齐。
3
3
 
4
4
  import { EditorCore } from '../kernel/editor/engine/editor.js';
5
+ import { isRuntimeBlock } from '../kernel/editor/engine/dom.js';
5
6
  import { overlayOrigin, PROBE_WIDTH } from '../kernel/editor/overlayGeometry.js';
6
7
 
7
8
  /** 内容上报防抖(ms):按键只置脏,序列化交给拖尾防抖;失焦与卸载立即落地 */
@@ -11,7 +12,16 @@ const MARQUEE_THRESHOLD = 4;
11
12
  const MIN_IMAGE_WIDTH = 60;
12
13
  const MIN_IMAGE_HEIGHT = 40;
13
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';
14
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>';
15
25
 
16
26
  export class EditorSurface {
17
27
  /**
@@ -48,9 +58,11 @@ export class EditorSurface {
48
58
  <div class="re-table-layer">
49
59
  <span class="re-table-select" hidden></span>
50
60
  <div class="re-table-handles" hidden>
61
+ <button type="button" class="re-table-move" aria-label="拖动表格" title="拖动表格">${MOVE_ICON}</button>
51
62
  <button type="button" class="re-table-handle gbd-is-column" aria-label="在右侧插入一列">+</button>
52
63
  <button type="button" class="re-table-handle gbd-is-row" aria-label="在下方插入一行">+</button>
53
64
  </div>
65
+ <span class="re-drop-line" hidden></span>
54
66
  <span class="re-col-line" hidden></span>
55
67
  </div>
56
68
  <div class="re-marquee" hidden></div>
@@ -71,6 +83,8 @@ export class EditorSurface {
71
83
  this.tableLayer = root.querySelector('.re-table-layer');
72
84
  this.selectBoxEl = root.querySelector('.re-table-select');
73
85
  this.handlesEl = root.querySelector('.re-table-handles');
86
+ this.moveHandleEl = root.querySelector('.re-table-move');
87
+ this.dropLineEl = root.querySelector('.re-drop-line');
74
88
  this.colLineEl = root.querySelector('.re-col-line');
75
89
  this.marqueeEl = root.querySelector('.re-marquee');
76
90
  this.resizeBoxEl = root.querySelector('.re-resize-box');
@@ -181,6 +195,7 @@ export class EditorSurface {
181
195
  destroy() {
182
196
  this.flushEmit();
183
197
  this._resizeCleanup?.();
198
+ this._tableMoveCleanup?.();
184
199
  this.editor?.destroy();
185
200
  this.editor = null;
186
201
  if (this.resizeRaf) cancelAnimationFrame(this.resizeRaf);
@@ -242,6 +257,12 @@ export class EditorSurface {
242
257
  const row = this.handlesEl.querySelector('.gbd-is-row');
243
258
  Object.assign(col.style, { left: `${Math.round(left + width)}px`, top: `${Math.round(top)}px`, height: `${Math.round(height)}px` });
244
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
+ });
245
266
  this.handlesEl.hidden = false;
246
267
  }
247
268
 
@@ -301,11 +322,14 @@ export class EditorSurface {
301
322
  });
302
323
  this.handlesEl.querySelector('.gbd-is-column').addEventListener('mousedown', (e) => this.startEdgeGesture('column', e));
303
324
  this.handlesEl.querySelector('.gbd-is-row').addEventListener('mousedown', (e) => this.startEdgeGesture('row', e));
325
+ this.moveHandleEl.addEventListener('mousedown', (e) => this.startTableMove(e));
304
326
  this.viewerEl.addEventListener('click', () => this.closePreview());
305
327
  }
306
328
 
307
329
  onSurfaceMouseMove(event) {
308
330
  if (!this.editable) return;
331
+ // 拖表手势期悬停目标已锁:再按指针重算会让手柄跟着别的表跳
332
+ if (this._tableMoveCleanup) return;
309
333
  const target = event.target;
310
334
  if (!(target instanceof Element)) return;
311
335
  if (target.closest('.re-table-handles')) return;
@@ -327,6 +351,113 @@ export class EditorSurface {
327
351
  ed.beginEdgeGesture(event, table, axis);
328
352
  }
329
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
+
330
461
  onBlankMouseDown(event) {
331
462
  const ed = this.editor;
332
463
  const root = this.contentEl;