@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 甲宁
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,207 @@
1
- # Temporary Holding Version
1
+ # @a200888213/gbdocx
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 独立 `.docx` 编辑器:**OOXML docx 编解码内核 + 自研 contenteditable 编辑器内核 + 原生 HTML 界面**。
4
+
5
+ 没有 React/Vue,没有 ProseMirror/TipTap,没有 CKEditor。整个包只依赖 [`gbooxml`](https://www.npmjs.com/package/gbooxml) 做 ZIP 与 XML,其余全部自持:`.docx` 双向编解码、以 DOM 为文档模型的编辑器内核、分页/页眉页脚/脚注尾注/批注/修订,以及菜单、工具栏、查找、颜色面板这一整套 UI。
6
+
7
+ ## 三层结构
8
+
9
+ | 层 | 入口 | 职责 |
10
+ | --- | --- | --- |
11
+ | 编解码 | `@a200888213/gbdocx/kernel/docx/codec/*` | `.docx` 字节 ⇄ 文档模型 ⇄ HTML |
12
+ | 编辑器内核 | `@a200888213/gbdocx/surface/editor-surface` | `EditorSurface` 承载 `EditorCore`:命令、状态快照、历史、表格、批注、修订 |
13
+ | 完整应用 | `@a200888213/gbdocx`(根入口) | `WordApp`:把上面两层装配成一个可用的 Word 界面 |
14
+
15
+ 只想做一个在线文档编辑器 → 用 `WordApp`;已有自己的界面、只要编辑内核 → 用 `EditorSurface`;只要读写文件、不要编辑器 → 用 codec。
16
+
17
+ ## 安装
18
+
19
+ ```bash
20
+ npm install @a200888213/gbdocx
21
+ ```
22
+
23
+ ## 样式隔离(0.3.0 起)
24
+
25
+ - CSS 自定义属性统一用包专属前缀 `--gbd-*`,类名统一用 `gbd-*` / `gbd-is-*`;四个 gb 包可同时挂在同一个宿主页面,不会互相覆盖,也不会撞上 Element Plus 的 `.is-*` 状态类。
26
+ - 页面级底座规则(`html,body` / `body` / `#app` / `*` / `button` / 滚动条)只挂在 `.gbd-root` 作用域内:**嵌入宿主时挂载点必须带 `gbd-root` 类**,否则字体、高度与盒模型底座不生效;宿主的 `body` / `#app` / 全局按钮不受任何影响。
27
+ - `:root` 的设计令牌保持全局可见(菜单与弹层会挂到 `body`),变量名已包专属;暗色令牌由 `[data-gbd-theme='dark']` 切换,不再被宿主的 `data-theme` 误触发。
28
+
29
+ ## 先把它跑起来
30
+
31
+ ```bash
32
+ npm start # node serve.mjs,默认 http://localhost:5273/
33
+ ```
34
+
35
+ `serve.mjs` 只是薄封装,静态服务器本体是 `guabiutils/dev-server`(三端共用同一份),端口可 `node serve.mjs 8080` 或用环境变量 `GBDOCX_PORT`。打开根路径即为完整编辑器,控制台里有 `window.gbdocx` 指向 `WordApp` 实例,可直接调 `await window.gbdocx.selfTest()` 做一次全链路自检。
36
+
37
+ 页面本身只有 `index.html`,它加载四个样式表(顺序有意义):`tokens.css` → `editor-content.css` → `word-panel.css` → `app.css`。自己装配页面时请全部引入,否则正文排版和面板都会走形。
38
+
39
+ `index.html` 里有一条 importmap,把裸标识符 `gbooxml` / `guabiutils` 映射到 `/vendor/*`,而 `serve.mjs` 把 `/vendor/gbooxml/*`、`/vendor/gbofficeui/*` 指向 `packages/gboffice/` 下的同级源码,把 `/vendor/guabiutils/*` 指向仓库的 `packages/guabiutils/src`。这意味着这个自带 demo 只在仓库的 monorepo 布局下能跑;从 npm 单独安装后要用 demo 页面,请自行把 `gbooxml` 映射到 `node_modules/gbooxml/src/index.js`,并按下方顺序引入四份样式(顶栏皮肤来自 `gbofficeui`)。
40
+
41
+ ## 嵌入到自己的页面
42
+
43
+ ```js
44
+ import { WordApp } from '@a200888213/gbdocx';
45
+ import '@a200888213/gbdocx/styles/tokens.css';
46
+ import '@a200888213/gbdocx/styles/editor-content.css';
47
+ import '@a200888213/gbdocx/styles/word-panel.css';
48
+ import '@a200888213/gbdocx/styles/app.css';
49
+ import 'gbofficeui/styles/office-chrome.css'; // 菜单栏/文档头/功能区/状态栏共享皮肤
50
+
51
+ const app = new WordApp(document.getElementById('app'));
52
+ await app.start();
53
+ ```
54
+
55
+ 第一个参数是一个**已经挂在文档里的 DOM 元素**,编辑器 UI 会 `appendChild` 进去;第二个参数是可选 options:`embed` / `io` / `onDirty` / `isActive` 用于嵌入宿主,`readOnly` / `hideMenuBar` 见下一节。实例方法:
56
+
57
+ ```js
58
+ app.setEditMode('readonly'); // 'edit' | 'suggest' | 'readonly'
59
+ app.setZoom(120); // 40–300,会持久化到 localStorage
60
+ app.setView('commentsPanel', true);
61
+ await app.saveAs(); // 另存为 .docx(优先 File System Access API,回落下载)
62
+ app.print();
63
+ app.destroy(); // 停观察器与定时器,但不会把 DOM 从挂载点摘掉
64
+ ```
65
+
66
+ `destroy()` 只解除副作用(ResizeObserver、window resize、分页与自动保存定时器),**不会**移除它自己插入的 DOM;要彻底回收请连挂载点子树一起删。
67
+
68
+ ## 只读与隐藏菜单栏
69
+
70
+ `@a200888213/gbdocx` / `gbxlxs` / `gbpptx` 三个编辑器用同一套开关(`guabiutils` 的 `createReadOnlyGuard` 提供 DOM 层守卫,各包自己接模型层闸门):
71
+
72
+ | 能力 | 构造参数 | 运行时方法 |
73
+ | --- | --- | --- |
74
+ | 只读预览 | `readOnly: true` | `app.setReadOnly(on)` |
75
+ | 隐藏顶部菜单栏那一行 | `hideMenuBar: true` | `app.setMenuBarVisible(on)` |
76
+
77
+ ```js
78
+ const app = new WordApp(mountEl, { embed: true, readOnly: true, hideMenuBar: true });
79
+ await app.start();
80
+
81
+ app.setReadOnly(false); // 回到可编辑
82
+ app.setMenuBarVisible(true); // 再显示菜单栏
83
+ ```
84
+
85
+ 只读档下:内核切到 `editMode='readonly'`(正文 `contenteditable` 关闭、`run()` 拒绝写命令),工具栏与文件头 `inert`,编辑/插入/表格/格式菜单禁用,状态栏的模式/页边距/分栏开关与查找栏的替换行一并锁定;选区、滚动、复制、查找、缩放、导出与打印仍可用。`hideMenuBar` 只隐藏 `.gbd-menubar-host` 那一行,下面的文件头与正文不受影响。
86
+
87
+ ## 只读写文件(codec)
88
+
89
+ ```js
90
+ import { parseDocx } from '@a200888213/gbdocx/kernel/docx/codec/docx';
91
+ import { buildDocxVerified } from '@a200888213/gbdocx/kernel/docx/codec/roundtrip';
92
+ import { docToMarkdown } from '@a200888213/gbdocx/kernel/docx/codec/markdown';
93
+ import { lossText } from '@a200888213/gbdocx/kernel/docx/codec/losses';
94
+
95
+ const doc = await parseDocx(bytes); // Uint8Array | ArrayBuffer → Promise<Document>
96
+ console.log(lossText(doc.losses)); // 这次打开丢掉了哪些原文特性
97
+ const back = await buildDocxVerified(doc); // Promise<Uint8Array>
98
+ const md = docToMarkdown(doc); // 同步返回字符串
99
+ ```
100
+
101
+ 文档模型就是 codec 与编辑器之间唯一的接口:
102
+
103
+ ```js
104
+ {
105
+ html: '<p>正文</p>', // 正文(编辑器的工作内容)
106
+ sections: [{
107
+ type: '', // 分节类型
108
+ page: { size: 'A4', orientation: 'portrait',
109
+ margins: { top: 25.4, right: 25.4, bottom: 25.4, left: 25.4 },
110
+ columns: 1, colGap: 8, colSeparator: false, headerTop: 0, footerBottom: 0 },
111
+ hfMode: 'all', header: '', footer: '', headerEven: '', footerEven: '', headerFirst: '', footerFirst: '',
112
+ pageNumbers: { enabled: false, align: 'center', format: 'arabic', start: 1 },
113
+ watermark: { data: '', color: '#AEB5C0', size: 120, opacity: 0.3 },
114
+ }],
115
+ comments: [], footnotes: [], endnotes: [],
116
+ props: null, // 标题/作者等文档属性
117
+ defaultTabStop: 720,
118
+ carry: [], // 整包透传的分节(主题、术语表、customXml…)
119
+ losses: [], // 只有读出来的 doc 上有
120
+ }
121
+ ```
122
+
123
+ `WordApp.currentDoc()` 产出的就是这个形状,`applyDoc(model)` 接受它(传 `null` 得到空白文档)。
124
+
125
+ ### 保存自检
126
+
127
+ `buildDocx()` 直接生成字节;`buildDocxVerified()` 生成后会**立刻读回来比对内容摘要**,任何不一致都抛 `保存自检未通过…` 并拒绝这次保存。应用内所有保存路径走的都是 `buildDocxVerified`。想强行写出未经自检的结果(比如调试),才用 `buildDocx`。
128
+
129
+ ### 保住与丢失
130
+
131
+ 往返会保住:段落对齐/缩进/行距、H1–H6、加粗斜体下划删除线、颜色字号字体高亮、等宽代码、超链接、有序无序列表、表格(列宽、单元格底纹、横纵合并)、内联图片、分隔线、引用块、分页符、页眉页脚与页码、纸张尺寸方向页边距分栏、批注、修订(含作者与时间)、脚注尾注、文档属性,以及主题等整包透传内容。
132
+
133
+ 会丢的主要是:文本框/形状、域代码、SmartArt。丢失项在读入时就被清点进 `doc.losses`,用 `lossText()` 可以直接展示给用户。
134
+
135
+ 旧版二进制 `.doc` 会在文件头就被拒绝:`旧版二进制 .doc 不支持,请先另存为 .docx`。
136
+
137
+ ## 只用编辑内核
138
+
139
+ ```js
140
+ import { EditorSurface } from '@a200888213/gbdocx/surface/editor-surface';
141
+
142
+ const surface = new EditorSurface({
143
+ mount: document.getElementById('editor'),
144
+ modelValue: '<p>正文</p>',
145
+ placeholder: '开始输入',
146
+ editable: true,
147
+ backdrop: (host) => { /* 自己画纸张、页眉页脚带 */ },
148
+ });
149
+
150
+ const editor = surface.editor; // EditorCore
151
+ editor.exec('toggleBold');
152
+ editor.state(); // 一次快照,供工具栏刷新
153
+ editor.run(() => editor.exec('insertText', 'hi'), { merge: 'insertText' });
154
+ await surface.insertImages(fileList);
155
+ surface.destroy();
156
+ ```
157
+
158
+ 这里的 **文档模型就是那段 contenteditable DOM**:进出只有 `normalizeBody` / `serializeBody` 两道规范化,对应 `editor.getHTML()` / `editor.setHTML(html)`。`exec(name, ...args)` 的命令名在 `COMMANDS` 注册表里,未知名返回 `false`;`can(name, ...args)` 用来置灰按钮。常用命令:`undo`、`redo`、`toggleBold/Italic/Underline/Strike/Code`、`setColor`、`setFontSize`、`setFontFamily`、`setLink`、`clearFormat`、`setHeading(level)`、`toggleBlockquote`、`toggleBulletList`、`insertPageBreak`、`insertTable({ rows, cols, withHeaderRow })`、`tableAction(action, counts)`、`setComment(key)`、`insertNote(spec)`、`resolveRevisions(accept)`、`convertBlock(kind, el)`。
159
+
160
+ ## 导入路径
161
+
162
+ 深层入口走通配 `./src/*.js`,**子路径不带 `.js`**:
163
+
164
+ ```js
165
+ import { parseDocx } from '@a200888213/gbdocx/kernel/docx/codec/docx'; // ✔ → src/kernel/docx/codec/docx.js
166
+ import { EditorCore } from '@a200888213/gbdocx/kernel/editor/engine/editor';
167
+ import { useKeyboard } from '@a200888213/gbdocx/kernel/keyboard';
168
+ import { FONT_SIZES } from '@a200888213/gbdocx/kernel/textStyles';
169
+ import { notify } from '@a200888213/gbdocx/kernel/notify';
170
+ ```
171
+
172
+ 写成 `@a200888213/gbdocx/kernel/docx/codec/docx.js` 会解析成 `docx.js.js` 而报 `ERR_MODULE_NOT_FOUND`。
173
+
174
+ ## 环境说明
175
+
176
+ **读方向(`parseDocx`)在纯 Node 可跑** —— 它只用 gbooxml 的纯 JS ZIP/XML。
177
+
178
+ **写方向(`buildDocx` / `buildDocxVerified`)和整套 UI 需要 DOM**:HTML → 块模型的转换用 `DOMParser`,界面层还用到 `ResizeObserver`、`localStorage`、`showOpenFilePicker`。在 Node 里跑写入请自备 jsdom,本包的测试就是这么做的:
179
+
180
+ ```js
181
+ import { JSDOM } from 'jsdom';
182
+ const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/' });
183
+ Object.assign(globalThis, {
184
+ window: dom.window, document: dom.window.document,
185
+ DOMParser: dom.window.DOMParser, XMLSerializer: dom.window.XMLSerializer,
186
+ Node: dom.window.Node, NodeFilter: dom.window.NodeFilter,
187
+ Element: dom.window.Element, HTMLElement: dom.window.HTMLElement,
188
+ DocumentFragment: dom.window.DocumentFragment,
189
+ });
190
+ const { parseDocx } = await import('@a200888213/gbdocx/kernel/docx/codec/docx');
191
+ ```
192
+
193
+ 注意要用**动态 import**:编解码模块在被加载时就会触碰 DOM 全局,必须在上面的赋值之后再导入。
194
+
195
+ `jsdom` 只是本包测试的 devDependency,不在运行时依赖里 —— 浏览器场景无需任何 polyfill。
196
+
197
+ ## 已知坑
198
+
199
+ 1. 批注键在写出时会被重编号成数字 id:读到的 `data-cmt="c1"` 存回去可能变成 `data-cmt="0"`,别把自己的业务 id 直接绑在这个属性上。
200
+ 2. `new WordApp(mount)` 的挂载元素必须已在文档中,构造期间就会测量布局;先 `append` 再 `new`。
201
+ 3. `WordApp` 不对外派发任何事件,它只消费编辑器内核的事件总线。要做联动,取 `app.editor` 后 `app.editor.on('state' | 'selection', fn)`。
202
+ 4. 偏好(缩放、面板开关)持久化在 `localStorage['gbdocx.prefs']`,SSR 环境请在客户端实例化。
203
+ 5. 自带 demo 的 `/vendor/gbooxml` 依赖仓库 `packages/gboffice/` 的分组布局,从 npm 单独安装需自己改 importmap。
204
+
205
+ ## 许可
206
+
207
+ MIT
package/index.html ADDED
@@ -0,0 +1,25 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>挂逼文档 gbdocx</title>
7
+ <link rel="stylesheet" href="/styles/tokens.css" />
8
+ <link rel="stylesheet" href="/styles/editor-content.css" />
9
+ <link rel="stylesheet" href="/styles/word-panel.css" />
10
+ <link rel="stylesheet" href="/styles/app.css" />
11
+ <link rel="stylesheet" href="/vendor/gbofficeui/office-chrome.css" />
12
+ <script type="importmap">
13
+ {
14
+ "imports": {
15
+ "gbooxml": "/vendor/gbooxml/src/index.js",
16
+ "guabiutils": "/vendor/guabiutils/index.js"
17
+ }
18
+ }
19
+ </script>
20
+ </head>
21
+ <body>
22
+ <div id="app" class="gbd-root"></div>
23
+ <script type="module" src="/src/app/main.js"></script>
24
+ </body>
25
+ </html>
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
- {
2
- "name": "@a200888213/gbdocx",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@a200888213/gbdocx",
3
+ "version": "0.4.0",
4
+ "description": "挂逼文档:独立 .docx 编辑器(内核移植自 guabi office/docx 编解码 + 自研 contenteditable 编辑器内核,UI 用原生 HTML 重写),只依赖 gbooxml。",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "./src/app/word-app.js",
8
+ "exports": {
9
+ ".": "./src/app/word-app.js",
10
+ "./app": "./src/app/word-app.js",
11
+ "./styles/*": "./styles/*",
12
+ "./*": "./src/*.js",
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "src",
17
+ "styles",
18
+ "index.html",
19
+ "serve.mjs",
20
+ "LICENSE"
21
+ ],
22
+ "keywords": [
23
+ "docx",
24
+ "document",
25
+ "word",
26
+ "ooxml",
27
+ "editor",
28
+ "contenteditable"
29
+ ],
30
+ "engines": {
31
+ "node": ">=18"
32
+ },
33
+ "scripts": {
34
+ "start": "node serve.mjs",
35
+ "test": "node --test test/roundtrip.test.js test/ui.test.js test/mode.test.js"
36
+ },
37
+ "dependencies": {
38
+ "gbooxml": "^0.1.1",
39
+ "gbofficeui": "^0.1.0",
40
+ "guabiutils": "^0.3.0"
41
+ },
42
+ "devDependencies": {
43
+ "jsdom": "^30.1.3"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ }
48
+ }
package/serve.mjs ADDED
@@ -0,0 +1,22 @@
1
+ // [文件] gbdocx·serve —— 静态服务器(把 gbdocx 与同仓的 gbooxml / guabiutils 一起按 URL 空间供给,免打包免安装)
2
+ // 用法:node serve.mjs [端口]
3
+ import { fileURLToPath } from 'node:url';
4
+ import { startStaticServer } from 'guabiutils/dev-server';
5
+
6
+ const ooxmlRoot = fileURLToPath(new URL('../gbooxml/', import.meta.url));
7
+ const utilsSrc = fileURLToPath(new URL('../../guabiutils/src/', import.meta.url));
8
+ const officeChrome = fileURLToPath(new URL('../gbofficeui/styles/', import.meta.url));
9
+
10
+ const { origin } = await startStaticServer({
11
+ root: fileURLToPath(new URL('.', import.meta.url)),
12
+ index: 'index.html',
13
+ port: Number(process.argv[2] || process.env.GBDOCX_PORT || 5273),
14
+ mounts: [
15
+ { prefix: '/vendor/gbooxml/', dir: ooxmlRoot },
16
+ { prefix: '/vendor/guabiutils/', dir: utilsSrc },
17
+ { prefix: '/vendor/gbofficeui/', dir: officeChrome },
18
+ ],
19
+ });
20
+
21
+ console.log(`gbdocx 运行中:${origin}`);
22
+ console.log(`gbooxml 映射自:${ooxmlRoot}`);
@@ -0,0 +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, '新建文档');
@@ -0,0 +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;
@@ -0,0 +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 };
@@ -0,0 +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 };