@a200888213/gbdocx 0.0.0-stage → 0.3.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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +205 -2
  3. package/index.html +24 -0
  4. package/package.json +47 -6
  5. package/serve.mjs +20 -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 +152 -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 +88 -0
  19. package/src/app/word-app.js +440 -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 +121 -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 +208 -0
  50. package/src/kernel/editor/engine/commands.js +180 -0
  51. package/src/kernel/editor/engine/dom.js +622 -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 +371 -0
  66. package/src/kernel/editor/engine/tableMenu.js +250 -0
  67. package/src/kernel/editor/engine/tableOps.js +178 -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 +469 -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 +36 -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/special-chars.js +39 -0
  90. package/src/ui/statusbar.js +81 -0
  91. package/src/ui/toolbar.js +199 -0
  92. package/styles/app.css +944 -0
  93. package/styles/editor-content.css +440 -0
  94. package/styles/tokens.css +154 -0
  95. package/styles/word-panel.css +450 -0
@@ -0,0 +1,113 @@
1
+ // [文件] gbdocx·word·doc —— 文档状态 —— 应用/读取当前文档、脏标记与自动保存
2
+
3
+ // [设计] 方法以独立函数导出,由 word-app.js 末尾 Object.assign 装配到 WordApp.prototype:
4
+ // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
+
6
+ import { cleanHfHtml } from '../../kernel/docx/codec/helpers.js';
7
+ import { resetPagination } from '../../kernel/docx/pagination.js';
8
+ import { HF_MODES, defaultPageConf, defaultPageNumbers, defaultWatermark } from '../../kernel/docx/constants.js';
9
+ import { DOC_CLASS } from '../../kernel/editor/engine/schema.js';
10
+ import { countRevisions } from '../../kernel/editor/engine/revision.js';
11
+ function onDocUpdate() {
12
+ this.setDirty(true);
13
+ // 嵌入模式:自动保存归宿主(宿主自己排期与写盘),包内不按文件句柄自动保存
14
+ if (!this.embed && this.prefs.autosave) this.scheduleAutosave();
15
+ const root = this.editor?.root;
16
+ this.statusBar.setWords((root?.textContent || '').replace(/\s+/g, '').length);
17
+ this.suggestionCount = countRevisions(root);
18
+ this.statusBar.setSuggestions(this.suggestionCount);
19
+ if (this.flags.catalog) this.refreshCatalog();
20
+ this.schedulePaginate();
21
+ }
22
+
23
+ function setDirty(on) {
24
+ this.dirty = on;
25
+ if (this.dirtyEl) this.dirtyEl.hidden = !on;
26
+ this.statusBar?.setDirty(on, this.saving);
27
+ // 嵌入模式:脏态回调宿主(页签脏标与自动保存排期由宿主决定)
28
+ this.onDirty?.(on);
29
+ }
30
+
31
+ function scheduleAutosave() {
32
+ clearTimeout(this._autoTimer);
33
+ this._autoTimer = setTimeout(() => {
34
+ if (this.dirty && this.doc.handle) this.save(true);
35
+ }, 2000);
36
+ }
37
+
38
+ function applyDoc(model) {
39
+ const s = this.state;
40
+ const list = Array.isArray(model?.sections) ? model.sections : [];
41
+ s.sections = list;
42
+ const base = list[list.length - 1] || {};
43
+ s.page = { ...defaultPageConf(), ...(base.page || {}) };
44
+ s.hfMode = base.hfMode || HF_MODES[0].value;
45
+ s.header = cleanHfHtml(base.header || '');
46
+ s.footer = cleanHfHtml(base.footer || '');
47
+ s.headerEven = cleanHfHtml(base.headerEven || '');
48
+ s.footerEven = cleanHfHtml(base.footerEven || '');
49
+ s.headerFirst = cleanHfHtml(base.headerFirst || '');
50
+ s.footerFirst = cleanHfHtml(base.footerFirst || '');
51
+ s.pageNumbers = { ...defaultPageNumbers(), ...(base.pageNumbers || {}) };
52
+ s.watermark = { ...defaultWatermark(), ...(base.watermark || {}) };
53
+ s.footnotes = model?.footnotes || [];
54
+ s.endnotes = model?.endnotes || [];
55
+ s.props = model?.props || null;
56
+ s.defaultTabStop = model?.defaultTabStop > 0 ? model.defaultTabStop : 720;
57
+ // 标点挤压是排版设置:存回去时得带着,否则保存一次版式就回退(每行少一个字、整篇多一页)
58
+ s.compressPunctuation = model?.compressPunctuation === true;
59
+ s.carry = model?.carry || [];
60
+ s.losses = model?.losses || [];
61
+ this.lossAck = false;
62
+ this.lossAutoWarned = false;
63
+ this.comments = model?.comments || [];
64
+ this.activeCommentKey = '';
65
+ this.surface.setHTML(model?.html?.trim() ? model.html : '<p><br></p>');
66
+ this.renumberFootnotes();
67
+ const ed = this.editor;
68
+ if (ed?.root) ed.quietly(() => resetPagination(ed.root));
69
+ this.setEditMode(this.editMode);
70
+ this.setDirty(false);
71
+ this.refreshStats();
72
+ this.paginate();
73
+ this.renderPanels();
74
+ this.renderHead();
75
+ }
76
+
77
+ function currentDoc() {
78
+ const s = this.state;
79
+ const base = {
80
+ type: s.sections[s.sections.length - 1]?.type || '',
81
+ page: s.page,
82
+ header: s.header,
83
+ footer: s.footer,
84
+ headerEven: s.headerEven,
85
+ footerEven: s.footerEven,
86
+ headerFirst: s.headerFirst,
87
+ footerFirst: s.footerFirst,
88
+ hfMode: s.hfMode,
89
+ pageNumbers: s.pageNumbers,
90
+ watermark: s.watermark,
91
+ };
92
+ const list = s.sections.slice(0, -1);
93
+ list.push(base);
94
+ return {
95
+ html: this.surface.flush() ?? '',
96
+ sections: list,
97
+ comments: this.comments,
98
+ footnotes: s.footnotes,
99
+ endnotes: s.endnotes,
100
+ props: s.props,
101
+ defaultTabStop: s.defaultTabStop,
102
+ compressPunctuation: s.compressPunctuation === true,
103
+ carry: s.carry,
104
+ };
105
+ }
106
+
107
+ function hasContent(raw) {
108
+ const probe = document.createElement('div');
109
+ probe.innerHTML = raw || '';
110
+ return Boolean(probe.textContent.trim() || probe.querySelector(`img,table,hr,.${DOC_CLASS.PAGEBREAK}`));
111
+ }
112
+
113
+ export const docMethods = { onDocUpdate, setDirty, scheduleAutosave, applyDoc, currentDoc, hasContent };
@@ -0,0 +1,72 @@
1
+ // [文件] gbdocx·word·edit —— 编辑动作 —— 命令执行、编辑模式、统计、图片/链接/表格插入
2
+
3
+ // [设计] 方法以独立函数导出,由 word-app.js 末尾 Object.assign 装配到 WordApp.prototype:
4
+ // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
+
6
+ import { countRevisions } from '../../kernel/editor/engine/revision.js';
7
+ import { notify } from '../../kernel/notify.js';
8
+ import { openMenu } from '../../ui/context-menu.js';
9
+ function run(name, ...args) {
10
+ const ed = this.editor;
11
+ if (!ed || ed.destroyed || this.editMode === 'readonly') return false;
12
+ ed.focus();
13
+ return ed.exec(name, ...args);
14
+ }
15
+
16
+ function setEditMode(mode) {
17
+ this.editMode = mode;
18
+ this.surface.setEditable(mode !== 'readonly');
19
+ this.surface.setSuggesting(mode === 'suggest');
20
+ this.statusBar.setMode(mode);
21
+ this.toolbar.refresh();
22
+ }
23
+
24
+ function refreshStats() {
25
+ const root = this.editor?.root;
26
+ this.statusBar.setWords((root?.textContent || '').replace(/\s+/g, '').length);
27
+ this.suggestionCount = countRevisions(root);
28
+ this.statusBar.setSuggestions(this.suggestionCount);
29
+ if (this.flags.catalog) this.refreshCatalog();
30
+ }
31
+
32
+ function pickImage() {
33
+ if (this.editMode === 'readonly') return;
34
+ this.imageInput.click();
35
+ }
36
+
37
+ function onImagePicked() {
38
+ const files = Array.from(this.imageInput.files || []);
39
+ this.imageInput.value = '';
40
+ if (!files.length) return;
41
+ this.editor?.focus();
42
+ this.surface.insertImages(files);
43
+ }
44
+
45
+ function insertLink() {
46
+ if (this.editMode === 'readonly') return;
47
+ if (!this.editorState.hasSelection) return notify.warning('请先选择要加链接的文字');
48
+ this.editor.focus();
49
+ this.prompt.openAt(this.titleEl, {
50
+ title: '链接地址',
51
+ placeholder: 'https://…(留空取消链接)',
52
+ maxlength: 500,
53
+ required: false,
54
+ submit: (value) => {
55
+ if (this.run('setLink', value)) return true;
56
+ notify.warning('链接地址仅支持 http/https/mailto/tel/ftp 协议');
57
+ return false;
58
+ },
59
+ });
60
+ }
61
+
62
+ function openTableSpec(e) {
63
+ if (this.editMode === 'readonly') return;
64
+ const anchor = e?.currentTarget || e?.target || this.toolbar;
65
+ openMenu({
66
+ anchor,
67
+ items: [2, 3, 4, 5].map((n) => ({ label: `${n} × ${n} 表格`, onClick: () => this.run('insertTable', { rows: n, cols: n, withHeaderRow: true }) })),
68
+ placement: 'bottom-start',
69
+ });
70
+ }
71
+
72
+ export const editMethods = { run, setEditMode, refreshStats, pickImage, onImagePicked, insertLink, openTableSpec };
@@ -0,0 +1,162 @@
1
+ // [文件] gbdocx·word·file —— 文件动作 —— 新建/打开/保存/另存/导出/打印/丢弃确认
2
+
3
+ // [设计] 方法以独立函数导出,由 word-app.js 末尾 Object.assign 装配到 WordApp.prototype:
4
+ // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
+
6
+ import { downloadBlob } from 'guabiutils';
7
+ import { parseDocx } from '../../kernel/docx/codec/docx.js';
8
+ import { buildDocxVerified } from '../../kernel/docx/codec/roundtrip.js';
9
+ import { docToMarkdown } from '../../kernel/docx/codec/markdown.js';
10
+ import { lossText } from '../../kernel/docx/codec/losses.js';
11
+ import { notify } from '../../kernel/notify.js';
12
+ import { openDocx, saveDocx, saveDocxAs, ensureExt, DOCX_MIME } from '.././file-io.js';
13
+ import { MD_MIME } from './shared.js';
14
+ async function openFile() {
15
+ try {
16
+ const picked = await openDocx();
17
+ if (!picked) return;
18
+ if (this.dirty && !(await this.confirmDiscard('当前文档有未保存的修改,打开将丢弃这些修改。'))) return;
19
+ const bytes = picked.bytes;
20
+ this.doc = { name: picked.name, handle: picked.handle };
21
+ await this.applyDoc(bytes.length ? await parseDocx(bytes) : null);
22
+ notify.success(`已打开 ${picked.name}`);
23
+ } catch (err) {
24
+ notify.error(`打开失败:${err.message || err}`);
25
+ }
26
+ }
27
+
28
+ function newDoc() {
29
+ const start = async () => {
30
+ this.doc = { name: '新建文档', handle: null };
31
+ await this.applyDoc(null);
32
+ notify.info('已新建空白文档');
33
+ };
34
+ if (this.dirty && !this.confirmDiscardSync('当前文档有未保存的修改,新建将丢弃这些修改。')) return;
35
+ start();
36
+ }
37
+
38
+ async function confirmDiscard(message) {
39
+ return this.confirmDiscardSync(message);
40
+ }
41
+
42
+ function confirmDiscardSync(message) {
43
+ return window.confirm(`${message}\n\n确定继续吗?`);
44
+ }
45
+
46
+ async function save(silent = false) {
47
+ const model = this.currentDoc();
48
+ if (!this.hasContent(model.html)) {
49
+ if (!silent) notify.warning('正文为空,未保存');
50
+ return false;
51
+ }
52
+ if (!(await this.ensureLossAck({ silent }))) return false;
53
+ if (!this.doc.handle) {
54
+ return this.saveAs();
55
+ }
56
+ this.saving = true;
57
+ this.statusBar.setDirty(this.dirty, true);
58
+ try {
59
+ const bytes = await buildDocxVerified(model);
60
+ await saveDocx(bytes, this.doc.name, this.doc.handle);
61
+ this.setDirty(false);
62
+ if (!silent) notify.success('已保存');
63
+ return true;
64
+ } catch (err) {
65
+ notify.error(`保存失败:${err.message || err}`);
66
+ return false;
67
+ } finally {
68
+ this.saving = false;
69
+ this.statusBar.setDirty(this.dirty, false);
70
+ }
71
+ }
72
+
73
+ async function saveAs() {
74
+ const model = this.currentDoc();
75
+ if (!this.hasContent(model.html)) {
76
+ notify.warning('正文为空,未另存');
77
+ return false;
78
+ }
79
+ if (!(await this.ensureLossAck())) return false;
80
+ try {
81
+ const bytes = await buildDocxVerified(model);
82
+ const result = await saveDocxAs(bytes, this.doc.name);
83
+ if (!result.saved) return false;
84
+ if (result.handle) this.doc = { name: result.name || this.doc.name, handle: result.handle };
85
+ else this.doc = { name: result.name || this.doc.name, handle: null };
86
+ this.setDirty(false);
87
+ this.renderHead();
88
+ notify.success('已另存为');
89
+ return true;
90
+ } catch (err) {
91
+ notify.error(`另存失败:${err.message || err}`);
92
+ return false;
93
+ }
94
+ }
95
+
96
+ async function confirmLoss() {
97
+ const msg = `该文档含有编辑器不支持的内容,保存后将丢失:${lossText(this.state.losses)}。`;
98
+ if (this.io?.confirmLoss) return this.io.confirmLoss(msg);
99
+ return window.confirm(msg);
100
+ }
101
+
102
+ /** 嵌入模式:宿主给字节即装载(name/pathText 只用于标题与路径展示,落点由宿主持有) */
103
+ async function loadBytes(bytes, name = '文档.docx', pathText = '') {
104
+ this.doc = { name, handle: null, pathText };
105
+ await this.applyDoc(bytes?.length ? await parseDocx(bytes) : null);
106
+ }
107
+
108
+ /** 嵌入模式:保存前统一出口——空文/丢失确认都过,返回 null 表示宿主不该写盘 */
109
+ async function buildBytes() {
110
+ const model = this.currentDoc();
111
+ if (!this.hasContent(model.html)) return null;
112
+ if (!(await this.ensureLossAck())) return null;
113
+ return buildDocxVerified(model);
114
+ }
115
+
116
+ /** 嵌入模式:Markdown 导出内容(宿主自己决定下载/落盘) */
117
+ function buildMarkdown() {
118
+ return docToMarkdown(this.currentDoc());
119
+ }
120
+
121
+ async function ensureLossAck({ silent = false } = {}) {
122
+ if (!this.state.losses.length || this.lossAck) return true;
123
+ if (silent) {
124
+ if (!this.lossAutoWarned) {
125
+ this.lossAutoWarned = true;
126
+ notify.warning('当前文档含有编辑器不支持的内容,自动保存已暂停;请手动保存并确认丢失清单');
127
+ }
128
+ return false;
129
+ }
130
+ if (!(await this.confirmLoss())) return false;
131
+ this.lossAck = true;
132
+ return true;
133
+ }
134
+
135
+ async function exportDocx() {
136
+ const model = this.currentDoc();
137
+ if (!this.hasContent(model.html)) return notify.warning('正文为空,未导出');
138
+ if (!(await this.ensureLossAck())) return false;
139
+ try {
140
+ const bytes = await buildDocxVerified(model);
141
+ downloadBlob(new Blob([bytes], { type: DOCX_MIME }), ensureExt(this.doc.name, '.docx'));
142
+ } catch (err) {
143
+ notify.error(`导出失败:${err.message || err}`);
144
+ }
145
+ }
146
+
147
+ function exportMarkdown() {
148
+ const model = this.currentDoc();
149
+ if (!this.hasContent(model.html)) return notify.warning('正文为空,未导出');
150
+ try {
151
+ downloadBlob(new Blob([docToMarkdown(model)], { type: MD_MIME }), ensureExt(this.doc.name, '.md'));
152
+ } catch (err) {
153
+ notify.error(`导出失败:${err.message || err}`);
154
+ }
155
+ }
156
+
157
+ function print() {
158
+ this.findBar.close();
159
+ window.print();
160
+ }
161
+
162
+ export const fileMethods = { openFile, newDoc, confirmDiscard, confirmDiscardSync, save, saveAs, confirmLoss, ensureLossAck, exportDocx, exportMarkdown, print, loadBytes, buildBytes, buildMarkdown };
@@ -0,0 +1,76 @@
1
+ // [文件] gbdocx·word·hf —— 页眉页脚带 —— 槽位读写、显示、页码文案与就地编辑
2
+
3
+ // [设计] 方法以独立函数导出,由 word-app.js 末尾 Object.assign 装配到 WordApp.prototype:
4
+ // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
+
6
+ import { hfUsesEven, hfUsesFirst } from '../../kernel/docx/codec/docx.js';
7
+ import { cleanHfHtml } from '../../kernel/docx/codec/helpers.js';
8
+ import { pageNumberText as pageNumberTextOf } from '../../kernel/docx/pageGeometry.js';
9
+ function bandSlot(which, p) {
10
+ const mode = this.state.hfMode;
11
+ if (hfUsesFirst(mode) && p === 1) return which === 'header' ? 'headerFirst' : 'footerFirst';
12
+ const even = hfUsesEven(mode) && p % 2 === 0;
13
+ if (which === 'header') return even ? 'headerEven' : 'header';
14
+ return even ? 'footerEven' : 'footer';
15
+ }
16
+
17
+ function slotValue(slot) {
18
+ return this.state[slot] ?? '';
19
+ }
20
+
21
+ function hfTextAt(which, p) {
22
+ return this.slotValue(this.bandSlot(which, p));
23
+ }
24
+
25
+ function showHf(p, which) {
26
+ if (this.state.hfMode === 'none') return false;
27
+ const raw = String(this.hfTextAt(which, p));
28
+ return raw.replace(/<[^>]*>/g, '').trim() !== '' || /data-fld=/i.test(raw);
29
+ }
30
+
31
+ function showPageNumber(p) {
32
+ if (!this.state.pageNumbers.enabled || this.state.hfMode === 'none') return false;
33
+ if (hfUsesFirst(this.state.hfMode) && p === 1) return /data-fld="PAGE"/i.test(this.state.footerFirst || '');
34
+ return true;
35
+ }
36
+
37
+ function hfDisplayHtml(which, p) {
38
+ const raw = this.hfTextAt(which, p);
39
+ if (!raw) return '';
40
+ return String(raw).replace(/<span[^>]*data-fld="(PAGE|NUMPAGES|SECTIONPAGES)"[^>]*><\/span>/gi, (_, kind) => {
41
+ if (kind.toUpperCase() === 'PAGE') return this.pageNumberText(p);
42
+ return String(this.pageCount);
43
+ });
44
+ }
45
+
46
+ function pageNumberText(p) {
47
+ const { format, start } = this.state.pageNumbers;
48
+ // 文案口径(阿拉伯/中文/「- 1 -」短横)只在 pageGeometry 里实现一份,页面浮层与页脚域共用
49
+ return pageNumberTextOf(p, format, start);
50
+ }
51
+
52
+ function startEditBand(slot, el) {
53
+ if (this.editMode === 'readonly') return;
54
+ this.bandEditSlot = slot;
55
+ el.contentEditable = 'true';
56
+ el.classList.add('gbd-is-editing');
57
+ requestAnimationFrame(() => el.focus());
58
+ }
59
+
60
+ function commitBand() {
61
+ const slot = this.bandEditSlot;
62
+ this.bandEditSlot = '';
63
+ if (!slot) return;
64
+ const el = this.root.querySelector('.word-sheet-hf.gbd-is-editing');
65
+ if (el) {
66
+ const clean = cleanHfHtml(el.innerHTML);
67
+ if (clean !== this.slotValue(slot)) {
68
+ this.state[slot] = clean;
69
+ if ((clean.replace(/<[^>]*>/g, '').trim()) && this.state.hfMode === 'none') this.state.hfMode = 'all';
70
+ this.onDocUpdate();
71
+ }
72
+ }
73
+ this.renderBackdrop();
74
+ }
75
+
76
+ export const hfMethods = { bandSlot, slotValue, hfTextAt, showHf, showPageNumber, hfDisplayHtml, pageNumberText, startEditBand, commitBand };
@@ -0,0 +1,152 @@
1
+ // [文件] gbdocx·word·layout —— 页面几何与分页 —— 缩放、纸张层、页眉页脚带测量、滚动读数
2
+
3
+ // [设计] 方法以独立函数导出,由 word-app.js 末尾 Object.assign 装配到 WordApp.prototype:
4
+ // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
+
6
+ import { pageGeometry, layoutOf, GUTTER, fromSheetTop, pageNumberStyle, bandStyle, sheetStyle } from '../../kernel/docx/pageGeometry.js';
7
+ import { repaginate } from '../../kernel/docx/pagination.js';
8
+ import { savePrefs } from './shared.js';
9
+ function geo() { return pageGeometry(this.state.page); }
10
+
11
+ function layout() { return layoutOf(this.geo()); }
12
+
13
+ function sheetsCtx() {
14
+ return {
15
+ geo: () => this.geo(),
16
+ layout: () => this.layout(),
17
+ pageCount: () => this.pageCount,
18
+ pageNumbers: () => this.state.pageNumbers,
19
+ watermark: () => this.state.watermark,
20
+ endnotes: () => this.state.endnotes,
21
+ fnHeights: () => this.fnHeights,
22
+ bandEdit: () => this.bandEditSlot,
23
+ pageNumberText: (p) => this.pageNumberText(p),
24
+ fnPageOf: (p) => this.footnotePages.get(p) || [],
25
+ sheetStyleOf: (p) => sheetStyle(p, this.layout()),
26
+ hfBandStyle: (p, which) => bandStyle(p, which, this.geo(), this.layout(), { head: 0, foot: 0 }),
27
+ pageNumStyle: (p) => pageNumberStyle(p, this.geo(), this.layout(), this.state.pageNumbers.align),
28
+ fnBandStyle: (p) => {
29
+ const L = this.layout();
30
+ const h = this.fnHeights[p - 1] || 0;
31
+ return { top: fromSheetTop(p, L.padTop + L.availOf() - h, L), left: `${L.padLeft}px`, right: `${L.padRight}px` };
32
+ },
33
+ enBandStyle: () => {
34
+ const L = this.layout();
35
+ const p = this.pageCount;
36
+ const h = this.fnHeights[p - 1] || 0;
37
+ return { top: fromSheetTop(p, L.padTop + L.availOf() - h, L), left: `${L.padLeft}px`, right: `${L.padRight}px`, transform: 'translateY(-100%)' };
38
+ },
39
+ bandSlot: (which, p) => this.bandSlot(which, p),
40
+ hfDisplayHtml: (which, p) => this.hfDisplayHtml(which, p),
41
+ showHf: (p, which) => this.showHf(p, which),
42
+ showPageNumber: (p) => this.showPageNumber(p),
43
+ footerHasPageField: (p) => /data-fld="PAGE"/i.test(this.hfTextAt('footer', p)),
44
+ onBandDblClick: (slot, el) => this.startEditBand(slot, el),
45
+ onBandCommit: () => this.commitBand(),
46
+ onFootnoteDblClick: (fn) => this.editFootnote(fn),
47
+ onEndnoteDblClick: (en) => this.editEndnote(en),
48
+ zoom: () => this.zoom,
49
+ };
50
+ }
51
+
52
+ function applyEditorGeometry() {
53
+ const geo = this.geo();
54
+ const layout = this.layout();
55
+ this.editorWrap.style.zoom = String(this.zoom / 100);
56
+ const style = {
57
+ '--gbd-re-content-w': `${geo.w}mm`,
58
+ '--gbd-re-content-m': '0 auto',
59
+ '--gbd-re-content-pad': `${layout.padTop}px ${layout.padRight}px ${layout.padBottom}px ${layout.padLeft}px`,
60
+ '--gbd-re-content-min-h': `${this.pageCount * layout.pageH + Math.max(0, this.pageCount - 1) * GUTTER}px`,
61
+ };
62
+ for (const [k, v] of Object.entries(style)) this.editorWrap.style.setProperty(k, v);
63
+ }
64
+
65
+ function applyZoom() {
66
+ this.statusBar.setZoom(this.zoom);
67
+ this.applyEditorGeometry();
68
+ this.schedulePaginate();
69
+ }
70
+
71
+ function setZoom(z) {
72
+ this.zoom = Math.max(40, Math.min(300, Math.round(z)));
73
+ this.prefs.zoom = this.zoom;
74
+ savePrefs(this.prefs);
75
+ this.applyZoom();
76
+ }
77
+
78
+ function paginate() {
79
+ const ed = this.editor;
80
+ const root = ed?.root;
81
+ if (!root || ed.composing) return;
82
+ const L = this.layout();
83
+ const opts = {
84
+ cellsPerPage: L.cols,
85
+ gapOf: L.padTop + L.padBottom,
86
+ gutter: GUTTER,
87
+ padTop: L.padTop,
88
+ colW: L.colW,
89
+ colGap: L.colGap,
90
+ colSeparator: this.geo().colSeparator,
91
+ padLeft: L.padLeft,
92
+ padRight: L.padRight,
93
+ scale: this.zoom / 100,
94
+ };
95
+ ed.quietly(() => {
96
+ this.pageCount = repaginate(root, { ...opts, cellH: L.availOf() });
97
+ });
98
+ this.refreshFootnotePages();
99
+ this.renderBackdrop();
100
+ if (this.state.footnotes.length === 0) {
101
+ this.fnHeights = [];
102
+ return;
103
+ }
104
+ requestAnimationFrame(() => {
105
+ const hs = this.measureFnBands();
106
+ this.fnHeights = hs;
107
+ if (!hs.some((h) => h > 0)) {
108
+ this.renderBackdrop();
109
+ return;
110
+ }
111
+ ed.quietly(() => {
112
+ this.pageCount = repaginate(root, { ...opts, cellH: (p) => Math.max(60, L.availOf() - (hs[p - 1] || 0)) });
113
+ });
114
+ this.refreshFootnotePages();
115
+ this.renderBackdrop();
116
+ });
117
+ }
118
+
119
+ function schedulePaginate() {
120
+ clearTimeout(this.pageTimer);
121
+ cancelAnimationFrame(this.pageRaf);
122
+ this.pageTimer = setTimeout(() => {
123
+ this.pageRaf = requestAnimationFrame(() => this.paginate());
124
+ }, 120);
125
+ }
126
+
127
+ function renderBackdrop() {
128
+ this.surface.refreshBackdrop();
129
+ this.applyEditorGeometry();
130
+ this.refreshScroll();
131
+ this.statusBar.setPage(this.visiblePage, this.pageCount);
132
+ }
133
+
134
+ function measureFnBands() {
135
+ const scale = this.zoom / 100 || 1;
136
+ const out = [];
137
+ for (const el of this.root.querySelectorAll('.word-sheet-fn[data-page]')) {
138
+ const p = Number(el.dataset.page);
139
+ if (p > 0) out[p - 1] = el.getBoundingClientRect().height / scale;
140
+ }
141
+ return out;
142
+ }
143
+
144
+ function refreshScroll() {
145
+ const pageH = this.layout().pageH;
146
+ if (!pageH) return;
147
+ const step = pageH + GUTTER;
148
+ this.visiblePage = Math.max(1, Math.min(this.pageCount, Math.floor(this.surface.scrollEl.scrollTop / step) + 1));
149
+ this.statusBar.setPage(this.visiblePage, this.pageCount);
150
+ }
151
+
152
+ export const layoutMethods = { geo, layout, sheetsCtx, applyEditorGeometry, applyZoom, setZoom, paginate, schedulePaginate, renderBackdrop, measureFnBands, refreshScroll };