@a200888213/gbdocx 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/package.json +1 -1
  2. package/src/app/file-io.js +122 -122
  3. package/src/app/main.js +9 -9
  4. package/src/app/word/catalog.js +52 -52
  5. package/src/app/word/comments.js +112 -112
  6. package/src/app/word/doc.js +113 -113
  7. package/src/app/word/edit.js +72 -72
  8. package/src/app/word/hf.js +76 -76
  9. package/src/app/word/layout.js +155 -155
  10. package/src/app/word/notes.js +110 -110
  11. package/src/app/word/shared.js +22 -22
  12. package/src/app/word/view.js +3 -0
  13. package/src/app/word-app.js +1 -0
  14. package/src/app/word-sheets.js +101 -101
  15. package/src/kernel/docx/codec/blocks.js +123 -123
  16. package/src/kernel/docx/codec/carry.js +129 -129
  17. package/src/kernel/docx/codec/comments.js +25 -25
  18. package/src/kernel/docx/codec/docx.js +198 -198
  19. package/src/kernel/docx/codec/docxStyles.js +177 -177
  20. package/src/kernel/docx/codec/fonts.js +195 -195
  21. package/src/kernel/docx/codec/helpers.js +161 -161
  22. package/src/kernel/docx/codec/hfHtml.js +152 -152
  23. package/src/kernel/docx/codec/html.js +739 -739
  24. package/src/kernel/docx/codec/losses.js +420 -420
  25. package/src/kernel/docx/codec/markdown.js +170 -170
  26. package/src/kernel/docx/codec/parts.js +249 -249
  27. package/src/kernel/docx/codec/read.js +603 -603
  28. package/src/kernel/docx/codec/render.js +1156 -1156
  29. package/src/kernel/docx/codec/roundtrip.js +236 -236
  30. package/src/kernel/docx/codec/write.js +833 -833
  31. package/src/kernel/docx/comments.js +14 -14
  32. package/src/kernel/docx/pageGeometry.js +123 -123
  33. package/src/kernel/docx/pagination.js +481 -481
  34. package/src/kernel/docx/watermark.js +45 -45
  35. package/src/kernel/editor/constants.js +8 -8
  36. package/src/kernel/editor/engine/blocks.js +594 -594
  37. package/src/kernel/editor/engine/blocksEnter.js +109 -109
  38. package/src/kernel/editor/engine/blocksInsert.js +254 -254
  39. package/src/kernel/editor/engine/blocksStructure.js +226 -226
  40. package/src/kernel/editor/engine/commands.js +181 -181
  41. package/src/kernel/editor/engine/dom.js +646 -646
  42. package/src/kernel/editor/engine/history.js +149 -149
  43. package/src/kernel/editor/engine/inline.js +656 -656
  44. package/src/kernel/editor/engine/input.js +554 -554
  45. package/src/kernel/editor/engine/interaction.js +137 -137
  46. package/src/kernel/editor/engine/pointer.js +39 -39
  47. package/src/kernel/editor/engine/revision.js +138 -138
  48. package/src/kernel/editor/engine/schema.js +417 -417
  49. package/src/kernel/editor/engine/selection.js +119 -119
  50. package/src/kernel/editor/engine/state.js +118 -118
  51. package/src/kernel/editor/engine/tableClip.js +154 -154
  52. package/src/kernel/editor/engine/tableGrid.js +55 -55
  53. package/src/kernel/editor/engine/tableInteraction.js +388 -388
  54. package/src/kernel/editor/engine/tableMenu.js +250 -250
  55. package/src/kernel/editor/engine/tableOps.js +174 -174
  56. package/src/kernel/editor/engine/tables.js +732 -732
  57. package/src/kernel/editor/overlayGeometry.js +20 -20
  58. package/src/kernel/editor/utils.js +48 -48
  59. package/src/kernel/keyboard.js +114 -114
  60. package/src/kernel/textStyles.js +84 -84
  61. package/src/kernel/util/imageFile.js +91 -91
  62. package/src/kernel/util/shortcutKey.js +33 -33
  63. package/src/surface/editor-surface.js +600 -600
  64. package/src/ui/color-panel.js +69 -69
  65. package/src/ui/context-menu.js +133 -133
  66. package/src/ui/find-bar.js +151 -151
  67. package/src/ui/menubar.js +28 -28
  68. package/src/ui/panels.js +115 -115
  69. package/src/ui/prompt.js +89 -89
  70. package/src/ui/ribbon.js +485 -485
  71. package/src/ui/special-chars.js +39 -39
  72. package/src/ui/statusbar.js +81 -81
  73. package/src/ui/toolbar.js +32 -32
  74. package/styles/editor-content.css +440 -440
  75. package/styles/tokens.css +154 -154
  76. package/styles/word-panel.css +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a200888213/gbdocx",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "挂逼文档:独立 .docx 编辑器(内核移植自 guabi office/docx 编解码 + 自研 contenteditable 编辑器内核,UI 用原生 HTML 重写),只依赖 gbooxml。",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,122 +1,122 @@
1
- // [文件] gbdocx·文件读写 —— 打开 / 保存 / 另存为(优先 File System Access API,回退 input[type=file] + 下载)
2
-
3
- import { downloadBlob, ensureExt as ensureExtWith } from 'guabiutils';
4
-
5
- export const DOCX_MIME = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
6
-
7
- /** 跨源子框架:浏览器的 File System Access API 在跨源 iframe 里直接抛 SecurityError。
8
- * [坑] 只判断函数是否存在会掉进这个坑:工作台把演示页放在另一个端口的 iframe 里,
9
- * showOpenFilePicker 存在但一调就失败,必须提前识别并走 input/下载回退 */
10
- export const isCrossOriginFrame = (win = window) => {
11
- if (!win || win.self === win.top) return false;
12
- try {
13
- // 同源可读父窗口 location;跨源访问抛 SecurityError
14
- void win.top.location.href;
15
- return false;
16
- } catch {
17
- return true;
18
- }
19
- };
20
-
21
- /** 是否可用文件系统访问 API(Chromium 且非跨源子框架) */
22
- export const hasFsAccess = (win = window) => typeof win.showOpenFilePicker === 'function' && !isCrossOriginFrame(win);
23
-
24
- /**
25
- * 打开 .docx:返回 { name, bytes, handle|null };用户取消返回 null
26
- */
27
- export async function openDocx() {
28
- if (hasFsAccess()) {
29
- let picked = null;
30
- try {
31
- picked = await window.showOpenFilePicker({
32
- types: [{ description: 'Word 文档', accept: { [DOCX_MIME]: ['.docx'] } }],
33
- multiple: false,
34
- });
35
- } catch (err) {
36
- // 取消是正常返回;其余(含策略/环境的 SecurityError)退回 input 选择,别把打开流程卡死
37
- if (err?.name === 'AbortError') return null;
38
- }
39
- const handle = picked?.[0] || null;
40
- if (handle) {
41
- const file = await handle.getFile();
42
- return { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()), handle };
43
- }
44
- }
45
- const file = await pickViaInput();
46
- if (!file) return null;
47
- return { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()), handle: null };
48
- }
49
-
50
- /** 回退路径:隐藏 input 选文件(取消选择时用 cancel/focus 兜底结束,避免 Promise 永挂) */
51
- function pickViaInput() {
52
- return new Promise((resolve) => {
53
- const input = document.createElement('input');
54
- input.type = 'file';
55
- input.accept = '.docx';
56
- let settled = false;
57
- const done = (file) => {
58
- if (settled) return;
59
- settled = true;
60
- window.removeEventListener('focus', onFocus);
61
- resolve(file);
62
- };
63
- // 部分浏览器取消选择不派发任何事件:对话框关闭后窗口重新聚焦,稍等再看有没有文件
64
- const onFocus = () => {
65
- setTimeout(() => { if (!input.files?.length) done(null); }, 300);
66
- };
67
- input.addEventListener('change', () => done(input.files?.[0] || null), { once: true });
68
- input.addEventListener('cancel', () => done(null), { once: true });
69
- window.addEventListener('focus', onFocus, { once: true });
70
- input.click();
71
- });
72
- }
73
-
74
- /** 写入已知句柄:write 失败时中止流,避免半截文件与未关闭的 writable 泄漏 */
75
- async function writeHandle(handle, bytes) {
76
- const writable = await handle.createWritable();
77
- try {
78
- await writable.write(bytes);
79
- } catch (err) {
80
- await writable.abort?.().catch(() => {});
81
- throw err;
82
- }
83
- await writable.close();
84
- }
85
-
86
- /**
87
- * 保存到已知句柄(无句柄则触发下载);返回 { saved:boolean, handle }
88
- */
89
- export async function saveDocx(bytes, name, handle) {
90
- if (handle?.createWritable) {
91
- await writeHandle(handle, bytes);
92
- return { saved: true, handle };
93
- }
94
- downloadBlob(new Blob([bytes], { type: DOCX_MIME }), ensureExt(name, '.docx'));
95
- return { saved: true, handle: null };
96
- }
97
-
98
- /** 另存为:优先系统保存对话框,回退下载;返回 { saved, handle, name } */
99
- export async function saveDocxAs(bytes, name) {
100
- const suggested = ensureExt(name, '.docx');
101
- if (typeof window.showSaveFilePicker === 'function' && !isCrossOriginFrame()) {
102
- let handle = null;
103
- try {
104
- handle = await window.showSaveFilePicker({
105
- suggestedName: suggested,
106
- types: [{ description: 'Word 文档', accept: { [DOCX_MIME]: ['.docx'] } }],
107
- });
108
- } catch (err) {
109
- if (err?.name === 'AbortError') return { saved: false, handle: null, name: suggested };
110
- // 跨源框架/策略拒绝:回退下载
111
- }
112
- if (handle) {
113
- await writeHandle(handle, bytes);
114
- return { saved: true, handle, name: handle.name || suggested };
115
- }
116
- }
117
- downloadBlob(new Blob([bytes], { type: DOCX_MIME }), suggested);
118
- return { saved: true, handle: null, name: suggested };
119
- }
120
-
121
- /** 文件名兜底扩展名(空名用「新建文档」) */
122
- export const ensureExt = (name, ext) => ensureExtWith(name, ext, '新建文档');
1
+ // [文件] gbdocx·文件读写 —— 打开 / 保存 / 另存为(优先 File System Access API,回退 input[type=file] + 下载)
2
+
3
+ import { downloadBlob, ensureExt as ensureExtWith } from 'guabiutils';
4
+
5
+ export const DOCX_MIME = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
6
+
7
+ /** 跨源子框架:浏览器的 File System Access API 在跨源 iframe 里直接抛 SecurityError。
8
+ * [坑] 只判断函数是否存在会掉进这个坑:工作台把演示页放在另一个端口的 iframe 里,
9
+ * showOpenFilePicker 存在但一调就失败,必须提前识别并走 input/下载回退 */
10
+ export const isCrossOriginFrame = (win = window) => {
11
+ if (!win || win.self === win.top) return false;
12
+ try {
13
+ // 同源可读父窗口 location;跨源访问抛 SecurityError
14
+ void win.top.location.href;
15
+ return false;
16
+ } catch {
17
+ return true;
18
+ }
19
+ };
20
+
21
+ /** 是否可用文件系统访问 API(Chromium 且非跨源子框架) */
22
+ export const hasFsAccess = (win = window) => typeof win.showOpenFilePicker === 'function' && !isCrossOriginFrame(win);
23
+
24
+ /**
25
+ * 打开 .docx:返回 { name, bytes, handle|null };用户取消返回 null
26
+ */
27
+ export async function openDocx() {
28
+ if (hasFsAccess()) {
29
+ let picked = null;
30
+ try {
31
+ picked = await window.showOpenFilePicker({
32
+ types: [{ description: 'Word 文档', accept: { [DOCX_MIME]: ['.docx'] } }],
33
+ multiple: false,
34
+ });
35
+ } catch (err) {
36
+ // 取消是正常返回;其余(含策略/环境的 SecurityError)退回 input 选择,别把打开流程卡死
37
+ if (err?.name === 'AbortError') return null;
38
+ }
39
+ const handle = picked?.[0] || null;
40
+ if (handle) {
41
+ const file = await handle.getFile();
42
+ return { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()), handle };
43
+ }
44
+ }
45
+ const file = await pickViaInput();
46
+ if (!file) return null;
47
+ return { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()), handle: null };
48
+ }
49
+
50
+ /** 回退路径:隐藏 input 选文件(取消选择时用 cancel/focus 兜底结束,避免 Promise 永挂) */
51
+ function pickViaInput() {
52
+ return new Promise((resolve) => {
53
+ const input = document.createElement('input');
54
+ input.type = 'file';
55
+ input.accept = '.docx';
56
+ let settled = false;
57
+ const done = (file) => {
58
+ if (settled) return;
59
+ settled = true;
60
+ window.removeEventListener('focus', onFocus);
61
+ resolve(file);
62
+ };
63
+ // 部分浏览器取消选择不派发任何事件:对话框关闭后窗口重新聚焦,稍等再看有没有文件
64
+ const onFocus = () => {
65
+ setTimeout(() => { if (!input.files?.length) done(null); }, 300);
66
+ };
67
+ input.addEventListener('change', () => done(input.files?.[0] || null), { once: true });
68
+ input.addEventListener('cancel', () => done(null), { once: true });
69
+ window.addEventListener('focus', onFocus, { once: true });
70
+ input.click();
71
+ });
72
+ }
73
+
74
+ /** 写入已知句柄:write 失败时中止流,避免半截文件与未关闭的 writable 泄漏 */
75
+ async function writeHandle(handle, bytes) {
76
+ const writable = await handle.createWritable();
77
+ try {
78
+ await writable.write(bytes);
79
+ } catch (err) {
80
+ await writable.abort?.().catch(() => {});
81
+ throw err;
82
+ }
83
+ await writable.close();
84
+ }
85
+
86
+ /**
87
+ * 保存到已知句柄(无句柄则触发下载);返回 { saved:boolean, handle }
88
+ */
89
+ export async function saveDocx(bytes, name, handle) {
90
+ if (handle?.createWritable) {
91
+ await writeHandle(handle, bytes);
92
+ return { saved: true, handle };
93
+ }
94
+ downloadBlob(new Blob([bytes], { type: DOCX_MIME }), ensureExt(name, '.docx'));
95
+ return { saved: true, handle: null };
96
+ }
97
+
98
+ /** 另存为:优先系统保存对话框,回退下载;返回 { saved, handle, name } */
99
+ export async function saveDocxAs(bytes, name) {
100
+ const suggested = ensureExt(name, '.docx');
101
+ if (typeof window.showSaveFilePicker === 'function' && !isCrossOriginFrame()) {
102
+ let handle = null;
103
+ try {
104
+ handle = await window.showSaveFilePicker({
105
+ suggestedName: suggested,
106
+ types: [{ description: 'Word 文档', accept: { [DOCX_MIME]: ['.docx'] } }],
107
+ });
108
+ } catch (err) {
109
+ if (err?.name === 'AbortError') return { saved: false, handle: null, name: suggested };
110
+ // 跨源框架/策略拒绝:回退下载
111
+ }
112
+ if (handle) {
113
+ await writeHandle(handle, bytes);
114
+ return { saved: true, handle, name: handle.name || suggested };
115
+ }
116
+ }
117
+ downloadBlob(new Blob([bytes], { type: DOCX_MIME }), suggested);
118
+ return { saved: true, handle: null, name: suggested };
119
+ }
120
+
121
+ /** 文件名兜底扩展名(空名用「新建文档」) */
122
+ export const ensureExt = (name, ext) => ensureExtWith(name, ext, '新建文档');
package/src/app/main.js CHANGED
@@ -1,9 +1,9 @@
1
- // [文件] gbdocx·main —— 应用引导(装配 WordApp 到 #app)
2
- import { WordApp } from './word-app.js';
3
-
4
- const mount = document.getElementById('app');
5
- const app = new WordApp(mount);
6
- app.start();
7
-
8
- // 调试入口(控制台取内核实例做快速自检)
9
- window.gbdocx = app;
1
+ // [文件] gbdocx·main —— 应用引导(装配 WordApp 到 #app)
2
+ import { WordApp } from './word-app.js';
3
+
4
+ const mount = document.getElementById('app');
5
+ const app = new WordApp(mount);
6
+ app.start();
7
+
8
+ // 调试入口(控制台取内核实例做快速自检)
9
+ window.gbdocx = app;
@@ -1,52 +1,52 @@
1
- // [文件] gbdocx·word·catalog —— 目录 —— 采集、定位、插入与刷新
2
-
3
- // [设计] 方法以独立函数导出,由 word-app.js 末尾 Object.assign 装配到 WordApp.prototype:
4
- // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
-
6
- import { escapeHtml } from 'guabiutils';
7
- import { pageOfElement } from '../../kernel/docx/pagination.js';
8
- import { collectCatalog, gotoCatalogItem } from '../../kernel/docx/catalog.js';
9
- import { DOC_CLASS } from '../../kernel/editor/engine/schema.js';
10
- import { notify } from '../../kernel/notify.js';
11
- function refreshCatalog() {
12
- const items = collectCatalog(this.editor?.root || null);
13
- this.catalog = items;
14
- this.catalogPanel.setItems(items.map((it) => ({ key: it.key, text: it.text, level: it.level })));
15
- }
16
-
17
- function locateCatalog(key) {
18
- const item = this.catalog.find((c) => c.key === key);
19
- if (item) gotoCatalogItem({ value: this.catalog }, key);
20
- }
21
-
22
- function tocRowParas(items, root) {
23
- const innerW = Math.round(this.layout().innerW);
24
- return items
25
- .filter((it) => it.level <= 3)
26
- .map((it) => `<p style="white-space:pre-wrap;tab-size:${innerW}px;margin:0;">${escapeHtml(it.text)}\t${pageOfElement(root, it.el)}</p>`)
27
- .join('');
28
- }
29
-
30
- function insertToc() {
31
- const ed = this.editor;
32
- if (!ed || this.editMode === 'readonly') return;
33
- const items = collectCatalog(ed.root);
34
- const rows = items.length ? this.tocRowParas(items, ed.root) : '';
35
- if (!rows) return notify.warning('正文里还没有标题,先写几个标题再插目录');
36
- ed.focus();
37
- if (!this.run('insertHtml', `<div class="${DOC_CLASS.TOC}" contenteditable="false">${rows}</div>`)) notify.warning('请先把光标放进正文');
38
- this.onDocUpdate();
39
- }
40
-
41
- function refreshToc() {
42
- const root = this.editor?.root;
43
- const el = root?.querySelector(`.${DOC_CLASS.TOC}`);
44
- if (!root || !el || this.editMode === 'readonly') return notify.warning('文档里还没有目录');
45
- this.paginate();
46
- const rows = this.tocRowParas(collectCatalog(root), root);
47
- if (!rows) return;
48
- this.editor.run(() => { el.innerHTML = rows; });
49
- this.onDocUpdate();
50
- }
51
-
52
- export const catalogMethods = { refreshCatalog, locateCatalog, tocRowParas, insertToc, refreshToc };
1
+ // [文件] gbdocx·word·catalog —— 目录 —— 采集、定位、插入与刷新
2
+
3
+ // [设计] 方法以独立函数导出,由 word-app.js 末尾 Object.assign 装配到 WordApp.prototype:
4
+ // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
+
6
+ import { escapeHtml } from 'guabiutils';
7
+ import { pageOfElement } from '../../kernel/docx/pagination.js';
8
+ import { collectCatalog, gotoCatalogItem } from '../../kernel/docx/catalog.js';
9
+ import { DOC_CLASS } from '../../kernel/editor/engine/schema.js';
10
+ import { notify } from '../../kernel/notify.js';
11
+ function refreshCatalog() {
12
+ const items = collectCatalog(this.editor?.root || null);
13
+ this.catalog = items;
14
+ this.catalogPanel.setItems(items.map((it) => ({ key: it.key, text: it.text, level: it.level })));
15
+ }
16
+
17
+ function locateCatalog(key) {
18
+ const item = this.catalog.find((c) => c.key === key);
19
+ if (item) gotoCatalogItem({ value: this.catalog }, key);
20
+ }
21
+
22
+ function tocRowParas(items, root) {
23
+ const innerW = Math.round(this.layout().innerW);
24
+ return items
25
+ .filter((it) => it.level <= 3)
26
+ .map((it) => `<p style="white-space:pre-wrap;tab-size:${innerW}px;margin:0;">${escapeHtml(it.text)}\t${pageOfElement(root, it.el)}</p>`)
27
+ .join('');
28
+ }
29
+
30
+ function insertToc() {
31
+ const ed = this.editor;
32
+ if (!ed || this.editMode === 'readonly') return;
33
+ const items = collectCatalog(ed.root);
34
+ const rows = items.length ? this.tocRowParas(items, ed.root) : '';
35
+ if (!rows) return notify.warning('正文里还没有标题,先写几个标题再插目录');
36
+ ed.focus();
37
+ if (!this.run('insertHtml', `<div class="${DOC_CLASS.TOC}" contenteditable="false">${rows}</div>`)) notify.warning('请先把光标放进正文');
38
+ this.onDocUpdate();
39
+ }
40
+
41
+ function refreshToc() {
42
+ const root = this.editor?.root;
43
+ const el = root?.querySelector(`.${DOC_CLASS.TOC}`);
44
+ if (!root || !el || this.editMode === 'readonly') return notify.warning('文档里还没有目录');
45
+ this.paginate();
46
+ const rows = this.tocRowParas(collectCatalog(root), root);
47
+ if (!rows) return;
48
+ this.editor.run(() => { el.innerHTML = rows; });
49
+ this.onDocUpdate();
50
+ }
51
+
52
+ export const catalogMethods = { refreshCatalog, locateCatalog, tocRowParas, insertToc, refreshToc };
@@ -1,112 +1,112 @@
1
- // [文件] gbdocx·word·comments —— 批注 —— 插入/定位/开关/删除与悬停预览
2
-
3
- // [设计] 方法以独立函数导出,由 word-app.js 末尾 Object.assign 装配到 WordApp.prototype:
4
- // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
-
6
- import { genId } from 'guabiutils';
7
- import { commentTime } from '../../kernel/docx/comments.js';
8
- import { DOC_CLASS, COMMENT_ATTR } from '../../kernel/editor/engine/schema.js';
9
- import { notify } from '../../kernel/notify.js';
10
- import { openPopup } from '../../ui/popup.js';
11
- function insertComment() {
12
- if (this.editMode === 'readonly') return;
13
- if (!this.editor?.state().hasSelection) return notify.warning('请先选择要批注的文字');
14
- if (this._pendingCommentKey) {
15
- this.run('removeComment', this._pendingCommentKey);
16
- this._pendingCommentKey = '';
17
- }
18
- const key = genId('c');
19
- if (!this.run('setComment', key)) return notify.warning('请先选择要批注的文字');
20
- this._pendingCommentKey = key;
21
- const anchorEl = this.editor.root.querySelector(`.${DOC_CLASS.COMMENT}[${COMMENT_ATTR}="${key}"]`);
22
- this.prompt.openAt(anchorEl, {
23
- title: '批注内容',
24
- placeholder: '写下你的意见…',
25
- maxlength: 300,
26
- submit: (text) => {
27
- this._pendingCommentKey = '';
28
- this.comments = [...this.comments, { key, text, author: '我', date: new Date().toISOString().slice(0, 19), resolved: false }];
29
- this.activeCommentKey = key;
30
- this.setView('commentsPanel', true);
31
- this.renderPanels();
32
- this.onDocUpdate();
33
- return true;
34
- },
35
- });
36
- }
37
-
38
- function onPromptClosed() {
39
- const key = this._pendingCommentKey;
40
- this._pendingCommentKey = '';
41
- if (key) this.run('removeComment', key);
42
- this.rollbackPendingNote();
43
- }
44
-
45
- function locateComment(key) {
46
- this.activeCommentKey = key;
47
- if (this.commentsPanel) {
48
- this.commentsPanel.activeKey = key;
49
- this.commentsPanel.render();
50
- }
51
- this.editor.root.querySelector(`.${DOC_CLASS.COMMENT}[${COMMENT_ATTR}="${key}"]`)?.scrollIntoView({ block: 'center', behavior: 'smooth' });
52
- }
53
-
54
- function toggleComment(key) {
55
- this.comments = this.comments.map((c) => (c.key === key ? { ...c, resolved: !c.resolved } : c));
56
- this.renderPanels();
57
- this.onDocUpdate();
58
- }
59
-
60
- function removeComment(key) {
61
- this.run('removeComment', key);
62
- this.comments = this.comments.filter((c) => c.key !== key);
63
- if (this.activeCommentKey === key) this.activeCommentKey = '';
64
- this.renderPanels();
65
- this.onDocUpdate();
66
- }
67
-
68
- function onAnchorOver(e) {
69
- const target = e.target?.closest?.(`.${DOC_CLASS.COMMENT}`);
70
- if (!target) return;
71
- const key = target.getAttribute(COMMENT_ATTR);
72
- if (key === this._peekKey && this._peekHandle) return;
73
- const item = this.comments.find((c) => c.key === key);
74
- if (!item) return;
75
- clearTimeout(this._peekTimer);
76
- this.closePeek();
77
- const card = document.createElement('div');
78
- card.className = 'wd-cmt-peek';
79
- card.innerHTML = `<div class="wd-cmt-peek-meta"></div><div class="wd-cmt-peek-text"></div>`;
80
- card.querySelector('.wd-cmt-peek-meta').textContent = `${item.author || '匿名'} · ${commentTime(item.date)}${item.resolved ? ' · 已解决' : ''}`;
81
- card.querySelector('.wd-cmt-peek-text').textContent = item.text;
82
- card.addEventListener('mouseenter', () => clearTimeout(this._peekTimer));
83
- card.addEventListener('mouseleave', () => this.scheduleClosePeek());
84
- this._peekHandle = openPopup({ anchor: target.getBoundingClientRect(), content: card, placement: 'top-start', className: 'gbd-popup--peek' });
85
- this._peekKey = key;
86
- }
87
-
88
- function onAnchorOut(e) {
89
- if (e.relatedTarget?.closest?.(`.${DOC_CLASS.COMMENT}`)) return;
90
- this.scheduleClosePeek();
91
- }
92
-
93
- function scheduleClosePeek() {
94
- clearTimeout(this._peekTimer);
95
- this._peekTimer = setTimeout(() => this.closePeek(), 200);
96
- }
97
-
98
- function closePeek() {
99
- this._peekHandle?.close();
100
- this._peekHandle = null;
101
- this._peekKey = '';
102
- }
103
-
104
- function onAnchorClick(e) {
105
- const key = e.target?.closest?.(`.${DOC_CLASS.COMMENT}`)?.getAttribute(COMMENT_ATTR);
106
- if (!key) return;
107
- if (window.getSelection() && !window.getSelection().isCollapsed) return;
108
- this.setView('commentsPanel', true);
109
- this.locateComment(key);
110
- }
111
-
112
- export const commentsMethods = { insertComment, onPromptClosed, locateComment, toggleComment, removeComment, onAnchorOver, onAnchorOut, scheduleClosePeek, closePeek, onAnchorClick };
1
+ // [文件] gbdocx·word·comments —— 批注 —— 插入/定位/开关/删除与悬停预览
2
+
3
+ // [设计] 方法以独立函数导出,由 word-app.js 末尾 Object.assign 装配到 WordApp.prototype:
4
+ // 仍是同一个 this(方法调用时绑定),调用方形状与拆分前完全一致。
5
+
6
+ import { genId } from 'guabiutils';
7
+ import { commentTime } from '../../kernel/docx/comments.js';
8
+ import { DOC_CLASS, COMMENT_ATTR } from '../../kernel/editor/engine/schema.js';
9
+ import { notify } from '../../kernel/notify.js';
10
+ import { openPopup } from '../../ui/popup.js';
11
+ function insertComment() {
12
+ if (this.editMode === 'readonly') return;
13
+ if (!this.editor?.state().hasSelection) return notify.warning('请先选择要批注的文字');
14
+ if (this._pendingCommentKey) {
15
+ this.run('removeComment', this._pendingCommentKey);
16
+ this._pendingCommentKey = '';
17
+ }
18
+ const key = genId('c');
19
+ if (!this.run('setComment', key)) return notify.warning('请先选择要批注的文字');
20
+ this._pendingCommentKey = key;
21
+ const anchorEl = this.editor.root.querySelector(`.${DOC_CLASS.COMMENT}[${COMMENT_ATTR}="${key}"]`);
22
+ this.prompt.openAt(anchorEl, {
23
+ title: '批注内容',
24
+ placeholder: '写下你的意见…',
25
+ maxlength: 300,
26
+ submit: (text) => {
27
+ this._pendingCommentKey = '';
28
+ this.comments = [...this.comments, { key, text, author: '我', date: new Date().toISOString().slice(0, 19), resolved: false }];
29
+ this.activeCommentKey = key;
30
+ this.setView('commentsPanel', true);
31
+ this.renderPanels();
32
+ this.onDocUpdate();
33
+ return true;
34
+ },
35
+ });
36
+ }
37
+
38
+ function onPromptClosed() {
39
+ const key = this._pendingCommentKey;
40
+ this._pendingCommentKey = '';
41
+ if (key) this.run('removeComment', key);
42
+ this.rollbackPendingNote();
43
+ }
44
+
45
+ function locateComment(key) {
46
+ this.activeCommentKey = key;
47
+ if (this.commentsPanel) {
48
+ this.commentsPanel.activeKey = key;
49
+ this.commentsPanel.render();
50
+ }
51
+ this.editor.root.querySelector(`.${DOC_CLASS.COMMENT}[${COMMENT_ATTR}="${key}"]`)?.scrollIntoView({ block: 'center', behavior: 'smooth' });
52
+ }
53
+
54
+ function toggleComment(key) {
55
+ this.comments = this.comments.map((c) => (c.key === key ? { ...c, resolved: !c.resolved } : c));
56
+ this.renderPanels();
57
+ this.onDocUpdate();
58
+ }
59
+
60
+ function removeComment(key) {
61
+ this.run('removeComment', key);
62
+ this.comments = this.comments.filter((c) => c.key !== key);
63
+ if (this.activeCommentKey === key) this.activeCommentKey = '';
64
+ this.renderPanels();
65
+ this.onDocUpdate();
66
+ }
67
+
68
+ function onAnchorOver(e) {
69
+ const target = e.target?.closest?.(`.${DOC_CLASS.COMMENT}`);
70
+ if (!target) return;
71
+ const key = target.getAttribute(COMMENT_ATTR);
72
+ if (key === this._peekKey && this._peekHandle) return;
73
+ const item = this.comments.find((c) => c.key === key);
74
+ if (!item) return;
75
+ clearTimeout(this._peekTimer);
76
+ this.closePeek();
77
+ const card = document.createElement('div');
78
+ card.className = 'wd-cmt-peek';
79
+ card.innerHTML = `<div class="wd-cmt-peek-meta"></div><div class="wd-cmt-peek-text"></div>`;
80
+ card.querySelector('.wd-cmt-peek-meta').textContent = `${item.author || '匿名'} · ${commentTime(item.date)}${item.resolved ? ' · 已解决' : ''}`;
81
+ card.querySelector('.wd-cmt-peek-text').textContent = item.text;
82
+ card.addEventListener('mouseenter', () => clearTimeout(this._peekTimer));
83
+ card.addEventListener('mouseleave', () => this.scheduleClosePeek());
84
+ this._peekHandle = openPopup({ anchor: target.getBoundingClientRect(), content: card, placement: 'top-start', className: 'gbd-popup--peek' });
85
+ this._peekKey = key;
86
+ }
87
+
88
+ function onAnchorOut(e) {
89
+ if (e.relatedTarget?.closest?.(`.${DOC_CLASS.COMMENT}`)) return;
90
+ this.scheduleClosePeek();
91
+ }
92
+
93
+ function scheduleClosePeek() {
94
+ clearTimeout(this._peekTimer);
95
+ this._peekTimer = setTimeout(() => this.closePeek(), 200);
96
+ }
97
+
98
+ function closePeek() {
99
+ this._peekHandle?.close();
100
+ this._peekHandle = null;
101
+ this._peekKey = '';
102
+ }
103
+
104
+ function onAnchorClick(e) {
105
+ const key = e.target?.closest?.(`.${DOC_CLASS.COMMENT}`)?.getAttribute(COMMENT_ATTR);
106
+ if (!key) return;
107
+ if (window.getSelection() && !window.getSelection().isCollapsed) return;
108
+ this.setView('commentsPanel', true);
109
+ this.locateComment(key);
110
+ }
111
+
112
+ export const commentsMethods = { insertComment, onPromptClosed, locateComment, toggleComment, removeComment, onAnchorOver, onAnchorOut, scheduleClosePeek, closePeek, onAnchorClick };