@a200888213/gbdocx 0.0.0-stage → 0.4.0

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