@a200888213/gbdocx 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +215 -207
  2. package/index.html +3 -2
  3. package/package.json +48 -48
  4. package/serve.mjs +3 -2
  5. package/src/app/file-io.js +122 -122
  6. package/src/app/main.js +9 -9
  7. package/src/app/word/catalog.js +52 -52
  8. package/src/app/word/comments.js +112 -112
  9. package/src/app/word/doc.js +113 -113
  10. package/src/app/word/edit.js +72 -72
  11. package/src/app/word/file.js +30 -1
  12. package/src/app/word/hf.js +76 -76
  13. package/src/app/word/layout.js +155 -155
  14. package/src/app/word/notes.js +110 -110
  15. package/src/app/word/shared.js +22 -22
  16. package/src/app/word/view.js +6 -2
  17. package/src/app/word-app.js +486 -469
  18. package/src/app/word-sheets.js +101 -101
  19. package/src/kernel/docx/codec/blocks.js +123 -123
  20. package/src/kernel/docx/codec/carry.js +129 -129
  21. package/src/kernel/docx/codec/comments.js +25 -25
  22. package/src/kernel/docx/codec/docx.js +198 -198
  23. package/src/kernel/docx/codec/docxStyles.js +177 -177
  24. package/src/kernel/docx/codec/fonts.js +195 -195
  25. package/src/kernel/docx/codec/helpers.js +161 -161
  26. package/src/kernel/docx/codec/hfHtml.js +152 -152
  27. package/src/kernel/docx/codec/html.js +739 -739
  28. package/src/kernel/docx/codec/losses.js +420 -420
  29. package/src/kernel/docx/codec/markdown.js +170 -170
  30. package/src/kernel/docx/codec/parts.js +249 -249
  31. package/src/kernel/docx/codec/read.js +603 -603
  32. package/src/kernel/docx/codec/render.js +1156 -1156
  33. package/src/kernel/docx/codec/roundtrip.js +236 -236
  34. package/src/kernel/docx/codec/write.js +833 -833
  35. package/src/kernel/docx/comments.js +14 -14
  36. package/src/kernel/docx/pageGeometry.js +123 -123
  37. package/src/kernel/docx/pagination.js +481 -481
  38. package/src/kernel/docx/watermark.js +45 -45
  39. package/src/kernel/editor/constants.js +8 -8
  40. package/src/kernel/editor/engine/blocks.js +594 -594
  41. package/src/kernel/editor/engine/blocksEnter.js +109 -109
  42. package/src/kernel/editor/engine/blocksInsert.js +254 -254
  43. package/src/kernel/editor/engine/blocksStructure.js +226 -226
  44. package/src/kernel/editor/engine/commands.js +181 -181
  45. package/src/kernel/editor/engine/dom.js +646 -646
  46. package/src/kernel/editor/engine/history.js +149 -149
  47. package/src/kernel/editor/engine/inline.js +656 -656
  48. package/src/kernel/editor/engine/input.js +554 -554
  49. package/src/kernel/editor/engine/interaction.js +137 -137
  50. package/src/kernel/editor/engine/pointer.js +39 -39
  51. package/src/kernel/editor/engine/revision.js +138 -138
  52. package/src/kernel/editor/engine/schema.js +417 -417
  53. package/src/kernel/editor/engine/selection.js +119 -119
  54. package/src/kernel/editor/engine/state.js +118 -118
  55. package/src/kernel/editor/engine/tableClip.js +154 -154
  56. package/src/kernel/editor/engine/tableGrid.js +55 -55
  57. package/src/kernel/editor/engine/tableInteraction.js +388 -388
  58. package/src/kernel/editor/engine/tableMenu.js +250 -250
  59. package/src/kernel/editor/engine/tableOps.js +174 -174
  60. package/src/kernel/editor/engine/tables.js +732 -732
  61. package/src/kernel/editor/overlayGeometry.js +20 -20
  62. package/src/kernel/editor/utils.js +48 -48
  63. package/src/kernel/keyboard.js +114 -114
  64. package/src/kernel/textStyles.js +84 -84
  65. package/src/kernel/util/imageFile.js +91 -91
  66. package/src/kernel/util/shortcutKey.js +33 -33
  67. package/src/surface/editor-surface.js +600 -600
  68. package/src/ui/color-panel.js +69 -69
  69. package/src/ui/context-menu.js +133 -133
  70. package/src/ui/find-bar.js +151 -151
  71. package/src/ui/icons.js +137 -135
  72. package/src/ui/menubar.js +28 -28
  73. package/src/ui/panels.js +115 -115
  74. package/src/ui/prompt.js +89 -89
  75. package/src/ui/ribbon.js +485 -485
  76. package/src/ui/special-chars.js +39 -39
  77. package/src/ui/statusbar.js +81 -81
  78. package/src/ui/toolbar.js +32 -32
  79. package/styles/editor-content.css +440 -440
  80. package/styles/tokens.css +154 -154
@@ -1,469 +1,486 @@
1
- // [文件] gbdocx·WordApp —— docx 编辑器应用装配(几何/分页/批注/脚注/目录/页眉页脚带/菜单/快捷键)
2
- //
3
- // [设计] 本文件只留「装配 + 骨架 + 生命周期 + 自检」;其余职责拆到 ./word/*:
4
- // layout(几何与分页)/ doc(文档状态)/ file(文件动作)/ edit(编辑动作)/ catalog(目录)/
5
- // comments(批注)/ notes(脚注尾注)/ hf(页眉页脚带)/ view(视图与对话框)/ menus(右键菜单与快捷键)。
6
- // 各模块导出方法组,由文件末尾 Object.assign 装配到 WordApp.prototype —— 同一个 this、同一套调用,
7
- // 外部拿到的 WordApp 形状与拆分前完全一致。
8
- // [坑] 装配必须在实例化之前完成:Object.assign 在模块求值时执行,而实例只能在 import 之后 new。
9
-
10
- import { EditorSurface } from '../surface/editor-surface.js';
11
- import { bindCtrlWheelZoom, createReadOnlyGuard } from 'guabiutils';
12
- import { parseDocx } from '../kernel/docx/codec/docx.js';
13
- import { buildDocxVerified } from '../kernel/docx/codec/roundtrip.js';
14
- import { runShortcut } from '../kernel/docx/wordShortcuts.js';
15
- import { buildMenus } from '../kernel/docx/menus.js';
16
- import { HF_MODES, defaultPageConf, defaultPageNumbers, defaultWatermark } from '../kernel/docx/constants.js';
17
- import { notify } from '../kernel/notify.js';
18
- import { useKeyboard, KEY_PRIORITY } from '../kernel/keyboard.js';
19
- import { buildMenuBar } from '../ui/menubar.js';
20
- import { closeAll } from '../ui/popup.js';
21
- import { buildRibbon } from '../ui/ribbon.js';
22
- import { icon } from '../ui/icons.js';
23
- import { StatusBar } from '../ui/statusbar.js';
24
- import { CatalogPanel, CommentsPanel } from '../ui/panels.js';
25
- import { PromptPopover } from '../ui/prompt.js';
26
- import { FindBar } from '../ui/find-bar.js';
27
- import { buildSpecialChars } from '../ui/special-chars.js';
28
- import { openColumnDialog, openMarginDialog } from '../ui/dialogs.js';
29
- import { renderSheets } from './word-sheets.js';
30
- import { loadPrefs, savePrefs } from './word/shared.js';
31
- import { layoutMethods } from './word/layout.js';
32
- import { docMethods } from './word/doc.js';
33
- import { fileMethods } from './word/file.js';
34
- import { editMethods } from './word/edit.js';
35
- import { catalogMethods } from './word/catalog.js';
36
- import { commentsMethods } from './word/comments.js';
37
- import { notesMethods } from './word/notes.js';
38
- import { hfMethods } from './word/hf.js';
39
- import { viewMethods } from './word/view.js';
40
- import { menusMethods } from './word/menus.js';
41
-
42
- export class WordApp {
43
- /**
44
- * @param {HTMLElement} mount 已挂在文档里的挂载点
45
- * @param {object} [options] embed=嵌入宿主;io=文件动作;onDirty/isActive=脏态与快捷键闸门;
46
- * readOnly=只读(禁写且锁编辑控件);hideMenuBar=隐藏顶部菜单栏那一行
47
- */
48
- constructor(mount, options = {}) {
49
- this.mount = mount;
50
- this.embed = !!options.embed;
51
- this.readOnly = !!options.readOnly;
52
- this.menuBarVisible = !options.hideMenuBar;
53
- this.io = options.io || null;
54
- this.onDirty = typeof options.onDirty === 'function' ? options.onDirty : null;
55
- this.isActive = typeof options.isActive === 'function' ? options.isActive : null;
56
- this.doc = { name: '新建文档', handle: null };
57
- this.state = {
58
- sections: [],
59
- page: defaultPageConf(),
60
- pageNumbers: defaultPageNumbers(),
61
- watermark: defaultWatermark(),
62
- hfMode: HF_MODES[0].value,
63
- header: '',
64
- footer: '',
65
- headerEven: '',
66
- footerEven: '',
67
- headerFirst: '',
68
- footerFirst: '',
69
- footnotes: [],
70
- endnotes: [],
71
- props: null,
72
- defaultTabStop: 720,
73
- compressPunctuation: false,
74
- carry: [],
75
- losses: [],
76
- };
77
- this.comments = [];
78
- this.catalog = [];
79
- /** 本次载入的「保存必丢」清单是否已由用户确认(自动保存不得绕过确认静默丢内容) */
80
- this.lossAck = false;
81
- this.lossAutoWarned = false;
82
- this.footnotePages = new Map();
83
- this.fnHeights = [];
84
- this.pageCount = 1;
85
- this.visiblePage = 1;
86
- this.editMode = 'edit';
87
- this.preview = false;
88
- this.previewRestore = null;
89
- this.pageFullscreen = false;
90
- this.dirty = false;
91
- this.saving = false;
92
- this.suggestionCount = 0;
93
- this.activeCommentKey = '';
94
- this.bandEditSlot = '';
95
- this.prefs = loadPrefs();
96
- this.zoom = this.prefs.zoom || 100;
97
- this.flags = this.prefs.flags || { catalog: false, commentsPanel: false };
98
- this.lastEmittedHtml = '';
99
- this.pageTimer = 0;
100
- this.pageRaf = 0;
101
- // [坑] 编辑器内核在 mount 时即抛一次 update(构造期),此时状态栏/工具栏尚未装配:
102
- // 事件接线在构造完成前一律静默,避免读到未定义的宿主成员
103
- this.ready = false;
104
- this.build();
105
- }
106
-
107
- /* ===================== 几何读取 ===================== */
108
-
109
- build() {
110
- // [设计] 所有样式收在 .word-scope 下(本包 CSS 已按该前缀作用域化),宿主落地时不污染同页其它编辑器
111
- const scope = document.createElement('div');
112
- // 应用作用域:需要撑满宿主(.word-app 的 height:100% 以它为基准);浮层的 .word-scope 不挂这个类
113
- scope.className = 'word-scope word-scope--app';
114
- const root = document.createElement('div');
115
- root.className = 'word-app word-skin';
116
- if (this.embed) root.classList.add('gbd-is-embed');
117
- root.innerHTML = `
118
- <div class="gbo-head word-head">
119
- <span class="gbo-head__title"></span>
120
- <span class="gbo-head__sub"></span>
121
- <span class="word-head__dirty" hidden>●</span>
122
- <span class="gbo-head__spacer"></span>
123
- <span class="gbo-head__actions">
124
- <label class="gbo-head__auto"><input type="checkbox" class="gbo-head__autosave" />自动保存</label>
125
- <button type="button" class="gbo-head__btn gbo-head__btn--primary" data-act="save">保存</button>
126
- </span>
127
- <button type="button" class="gbo-head__btn gbo-head__preview" data-act="preview" title="预览模式" aria-pressed="false">${icon('eye')}<span>预览</span></button>
128
- <button type="button" class="gbo-head__btn gbo-head__preview" data-act="fullscreen" title="全屏" aria-pressed="false">${icon('fullscreen')}<span>全屏</span></button>
129
- </div>
130
- <div class="gbd-menubar-host"></div>
131
- <div class="gbd-toolbar-host"></div>
132
- <div class="word-main">
133
- <div class="word-editor"><div class="word-editor-mount"></div></div>
134
- </div>
135
- <div class="gbd-statusbar-host"></div>`;
136
- scope.appendChild(root);
137
- this.mount.appendChild(scope);
138
- this.scopeEl = scope;
139
- this.root = root;
140
- this.menubarHost = root.querySelector('.gbd-menubar-host');
141
- this.headEl = root.querySelector('.word-head');
142
- this.toolbarHost = root.querySelector('.gbd-toolbar-host');
143
- this.headActionsEl = root.querySelector('.gbo-head__actions');
144
- // 预览按钮不随只读被 inert:它要能在预览档里继续点「退出预览」
145
- this.guard = createReadOnlyGuard(root, { editZones: () => [this.headActionsEl, this.toolbarHost] });
146
- this.editorWrap = root.querySelector('.word-editor');
147
- this.titleEl = root.querySelector('.gbo-head__title');
148
- this.pathEl = root.querySelector('.gbo-head__sub');
149
- this.dirtyEl = root.querySelector('.word-head__dirty');
150
- this.autosaveEl = root.querySelector('.gbo-head__autosave');
151
- this.previewBtn = root.querySelector('[data-act="preview"]');
152
- this.fullscreenBtn = root.querySelector('[data-act="fullscreen"]');
153
-
154
- this.catalogPanel = new CatalogPanel((key) => this.locateCatalog(key));
155
- this.commentsPanel = new CommentsPanel({
156
- locate: (key) => this.locateComment(key),
157
- toggle: (key) => this.toggleComment(key),
158
- remove: (key) => this.removeComment(key),
159
- });
160
-
161
- this.surface = new EditorSurface({
162
- mount: root.querySelector('.word-editor-mount'),
163
- placeholder: '开始输入正文…',
164
- editable: true,
165
- handlers: {
166
- update: () => { if (this.ready) this.onDocUpdate(); },
167
- 'open-find': () => this.findBar.open(),
168
- 'request-link': () => this.insertLink(),
169
- },
170
- backdrop: (host) => renderSheets(host, this.sheetsCtx()),
171
- });
172
- this.editorState = this.editor.state();
173
-
174
- // 选项卡栏(WPS 风格):tab 行 + 各页分组工具面板,完全接管原图标工具栏
175
- this.ribbon = buildRibbon({
176
- getState: () => ({ ...this.editorState, ...this.menuCtx().state }),
177
- getCtx: () => this.menuCtx(),
178
- isDisabled: () => this.editMode === 'readonly',
179
- run: (name, ...args) => this.run(name, ...args),
180
- actions: {
181
- insertTable: (e) => this.openTableSpec(e),
182
- insertImage: () => this.pickImage(),
183
- insertLink: () => this.insertLink(),
184
- },
185
- find: (replace) => this.findBar.open(!!replace),
186
- openMargin: () => this.openMarginDialog(),
187
- openColumn: () => this.openColumnDialog(),
188
- });
189
- this.toolbarHost.appendChild(this.ribbon);
190
-
191
- this.statusBar = new StatusBar({
192
- onMode: (m) => this.setEditMode(m),
193
- onZoomIn: () => this.setZoom(this.zoom + 10),
194
- onZoomOut: () => this.setZoom(this.zoom - 10),
195
- onZoomReset: () => this.setZoom(100),
196
- onOpenMargin: () => this.openMarginDialog(),
197
- onOpenColumn: () => this.openColumnDialog(),
198
- });
199
- root.querySelector('.gbd-statusbar-host').appendChild(this.statusBar.el);
200
-
201
- this.findBar = new FindBar(() => this.editor);
202
- root.querySelector('.word-editor').appendChild(this.findBar.el);
203
-
204
- this.prompt = new PromptPopover();
205
- this.prompt.onClosed = () => this.onPromptClosed();
206
-
207
- this.imageInput = document.createElement('input');
208
- this.imageInput.type = 'file';
209
- this.imageInput.accept = 'image/*';
210
- this.imageInput.multiple = true;
211
- this.imageInput.hidden = true;
212
- this.imageInput.addEventListener('change', () => this.onImagePicked());
213
- root.appendChild(this.imageInput);
214
-
215
- this.importInput = document.createElement('input');
216
- this.importInput.type = 'file';
217
- this.importInput.accept = '.docx';
218
- this.importInput.hidden = true;
219
- this.importInput.addEventListener('change', () => this.onImportFile());
220
- root.appendChild(this.importInput);
221
-
222
- this.charsPop = document.createElement('div');
223
- this.charsPop.className = 'word-chars-pop';
224
- this.charsPop.hidden = true;
225
- this.charsPop.appendChild(buildSpecialChars((ch) => this.run('insertText', ch)));
226
- root.querySelector('.word-editor').appendChild(this.charsPop);
227
-
228
- this.bindHead();
229
- this.buildChrome();
230
- this.bindEvents();
231
- this.applyZoom();
232
- this.ready = true;
233
- this.applyMode();
234
- }
235
-
236
- get editor() {
237
- return this.surface.editor;
238
- }
239
-
240
- bindHead() {
241
- const io = this.io || {};
242
- const autosaveOn = typeof io.autosave === 'function' ? io.autosave() : !!this.prefs.autosave;
243
- this.autosaveEl.checked = autosaveOn;
244
- // 嵌入模式:文件头保留(标题/路径/脏标/保存钮照旧),但动作交给宿主 io
245
- const bind = (act, ioKey, fallback) => {
246
- this.root.querySelector(`[data-act="${act}"]`).addEventListener('click', () => {
247
- const hostAction = this.embed ? this.io?.[ioKey] : null;
248
- return hostAction ? hostAction() : fallback.call(this);
249
- });
250
- };
251
- bind('save', 'save', this.save);
252
- this.previewBtn.addEventListener('click', () => this.setPreview(!this.preview));
253
- this.fullscreenBtn.addEventListener('click', () => this.toggleFullscreen());
254
- this.onFullscreenEsc = (event) => {
255
- if (event.key !== 'Escape' || !this.pageFullscreen) return;
256
- // 菜单/弹窗开着时先交给它们自己关,别一按 Esc 就退出全屏
257
- if (document.querySelector('.gbd-menu, .gbd-modal-mask, .gbd-prompt, .gbrt-modal')) return;
258
- event.stopPropagation();
259
- this.setPageFullscreen(false);
260
- };
261
- this.autosaveEl.addEventListener('change', () => {
262
- const on = this.autosaveEl.checked;
263
- if (this.embed && this.io?.setAutosave) return this.io.setAutosave(on);
264
- this.prefs.autosave = on;
265
- savePrefs(this.prefs);
266
- });
267
- }
268
-
269
- /** 菜单栏(条目结构来自 docx/menus.js 的 buildMenus);只读档锁掉纯编辑类菜单 */
270
- buildChrome() {
271
- const menus = buildMenus(this.menuCtx());
272
- this.menubarHost.replaceChildren(buildMenuBar(menus, this.readOnly ? ['edit', 'insert', 'table', 'format'] : []));
273
- }
274
-
275
- /** 构造参数落 DOM:装配完成后才调用,此时工具栏/状态栏/查找栏都已就位 */
276
- applyMode() {
277
- this.setMenuBarVisible(this.menuBarVisible);
278
- if (this.readOnly) this.setReadOnly(true);
279
- }
280
-
281
- /** 显示/隐藏顶部菜单栏那一行;文件头、正文与状态栏不受影响 */
282
- setMenuBarVisible(on) {
283
- this.menuBarVisible = !!on;
284
- this.menubarHost.style.display = this.menuBarVisible ? '' : 'none';
285
- }
286
-
287
- /** 只读开关:内核档位、DOM 守卫、编辑控件与菜单可用性同一处切换 */
288
- setReadOnly(on) {
289
- this.readOnly = !!on;
290
- this.guard.setReadOnly(this.readOnly);
291
- this.setEditMode(this.readOnly ? 'readonly' : 'edit');
292
- this.statusBar.setReadOnly(this.readOnly);
293
- this.findBar.setReadOnly(this.readOnly);
294
- this.buildChrome();
295
- }
296
-
297
- bindEvents() {
298
- // 编辑器状态刷新 → 工具栏/状态栏
299
- const refresh = () => {
300
- this.editorState = this.editor.state();
301
- this.ribbon.refresh();
302
- this.statusBar.setCaret(this.editorState.line || 0, this.editorState.column || 0);
303
- };
304
- this.editor.on('state', refresh);
305
- this.editor.on('selection', refresh);
306
-
307
- // 快捷键(Ctrl/⌘ 组合走 wordShortcuts;Esc 关特殊字符浮盘)
308
- this.unbindKeys = useKeyboard({
309
- keydown: (e) => {
310
- // 嵌入模式:非激活页签不消费任何快捷键(多页签同页共存时键盘归属只看 active)
311
- if (this.isActive && !this.isActive()) return false;
312
- if (!e.ctrlKey && !e.metaKey) {
313
- if (e.key === 'Escape' && this.preview) {
314
- this.setPreview(false);
315
- return true;
316
- }
317
- if (e.key === 'Escape' && !this.charsPop.hidden) {
318
- this.charsPop.hidden = true;
319
- return true;
320
- }
321
- return false;
322
- }
323
- return runShortcut(e, this.shortcutCtx());
324
- },
325
- }, { priority: KEY_PRIORITY.WINDOW });
326
-
327
- // 滚动读数(可见页)
328
- const scroll = this.surface.scrollEl;
329
- scroll.addEventListener('scroll', () => this.refreshScroll(), { passive: true });
330
-
331
- // Ctrl/⌘+滚轮:以指针为锚缩放(编辑器用 CSS zoom,滚动量是内容本地像素)
332
- this.unbindWheel = bindCtrlWheelZoom({
333
- target: scroll,
334
- scrollEl: scroll,
335
- scrollMode: 'local',
336
- getScale: () => this.zoom / 100,
337
- zoomStep: (direction) => {
338
- const before = this.zoom;
339
- this.setZoom(before + direction * 10);
340
- return this.zoom !== before;
341
- },
342
- });
343
-
344
- // 编辑器右键菜单
345
- this.surface.contentEl.addEventListener('contextmenu', (e) => this.onContextMenu(e));
346
-
347
- // 图片异步加载 / 窗口宽度变化都会改正文高度 → 重排
348
- this.layoutObs = new ResizeObserver(() => this.schedulePaginate());
349
- this.layoutObs.observe(this.editor.root);
350
- this._onWinResize = () => this.schedulePaginate();
351
- window.addEventListener('resize', this._onWinResize);
352
-
353
- // 批注锚点 hover / 点击
354
- this.surface.contentEl.addEventListener('mouseover', (e) => this.onAnchorOver(e));
355
- this.surface.contentEl.addEventListener('mouseout', (e) => this.onAnchorOut(e));
356
- this.surface.contentEl.addEventListener('click', (e) => this.onAnchorClick(e));
357
- }
358
-
359
- /* ===================== 纸面 ctx(供 renderSheets) ===================== */
360
-
361
- onImportFile = async () => {
362
- const file = this.importInput.files?.[0];
363
- this.importInput.value = '';
364
- if (!file) return;
365
- if (!/\.docx$/i.test(file.name)) return notify.warning('只支持 .docx(旧版 .doc 请先用 Word 另存为 .docx)');
366
- if (this.dirty && !this.confirmDiscardSync('导入会替换当前编辑内容,未保存的修改将丢失。仍然导入?')) return;
367
- try {
368
- const bytes = new Uint8Array(await file.arrayBuffer());
369
- await this.applyDoc(bytes.length ? await parseDocx(bytes) : null);
370
- this.setDirty(true);
371
- notify.success(`已导入 ${file.name}——保存将写入当前文档`);
372
- } catch (err) {
373
- notify.error(`导入失败:${err.message || err}`);
374
- }
375
- };
376
-
377
- /* ===================== 编辑动作 ===================== */
378
-
379
- async selfTest() {
380
- // 覆盖全部「模型承诺过」的往返口径:批注/脚注/尾注锚点、首页不同页眉、奇偶页、表格与标题
381
- const html = '<h1>标题一</h1><p>正文 <strong>加粗</strong> 与 <em>斜体</em>'
382
- + ' <span class="doc-comment" data-cmt="c1">批注锚</span>'
383
- + '<sup class="doc-footnote" data-fn="fn1">1</sup><sup class="doc-endnote" data-fn="en1">1</sup></p>'
384
- + '<table><tbody><tr><td><p>A</p></td><td><p>B</p></td></tr></tbody></table>';
385
- const model = {
386
- html,
387
- sections: [{
388
- type: '',
389
- page: this.state.page,
390
- hfMode: 'except-first',
391
- header: '页眉',
392
- footer: '',
393
- headerFirst: '首页页眉',
394
- footerFirst: '',
395
- pageNumbers: { enabled: true, align: 'center', format: 'arabic', start: 2 },
396
- watermark: { data: '', color: '#AEB5C0', size: 120, opacity: 0.3 },
397
- }],
398
- comments: [{ key: 'c1', text: '批注文本', author: '我', date: '2025-01-01T00:00:00' }],
399
- footnotes: [{ id: 'fn1', text: '脚注文本' }],
400
- endnotes: [{ id: 'en1', text: '尾注文本' }],
401
- props: null,
402
- defaultTabStop: 720,
403
- compressPunctuation: false,
404
- carry: [],
405
- };
406
- const bytes = await buildDocxVerified(model);
407
- const back = await parseDocx(bytes);
408
- return {
409
- bytes: bytes.length,
410
- backHtmlLength: (back.html || '').length,
411
- hasTitle: /标题一/.test(back.html || ''),
412
- hasBold: /<strong|<b\b/i.test(back.html || ''),
413
- hasTable: /<table/i.test(back.html || ''),
414
- hasCommentAnchor: /data-cmt="0"/.test(back.html || ''),
415
- hasFootnoteAnchor: /data-fn="fn1"/.test(back.html || ''),
416
- hasEndnoteAnchor: /data-fn="en1"/.test(back.html || ''),
417
- sections: (back.sections || []).length,
418
- comments: (back.comments || []).length,
419
- footnotes: (back.footnotes || []).length,
420
- endnotes: (back.endnotes || []).length,
421
- hfMode: (back.sections || [])[0]?.hfMode || '',
422
- header: (back.sections || [])[0]?.header || '',
423
- headerFirst: (back.sections || [])[0]?.headerFirst || '',
424
- };
425
- }
426
-
427
- /* ===================== 启动 ===================== */
428
-
429
- async start() {
430
- this.applyView();
431
- this.renderHead();
432
- if (this.embed) return;
433
- await this.applyDoc(null);
434
- notify.info(this.readOnly ? 'gbdocx 已就绪:只读预览' : 'gbdocx 已就绪:可直接编辑,或用「打开」载入 .docx');
435
- }
436
-
437
- destroy() {
438
- // 全屏中的 .word-scope 挂着 body:先归还原位,再随挂载点一起移除
439
- if (this.pageFullscreen) this.setPageFullscreen(false);
440
- this.unbindKeys?.();
441
- this.unbindWheel?.();
442
- this.layoutObs?.disconnect();
443
- window.removeEventListener('resize', this._onWinResize);
444
- clearTimeout(this.pageTimer);
445
- clearTimeout(this._autoTimer);
446
- clearTimeout(this._peekTimer);
447
- cancelAnimationFrame(this.pageRaf);
448
- // 菜单/浮层挂 body:宿主卸载后不收,会留下悬空浮层与 document 监听
449
- closeAll();
450
- document.removeEventListener('keydown', this.onFullscreenEsc, true);
451
- this.guard.destroy();
452
- this.surface.destroy();
453
- this.scopeEl?.remove();
454
- }
455
- }
456
-
457
- Object.assign(
458
- WordApp.prototype,
459
- layoutMethods,
460
- docMethods,
461
- fileMethods,
462
- editMethods,
463
- catalogMethods,
464
- commentsMethods,
465
- notesMethods,
466
- hfMethods,
467
- viewMethods,
468
- menusMethods
469
- );
1
+ // [文件] gbdocx·WordApp —— docx 编辑器应用装配(几何/分页/批注/脚注/目录/页眉页脚带/菜单/快捷键)
2
+ //
3
+ // [设计] 本文件只留「装配 + 骨架 + 生命周期 + 自检」;其余职责拆到 ./word/*:
4
+ // layout(几何与分页)/ doc(文档状态)/ file(文件动作)/ edit(编辑动作)/ catalog(目录)/
5
+ // comments(批注)/ notes(脚注尾注)/ hf(页眉页脚带)/ view(视图与对话框)/ menus(右键菜单与快捷键)。
6
+ // 各模块导出方法组,由文件末尾 Object.assign 装配到 WordApp.prototype —— 同一个 this、同一套调用,
7
+ // 外部拿到的 WordApp 形状与拆分前完全一致。
8
+ // [坑] 装配必须在实例化之前完成:Object.assign 在模块求值时执行,而实例只能在 import 之后 new。
9
+
10
+ import { EditorSurface } from '../surface/editor-surface.js';
11
+ import { bindCtrlWheelZoom, createReadOnlyGuard } from 'guabiutils';
12
+ import { createOfficeHead } from 'gbofficeui/head';
13
+ import { parseDocx } from '../kernel/docx/codec/docx.js';
14
+ import { buildDocxVerified } from '../kernel/docx/codec/roundtrip.js';
15
+ import { runShortcut } from '../kernel/docx/wordShortcuts.js';
16
+ import { buildMenus } from '../kernel/docx/menus.js';
17
+ import { HF_MODES, defaultPageConf, defaultPageNumbers, defaultWatermark } from '../kernel/docx/constants.js';
18
+ import { notify } from '../kernel/notify.js';
19
+ import { useKeyboard, KEY_PRIORITY } from '../kernel/keyboard.js';
20
+ import { buildMenuBar } from '../ui/menubar.js';
21
+ import { closeAll } from '../ui/popup.js';
22
+ import { buildRibbon } from '../ui/ribbon.js';
23
+ import { icon } from '../ui/icons.js';
24
+ import { StatusBar } from '../ui/statusbar.js';
25
+ import { CatalogPanel, CommentsPanel } from '../ui/panels.js';
26
+ import { PromptPopover } from '../ui/prompt.js';
27
+ import { FindBar } from '../ui/find-bar.js';
28
+ import { buildSpecialChars } from '../ui/special-chars.js';
29
+ import { openColumnDialog, openMarginDialog } from '../ui/dialogs.js';
30
+ import { renderSheets } from './word-sheets.js';
31
+ import { loadPrefs, savePrefs } from './word/shared.js';
32
+ import { layoutMethods } from './word/layout.js';
33
+ import { docMethods } from './word/doc.js';
34
+ import { fileMethods } from './word/file.js';
35
+ import { editMethods } from './word/edit.js';
36
+ import { catalogMethods } from './word/catalog.js';
37
+ import { commentsMethods } from './word/comments.js';
38
+ import { notesMethods } from './word/notes.js';
39
+ import { hfMethods } from './word/hf.js';
40
+ import { viewMethods } from './word/view.js';
41
+ import { menusMethods } from './word/menus.js';
42
+
43
+ export class WordApp {
44
+ /**
45
+ * @param {HTMLElement} mount 已挂在文档里的挂载点
46
+ * @param {object} [options] embed=嵌入宿主;io=文件动作;onDirty/isActive=脏态与快捷键闸门;
47
+ * readOnly=只读(禁写且锁编辑控件);hideMenuBar=隐藏顶部菜单栏那一行
48
+ */
49
+ constructor(mount, options = {}) {
50
+ this.mount = mount;
51
+ this.embed = !!options.embed;
52
+ this.readOnly = !!options.readOnly;
53
+ this.menuBarVisible = !options.hideMenuBar;
54
+ this.io = options.io || null;
55
+ this.onDirty = typeof options.onDirty === 'function' ? options.onDirty : null;
56
+ this.isActive = typeof options.isActive === 'function' ? options.isActive : null;
57
+ this.doc = { name: '新建文档', handle: null };
58
+ this.state = {
59
+ sections: [],
60
+ page: defaultPageConf(),
61
+ pageNumbers: defaultPageNumbers(),
62
+ watermark: defaultWatermark(),
63
+ hfMode: HF_MODES[0].value,
64
+ header: '',
65
+ footer: '',
66
+ headerEven: '',
67
+ footerEven: '',
68
+ headerFirst: '',
69
+ footerFirst: '',
70
+ footnotes: [],
71
+ endnotes: [],
72
+ props: null,
73
+ defaultTabStop: 720,
74
+ compressPunctuation: false,
75
+ carry: [],
76
+ losses: [],
77
+ };
78
+ this.comments = [];
79
+ this.catalog = [];
80
+ /** 本次载入的「保存必丢」清单是否已由用户确认(自动保存不得绕过确认静默丢内容) */
81
+ this.lossAck = false;
82
+ this.lossAutoWarned = false;
83
+ this.footnotePages = new Map();
84
+ this.fnHeights = [];
85
+ this.pageCount = 1;
86
+ this.visiblePage = 1;
87
+ this.editMode = 'edit';
88
+ this.preview = false;
89
+ this.previewRestore = null;
90
+ this.pageFullscreen = false;
91
+ this.dirty = false;
92
+ this.saving = false;
93
+ this.suggestionCount = 0;
94
+ this.activeCommentKey = '';
95
+ this.bandEditSlot = '';
96
+ this.prefs = loadPrefs();
97
+ this.zoom = this.prefs.zoom || 100;
98
+ this.flags = this.prefs.flags || { catalog: false, commentsPanel: false };
99
+ this.lastEmittedHtml = '';
100
+ this.pageTimer = 0;
101
+ this.pageRaf = 0;
102
+ // [坑] 编辑器内核在 mount 时即抛一次 update(构造期),此时状态栏/工具栏尚未装配:
103
+ // 事件接线在构造完成前一律静默,避免读到未定义的宿主成员
104
+ this.ready = false;
105
+ this.build();
106
+ }
107
+
108
+ /* ===================== 几何读取 ===================== */
109
+
110
+ build() {
111
+ // [设计] 所有样式收在 .word-scope 下(本包 CSS 已按该前缀作用域化),宿主落地时不污染同页其它编辑器
112
+ const scope = document.createElement('div');
113
+ // 应用作用域:需要撑满宿主(.word-app 的 height:100% 以它为基准);浮层的 .word-scope 不挂这个类
114
+ scope.className = 'word-scope word-scope--app';
115
+ const root = document.createElement('div');
116
+ root.className = 'word-app word-skin';
117
+ if (this.embed) root.classList.add('gbd-is-embed');
118
+ root.innerHTML = `
119
+ <div class="word-head-host"></div>
120
+ <div class="gbd-menubar-host"></div>
121
+ <div class="gbd-toolbar-host"></div>
122
+ <div class="word-main">
123
+ <div class="word-editor"><div class="word-editor-mount"></div></div>
124
+ </div>
125
+ <div class="gbd-statusbar-host"></div>`;
126
+ scope.appendChild(root);
127
+ this.mount.appendChild(scope);
128
+ this.scopeEl = scope;
129
+ this.root = root;
130
+ // 文档头骨架来自 gbofficeui(标题 / 重命名 / 保存 / 下载 / 预览 / 全屏 三家同一套)
131
+ const dirtyEl = document.createElement('span');
132
+ dirtyEl.className = 'word-head__dirty';
133
+ dirtyEl.hidden = true;
134
+ dirtyEl.textContent = '●';
135
+ this.head = createOfficeHead({
136
+ className: 'word-head',
137
+ icon,
138
+ title: this.doc.name,
139
+ autoSave: this.autosaveOn(),
140
+ extra: [dirtyEl],
141
+ rename: this.canRename() ? { onClick: (event) => this.renameDoc(event) } : null,
142
+ download: this.canDownload() ? { onClick: () => this.downloadDoc() } : null,
143
+ onSave: () => {
144
+ const hostSave = this.embed ? this.io?.save : null;
145
+ return hostSave ? hostSave() : this.save();
146
+ },
147
+ onPreview: () => this.setPreview(!this.preview),
148
+ onFullscreen: () => this.toggleFullscreen(),
149
+ });
150
+ root.querySelector('.word-head-host').replaceWith(this.head.el);
151
+ this.menubarHost = root.querySelector('.gbd-menubar-host');
152
+ this.headEl = this.head.el;
153
+ this.toolbarHost = root.querySelector('.gbd-toolbar-host');
154
+ this.headActionsEl = this.head.actionsEl;
155
+ // 预览按钮不随只读被 inert:它要能在预览档里继续点「退出预览」
156
+ this.guard = createReadOnlyGuard(root, { editZones: () => [this.headActionsEl, this.toolbarHost] });
157
+ this.editorWrap = root.querySelector('.word-editor');
158
+ this.titleEl = this.head.titleEl;
159
+ this.pathEl = this.head.subEl;
160
+ this.dirtyEl = dirtyEl;
161
+ this.autosaveEl = this.head.autosaveEl;
162
+ this.previewBtn = this.head.previewBtn;
163
+ this.fullscreenBtn = this.head.fullscreenBtn;
164
+
165
+ this.catalogPanel = new CatalogPanel((key) => this.locateCatalog(key));
166
+ this.commentsPanel = new CommentsPanel({
167
+ locate: (key) => this.locateComment(key),
168
+ toggle: (key) => this.toggleComment(key),
169
+ remove: (key) => this.removeComment(key),
170
+ });
171
+
172
+ this.surface = new EditorSurface({
173
+ mount: root.querySelector('.word-editor-mount'),
174
+ placeholder: '开始输入正文…',
175
+ editable: true,
176
+ handlers: {
177
+ update: () => { if (this.ready) this.onDocUpdate(); },
178
+ 'open-find': () => this.findBar.open(),
179
+ 'request-link': () => this.insertLink(),
180
+ },
181
+ backdrop: (host) => renderSheets(host, this.sheetsCtx()),
182
+ });
183
+ this.editorState = this.editor.state();
184
+
185
+ // 选项卡栏(WPS 风格):tab 行 + 各页分组工具面板,完全接管原图标工具栏
186
+ this.ribbon = buildRibbon({
187
+ getState: () => ({ ...this.editorState, ...this.menuCtx().state }),
188
+ getCtx: () => this.menuCtx(),
189
+ isDisabled: () => this.editMode === 'readonly',
190
+ run: (name, ...args) => this.run(name, ...args),
191
+ actions: {
192
+ insertTable: (e) => this.openTableSpec(e),
193
+ insertImage: () => this.pickImage(),
194
+ insertLink: () => this.insertLink(),
195
+ },
196
+ find: (replace) => this.findBar.open(!!replace),
197
+ openMargin: () => this.openMarginDialog(),
198
+ openColumn: () => this.openColumnDialog(),
199
+ });
200
+ this.toolbarHost.appendChild(this.ribbon);
201
+
202
+ this.statusBar = new StatusBar({
203
+ onMode: (m) => this.setEditMode(m),
204
+ onZoomIn: () => this.setZoom(this.zoom + 10),
205
+ onZoomOut: () => this.setZoom(this.zoom - 10),
206
+ onZoomReset: () => this.setZoom(100),
207
+ onOpenMargin: () => this.openMarginDialog(),
208
+ onOpenColumn: () => this.openColumnDialog(),
209
+ });
210
+ root.querySelector('.gbd-statusbar-host').appendChild(this.statusBar.el);
211
+
212
+ this.findBar = new FindBar(() => this.editor);
213
+ root.querySelector('.word-editor').appendChild(this.findBar.el);
214
+
215
+ this.prompt = new PromptPopover();
216
+ this.prompt.onClosed = () => this.onPromptClosed();
217
+ // 重命名气泡另起一个实例:批注/脚注气泡的「取消回滚」语义与它无关
218
+ this.renamePrompt = new PromptPopover();
219
+
220
+ this.imageInput = document.createElement('input');
221
+ this.imageInput.type = 'file';
222
+ this.imageInput.accept = 'image/*';
223
+ this.imageInput.multiple = true;
224
+ this.imageInput.hidden = true;
225
+ this.imageInput.addEventListener('change', () => this.onImagePicked());
226
+ root.appendChild(this.imageInput);
227
+
228
+ this.importInput = document.createElement('input');
229
+ this.importInput.type = 'file';
230
+ this.importInput.accept = '.docx';
231
+ this.importInput.hidden = true;
232
+ this.importInput.addEventListener('change', () => this.onImportFile());
233
+ root.appendChild(this.importInput);
234
+
235
+ this.charsPop = document.createElement('div');
236
+ this.charsPop.className = 'word-chars-pop';
237
+ this.charsPop.hidden = true;
238
+ this.charsPop.appendChild(buildSpecialChars((ch) => this.run('insertText', ch)));
239
+ root.querySelector('.word-editor').appendChild(this.charsPop);
240
+
241
+ this.bindHead();
242
+ this.buildChrome();
243
+ this.bindEvents();
244
+ this.applyZoom();
245
+ this.ready = true;
246
+ this.applyMode();
247
+ }
248
+
249
+ get editor() {
250
+ return this.surface.editor;
251
+ }
252
+
253
+ /** 自动保存开关初值:嵌入模式读宿主,独立模式读本地偏好 */
254
+ autosaveOn() {
255
+ const io = this.io || {};
256
+ return typeof io.autosave === 'function' ? !!io.autosave() : !!this.prefs.autosave;
257
+ }
258
+
259
+ /** 文档头「重命名」是否可用:嵌入模式由宿主提供,独立模式走包内实现 */
260
+ canRename() {
261
+ return !this.embed || typeof this.io?.rename === 'function';
262
+ }
263
+
264
+ /** 文档头「下载」是否可用:嵌入模式由宿主提供,独立模式走包内实现 */
265
+ canDownload() {
266
+ return !this.embed || typeof this.io?.download === 'function';
267
+ }
268
+
269
+ bindHead() {
270
+ // 保存 / 预览 / 全屏的点击已由共享文档头(gbofficeui)接管,这里只挂文档头之外的交互
271
+ this.onFullscreenEsc = (event) => {
272
+ if (event.key !== 'Escape' || !this.pageFullscreen) return;
273
+ // 菜单/弹窗开着时先交给它们自己关,别一按 Esc 就退出全屏
274
+ if (document.querySelector('.gbd-menu, .gbd-modal-mask, .gbd-prompt, .gbrt-modal')) return;
275
+ event.stopPropagation();
276
+ this.setPageFullscreen(false);
277
+ };
278
+ this.autosaveEl.addEventListener('change', () => {
279
+ const on = this.autosaveEl.checked;
280
+ if (this.embed && this.io?.setAutosave) return this.io.setAutosave(on);
281
+ this.prefs.autosave = on;
282
+ savePrefs(this.prefs);
283
+ });
284
+ }
285
+
286
+ /** 菜单栏(条目结构来自 docx/menus.js 的 buildMenus);只读档锁掉纯编辑类菜单 */
287
+ buildChrome() {
288
+ const menus = buildMenus(this.menuCtx());
289
+ this.menubarHost.replaceChildren(buildMenuBar(menus, this.readOnly ? ['edit', 'insert', 'table', 'format'] : []));
290
+ }
291
+
292
+ /** 构造参数落 DOM:装配完成后才调用,此时工具栏/状态栏/查找栏都已就位 */
293
+ applyMode() {
294
+ this.setMenuBarVisible(this.menuBarVisible);
295
+ if (this.readOnly) this.setReadOnly(true);
296
+ }
297
+
298
+ /** 显示/隐藏顶部菜单栏那一行;文件头、正文与状态栏不受影响 */
299
+ setMenuBarVisible(on) {
300
+ this.menuBarVisible = !!on;
301
+ this.menubarHost.style.display = this.menuBarVisible ? '' : 'none';
302
+ }
303
+
304
+ /** 只读开关:内核档位、DOM 守卫、编辑控件与菜单可用性同一处切换 */
305
+ setReadOnly(on) {
306
+ this.readOnly = !!on;
307
+ this.guard.setReadOnly(this.readOnly);
308
+ this.setEditMode(this.readOnly ? 'readonly' : 'edit');
309
+ this.statusBar.setReadOnly(this.readOnly);
310
+ this.findBar.setReadOnly(this.readOnly);
311
+ this.buildChrome();
312
+ }
313
+
314
+ bindEvents() {
315
+ // 编辑器状态刷新 → 工具栏/状态栏
316
+ const refresh = () => {
317
+ this.editorState = this.editor.state();
318
+ this.ribbon.refresh();
319
+ this.statusBar.setCaret(this.editorState.line || 0, this.editorState.column || 0);
320
+ };
321
+ this.editor.on('state', refresh);
322
+ this.editor.on('selection', refresh);
323
+
324
+ // 快捷键(Ctrl/⌘ 组合走 wordShortcuts;Esc 关特殊字符浮盘)
325
+ this.unbindKeys = useKeyboard({
326
+ keydown: (e) => {
327
+ // 嵌入模式:非激活页签不消费任何快捷键(多页签同页共存时键盘归属只看 active)
328
+ if (this.isActive && !this.isActive()) return false;
329
+ if (!e.ctrlKey && !e.metaKey) {
330
+ if (e.key === 'Escape' && this.preview) {
331
+ this.setPreview(false);
332
+ return true;
333
+ }
334
+ if (e.key === 'Escape' && !this.charsPop.hidden) {
335
+ this.charsPop.hidden = true;
336
+ return true;
337
+ }
338
+ return false;
339
+ }
340
+ return runShortcut(e, this.shortcutCtx());
341
+ },
342
+ }, { priority: KEY_PRIORITY.WINDOW });
343
+
344
+ // 滚动读数(可见页)
345
+ const scroll = this.surface.scrollEl;
346
+ scroll.addEventListener('scroll', () => this.refreshScroll(), { passive: true });
347
+
348
+ // Ctrl/⌘+滚轮:以指针为锚缩放(编辑器用 CSS zoom,滚动量是内容本地像素)
349
+ this.unbindWheel = bindCtrlWheelZoom({
350
+ target: scroll,
351
+ scrollEl: scroll,
352
+ scrollMode: 'local',
353
+ getScale: () => this.zoom / 100,
354
+ zoomStep: (direction) => {
355
+ const before = this.zoom;
356
+ this.setZoom(before + direction * 10);
357
+ return this.zoom !== before;
358
+ },
359
+ });
360
+
361
+ // 编辑器右键菜单
362
+ this.surface.contentEl.addEventListener('contextmenu', (e) => this.onContextMenu(e));
363
+
364
+ // 图片异步加载 / 窗口宽度变化都会改正文高度 → 重排
365
+ this.layoutObs = new ResizeObserver(() => this.schedulePaginate());
366
+ this.layoutObs.observe(this.editor.root);
367
+ this._onWinResize = () => this.schedulePaginate();
368
+ window.addEventListener('resize', this._onWinResize);
369
+
370
+ // 批注锚点 hover / 点击
371
+ this.surface.contentEl.addEventListener('mouseover', (e) => this.onAnchorOver(e));
372
+ this.surface.contentEl.addEventListener('mouseout', (e) => this.onAnchorOut(e));
373
+ this.surface.contentEl.addEventListener('click', (e) => this.onAnchorClick(e));
374
+ }
375
+
376
+ /* ===================== 纸面 ctx(供 renderSheets) ===================== */
377
+
378
+ onImportFile = async () => {
379
+ const file = this.importInput.files?.[0];
380
+ this.importInput.value = '';
381
+ if (!file) return;
382
+ if (!/\.docx$/i.test(file.name)) return notify.warning('只支持 .docx(旧版 .doc 请先用 Word 另存为 .docx)');
383
+ if (this.dirty && !this.confirmDiscardSync('导入会替换当前编辑内容,未保存的修改将丢失。仍然导入?')) return;
384
+ try {
385
+ const bytes = new Uint8Array(await file.arrayBuffer());
386
+ await this.applyDoc(bytes.length ? await parseDocx(bytes) : null);
387
+ this.setDirty(true);
388
+ notify.success(`已导入 ${file.name}——保存将写入当前文档`);
389
+ } catch (err) {
390
+ notify.error(`导入失败:${err.message || err}`);
391
+ }
392
+ };
393
+
394
+ /* ===================== 编辑动作 ===================== */
395
+
396
+ async selfTest() {
397
+ // 覆盖全部「模型承诺过」的往返口径:批注/脚注/尾注锚点、首页不同页眉、奇偶页、表格与标题
398
+ const html = '<h1>标题一</h1><p>正文 <strong>加粗</strong> 与 <em>斜体</em>'
399
+ + ' <span class="doc-comment" data-cmt="c1">批注锚</span>'
400
+ + '<sup class="doc-footnote" data-fn="fn1">1</sup><sup class="doc-endnote" data-fn="en1">1</sup></p>'
401
+ + '<table><tbody><tr><td><p>A</p></td><td><p>B</p></td></tr></tbody></table>';
402
+ const model = {
403
+ html,
404
+ sections: [{
405
+ type: '',
406
+ page: this.state.page,
407
+ hfMode: 'except-first',
408
+ header: '页眉',
409
+ footer: '',
410
+ headerFirst: '首页页眉',
411
+ footerFirst: '',
412
+ pageNumbers: { enabled: true, align: 'center', format: 'arabic', start: 2 },
413
+ watermark: { data: '', color: '#AEB5C0', size: 120, opacity: 0.3 },
414
+ }],
415
+ comments: [{ key: 'c1', text: '批注文本', author: '我', date: '2025-01-01T00:00:00' }],
416
+ footnotes: [{ id: 'fn1', text: '脚注文本' }],
417
+ endnotes: [{ id: 'en1', text: '尾注文本' }],
418
+ props: null,
419
+ defaultTabStop: 720,
420
+ compressPunctuation: false,
421
+ carry: [],
422
+ };
423
+ const bytes = await buildDocxVerified(model);
424
+ const back = await parseDocx(bytes);
425
+ return {
426
+ bytes: bytes.length,
427
+ backHtmlLength: (back.html || '').length,
428
+ hasTitle: /标题一/.test(back.html || ''),
429
+ hasBold: /<strong|<b\b/i.test(back.html || ''),
430
+ hasTable: /<table/i.test(back.html || ''),
431
+ hasCommentAnchor: /data-cmt="0"/.test(back.html || ''),
432
+ hasFootnoteAnchor: /data-fn="fn1"/.test(back.html || ''),
433
+ hasEndnoteAnchor: /data-fn="en1"/.test(back.html || ''),
434
+ sections: (back.sections || []).length,
435
+ comments: (back.comments || []).length,
436
+ footnotes: (back.footnotes || []).length,
437
+ endnotes: (back.endnotes || []).length,
438
+ hfMode: (back.sections || [])[0]?.hfMode || '',
439
+ header: (back.sections || [])[0]?.header || '',
440
+ headerFirst: (back.sections || [])[0]?.headerFirst || '',
441
+ };
442
+ }
443
+
444
+ /* ===================== 启动 ===================== */
445
+
446
+ async start() {
447
+ this.applyView();
448
+ this.renderHead();
449
+ if (this.embed) return;
450
+ await this.applyDoc(null);
451
+ notify.info(this.readOnly ? 'gbdocx 已就绪:只读预览' : 'gbdocx 已就绪:可直接编辑,或用「打开」载入 .docx');
452
+ }
453
+
454
+ destroy() {
455
+ // 全屏中的 .word-scope 挂着 body:先归还原位,再随挂载点一起移除
456
+ if (this.pageFullscreen) this.setPageFullscreen(false);
457
+ this.unbindKeys?.();
458
+ this.unbindWheel?.();
459
+ this.layoutObs?.disconnect();
460
+ window.removeEventListener('resize', this._onWinResize);
461
+ clearTimeout(this.pageTimer);
462
+ clearTimeout(this._autoTimer);
463
+ clearTimeout(this._peekTimer);
464
+ cancelAnimationFrame(this.pageRaf);
465
+ // 菜单/浮层挂 body:宿主卸载后不收,会留下悬空浮层与 document 监听
466
+ closeAll();
467
+ document.removeEventListener('keydown', this.onFullscreenEsc, true);
468
+ this.guard.destroy();
469
+ this.surface.destroy();
470
+ this.scopeEl?.remove();
471
+ }
472
+ }
473
+
474
+ Object.assign(
475
+ WordApp.prototype,
476
+ layoutMethods,
477
+ docMethods,
478
+ fileMethods,
479
+ editMethods,
480
+ catalogMethods,
481
+ commentsMethods,
482
+ notesMethods,
483
+ hfMethods,
484
+ viewMethods,
485
+ menusMethods
486
+ );