@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,646 @@
1
+ // [文件] web·editor-kernel·engine·dom —— 内核 DOM 基元:块判定、选区↔字符偏移换算、结构改写
2
+ // [约束] 「DOM 就是文档模型」的全部口径都在本文件:
3
+ // · 文本块 = 直接承载行内内容的元素(p / h1~h6 / td / th / 普通 li / 待办条目内的 div / 代码块内的 code),
4
+ // 容器(ul / ol / blockquote / pre / tr / 待办 li)不算文本块,只算结构块。
5
+ // · 字符偏移 = 文本节点长度累加,`br` 与 `img` 各算 1(与 inline.js 片段模型同一口径,否则选区换算错位)。
6
+ // · 运行期装饰(复选框 label、选中类名)一律不计入正文、不序列化。
7
+
8
+ /** 直接承载行内内容的标签 */
9
+ const TEXT_BLOCK_TAGS = new Set(['P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'TD', 'TH']);
10
+
11
+ /** 结构块标签(复制 / 删除 / 移动 / 拖拽的目标;LI 覆盖待办条目这种非文本块的容器) */
12
+ const STRUCTURE_TAGS = new Set(['BLOCKQUOTE', 'UL', 'OL', 'PRE', 'TABLE', 'HR', 'IMG', 'LI']);
13
+
14
+ /** 可承载块级内联样式(行高 / 对齐 / 缩进)的标签:代码块与原子块刻意不在内 */
15
+ const STYLEABLE_TAGS = new Set(['P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'TD', 'TH', 'LI', 'BLOCKQUOTE']);
16
+
17
+ /** 容器块属性名(高亮块 / 超级块 / 列):靠 data-* 识别,值即形态(高亮块的值=色调)。
18
+ * [设计] 用 data-* 而非 class:运行期类名会被 stripRuntimeClasses 剥掉、docx 方言又大量占用 class,
19
+ * data-* 与它们都不撞车,且随 Block.Attrs 原样往返。 */
20
+ export const CALLOUT_ATTR = 'data-callout';
21
+ export const SUPER_ATTR = 'data-super';
22
+ export const COL_ATTR = 'data-col';
23
+
24
+ /** 高亮块 / 超级块外壳(内容容器,本身不是文本块;删除/移动/拖拽以它为整块单位) */
25
+ export const isContainerBlock = (el) =>
26
+ !!el && el.nodeType === Node.ELEMENT_NODE && (el.hasAttribute(CALLOUT_ATTR) || el.hasAttribute(SUPER_ATTR));
27
+
28
+ /** 列外壳(超级块内的分栏容器) */
29
+ export const isColumnBlock = (el) => !!el && el.nodeType === Node.ELEMENT_NODE && el.hasAttribute(COL_ATTR);
30
+
31
+ /** 运行期装饰类:序列化前必须剥掉,绝不落盘(改名要同步 content.scss 里的同名规则)
32
+ * [设计] 表格框选与列宽提示不再走逐格类名——框选是宿主浮层里的一层矩形、列宽是贴边竖线,正文 DOM 一个字节都不动,
33
+ * 故此处不再登记 selectedCell / gbd-is-sel-* / has-sel-* / re-col-hover / re-col-resizing。 */
34
+ export const ATOM_SELECTED = 'gbd-is-selected-node';
35
+ export const BLOCK_DRAGGING = 'gbd-is-block-dragging';
36
+ /** 表格框选拖拽中(表级):内容锁 user-select,避免格内文字被原生选区涂成一条条蓝块 */
37
+ export const CELL_DRAGGING = 're-cell-dragging';
38
+ /** 定位闪烁(目录/批注锚点滚到位后闪一下,宿主加、1.2s 后自己摘) */
39
+ export const CATALOG_HIT = 'gbd-is-catalog-hit';
40
+ /** 块选中高亮(整块淡蓝底):选区跨块时由内核打(selection.js 的 syncBlockSelection) */
41
+ export const BLOCK_SELECTED = 'gbd-is-block-selected';
42
+ /** 块标悬浮/按下高亮:由块标操作条(BlockHandle)打,与选区高亮两回事、各自管理 */
43
+ export const BLOCK_HOVER = 'gbd-is-block-hover';
44
+ export const RUNTIME_CLASSES = [ATOM_SELECTED, BLOCK_DRAGGING, CELL_DRAGGING, CATALOG_HIT, BLOCK_SELECTED, BLOCK_HOVER];
45
+
46
+ /** 笔记行内锚属性(值与 schema.js 的 ATTACH_ATTR/REF_DOC_ATTR 同值;dom 是内核最底层不 import schema,故独立一份)
47
+ * 用途:blockText 与 hasBlockBody/isBlockEmpty 按此把锚点视作 1 字符位内容(与 nodeChars 的 contenteditable=false 口径配套) */
48
+ const ANCHOR_ATTRS = ['data-attach', 'data-ref-doc'];
49
+ const ANCHOR_SELECTOR = '[data-attach],[data-ref-doc]';
50
+
51
+ /** 运行期布局结构(Word 分页的产物;内核只提供还原机制,命名与 pagination.js 同契约):
52
+ * 占位/分隔元素整块删除;栏容器拆壳留内容;行级拆分块按家族标记并回首个块 */
53
+ export const RUNTIME_ELEMENT_SELECTOR = '.wd-page-gap, .wd-col-sep';
54
+ const RUNTIME_UNWRAP_SELECTOR = '.wd-col';
55
+ export const RUNTIME_SPLIT_ATTR = 'data-wd-split';
56
+
57
+ /**
58
+ * 运行期布局产物判据(Word 分页的页间缝 / 栏分隔 / 跨页拆分的段落碎片):不是正文块。
59
+ * 块标、结构操作与拖拽落点一律不认它们——缝会被 nearestStructure 当成就近块返回,
60
+ * 碎片被拖动后会在下次重排被 flatten 并回首片(等于白拖)。
61
+ */
62
+ export const isRuntimeBlock = (el) =>
63
+ el?.nodeType === Node.ELEMENT_NODE && (el.matches(RUNTIME_ELEMENT_SELECTOR) || el.hasAttribute(RUNTIME_SPLIT_ATTR));
64
+
65
+ /**
66
+ * 拆分家族并回首块
67
+ * @param {HTMLElement} first 首块(文档序最先的碎片)
68
+ * @param {HTMLElement[]} rest 其余碎片
69
+ * @returns {HTMLElement} 首块
70
+ */
71
+ function mergeSplitGroup(first, rest) {
72
+ rest.forEach((el) => {
73
+ // 表格家族:续表只有「重复表头 + 接续行」两块——表头是克隆(丢弃),接续行并回首表最后一个 tbody
74
+ if (first.tagName === 'TABLE') {
75
+ // [坑] 通用「appendChild 全部子节点」会把续表的 thead / tbody 直接挂到首表尾部(多出一个 tbody),
76
+ // 表格结构当场坏掉:行级分页只认 tBodies 里的行,行数由此少算,超高表被误判「装得下」而永不拆行
77
+ const host = first.tBodies[first.tBodies.length - 1] || first.appendChild(document.createElement('tbody'));
78
+ Array.from(el.tBodies).forEach((tb) => Array.from(tb.rows).forEach((row) => host.appendChild(row)));
79
+ el.remove();
80
+ return;
81
+ }
82
+ moveChildren(el, first);
83
+ el.remove();
84
+ });
85
+ first.removeAttribute(RUNTIME_SPLIT_ATTR);
86
+ return first;
87
+ }
88
+
89
+ /**
90
+ * 把 el 所在的跨页拆分家族并回首块(悬停/拖拽命中的可能是续表碎片)
91
+ * [设计] 只并本家族,不动其它分页产物:宿主拖表要在同一次历史提交里先并回再搬家,这一步不能等重排
92
+ * @param {HTMLElement} container 编辑面根(家族查找范围)
93
+ * @param {HTMLElement} el 家族任一成员
94
+ * @returns {HTMLElement} 首块(无拆分标记时原样返回)
95
+ */
96
+ export function mergeSplitFamily(container, el) {
97
+ const id = el?.getAttribute?.(RUNTIME_SPLIT_ATTR);
98
+ if (!id || !container?.querySelectorAll || !container.contains?.(el)) return el;
99
+ const members = Array.from(container.querySelectorAll(`[${RUNTIME_SPLIT_ATTR}]`))
100
+ .filter((node) => node.getAttribute(RUNTIME_SPLIT_ATTR) === id);
101
+ if (!members.length) return el;
102
+ return mergeSplitGroup(members[0], members.slice(1));
103
+ }
104
+
105
+ /**
106
+ * 把运行期布局结构还原成单流正文(装载时防御性调用、序列化前必须调用):
107
+ * 拆分块并回、栏容器拆壳、占位元素删除——三者的顺序不可调换
108
+ */
109
+ export function restoreRuntimeStructures(container) {
110
+ if (!container?.querySelector) return;
111
+ // 1) 行级拆分块并回:同一家族的尾块内容接回首个块,标记清除
112
+ const groups = new Map();
113
+ container.querySelectorAll(`[${RUNTIME_SPLIT_ATTR}]`).forEach((el) => {
114
+ const id = el.getAttribute(RUNTIME_SPLIT_ATTR);
115
+ if (!groups.has(id)) groups.set(id, []);
116
+ groups.get(id).push(el);
117
+ });
118
+ groups.forEach((els) => mergeSplitGroup(els[0], els.slice(1)));
119
+ // 2) 栏容器拆壳:里面装的是正文本体,删了就丢内容
120
+ container.querySelectorAll(RUNTIME_UNWRAP_SELECTOR).forEach((el) => unwrapElement(el));
121
+ // 3) 占位/分隔元素整块删除
122
+ container.querySelectorAll(RUNTIME_ELEMENT_SELECTOR).forEach((el) => el.remove());
123
+ }
124
+
125
+ /** 全部运行期装饰类的选择器 */
126
+ export const RUNTIME_CLASS_SELECTOR = RUNTIME_CLASSES.map((name) => `.${name}`).join(',');
127
+
128
+ /** 剥掉元素上的运行期类名,剥空了连 class 属性一起删(正文里不留空 class 噪声)
129
+ * [设计] 一个运行期类都没有时直接返回:这段在序列化前对每个元素调用,setAttribute 会顺带把
130
+ * MutationObserver 唤醒一遍,选区刷新与序列化撞上就会互相触发 */
131
+ export function stripRuntimeClasses(el) {
132
+ if (!el?.classList?.length) return;
133
+ if (!RUNTIME_CLASSES.some((name) => el.classList.contains(name))) return;
134
+ const kept = Array.from(el.classList).filter((name) => !RUNTIME_CLASSES.includes(name));
135
+ if (kept.length) el.setAttribute('class', kept.join(' '));
136
+ else el.removeAttribute('class');
137
+ }
138
+
139
+ export const isTaskItem = (el) => !!el && el.tagName === 'LI' && el.hasAttribute('data-checked');
140
+
141
+ /** 待办条目的正文宿主(li > label + div,div 才是文本块) */
142
+ const isTaskContent = (el) => !!el && el.tagName === 'DIV' && isTaskItem(el.parentElement);
143
+
144
+ /** 代码块正文宿主(pre > code) */
145
+ export const isCodeContent = (el) => !!el && el.tagName === 'CODE' && el.parentElement?.tagName === 'PRE';
146
+
147
+ /** 纯结构判据(不判归属):元素按标签/形态是否直接承载行内正文 */
148
+ function isTextBlockShape(el) {
149
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
150
+ if (TEXT_BLOCK_TAGS.has(el.tagName)) return true;
151
+ if (el.tagName === 'LI') return !isTaskItem(el);
152
+ return isTaskContent(el) || isCodeContent(el);
153
+ }
154
+
155
+ /** 带归属检查的文本块判定:必须确认元素确在该编辑面内 */
156
+ export function isTextBlock(el, root) {
157
+ return isTextBlockShape(el) && !!root && el !== root && root.contains(el);
158
+ }
159
+
160
+ function isStructureBlock(el, root) {
161
+ if (!el || el === root || !root.contains(el)) return false;
162
+ return STRUCTURE_TAGS.has(el.tagName) || isTextBlock(el, root) || isContainerBlock(el) || isColumnBlock(el);
163
+ }
164
+
165
+ /** 该元素能否承载块级样式(待办条目样式挂在 li 上,其正文 div 不算) */
166
+ export function isStyleableBlock(el) {
167
+ return !!el && (STYLEABLE_TAGS.has(el.tagName) || (isTextBlockShape(el) && el.tagName !== 'CODE'));
168
+ }
169
+
170
+ /** node(文本节点或元素)所属的最内层文本块;不在编辑面内返回 null */
171
+ export function blockOf(node, root) {
172
+ let el = node?.nodeType === Node.TEXT_NODE ? node.parentElement : node;
173
+ while (el && el !== root) {
174
+ if (isTextBlock(el, root)) return el;
175
+ el = el.parentElement;
176
+ }
177
+ return null;
178
+ }
179
+
180
+ /**
181
+ * 自 node 向上取最外层目标块(结构操作用)
182
+ * [坑] 必须从外向内取第一个命中:段落位于引用/列表项内时,目标是引用/条目本身而不是段落,
183
+ * 否则删除或拖拽只会作用到内层一块,与用户看到的整块不一致。
184
+ */
185
+ function outerBlock(node, root, predicate) {
186
+ const chain = [];
187
+ let el = node?.nodeType === Node.TEXT_NODE ? node.parentElement : node;
188
+ while (el && el !== root) {
189
+ chain.unshift(el);
190
+ el = el.parentElement;
191
+ }
192
+ return chain.find(predicate) || null;
193
+ }
194
+
195
+ export const structureTarget = (node, root) => outerBlock(node, root, (el) => isStructureBlock(el, root));
196
+ export const styleTarget = (node, root) => outerBlock(node, root, (el) => isStyleableBlock(el) || isTaskContent(el));
197
+
198
+ /** 块级样式的挂载元素:待办条目的正文 div 归到它的 li(与存量 data-checked 条目同口径) */
199
+ export function styleHost(block) {
200
+ return isTaskContent(block) ? block.parentElement : block;
201
+ }
202
+
203
+ /* ===================== 字符偏移换算 ===================== */
204
+
205
+ /** 参与正文的节点:只有待办复选框 label 不算正文(选中类名是元素自身状态,不能因此把整格正文抹掉) */
206
+ function isInlineContent(node) {
207
+ if (node.nodeType === Node.TEXT_NODE) return true;
208
+ return node.nodeType === Node.ELEMENT_NODE && node.tagName !== 'LABEL';
209
+ }
210
+
211
+ /** 单个节点在正文里占的字符数(文本按长度,br / img / 原子元素各 1,容器递归) */
212
+ function nodeChars(node) {
213
+ if (node.nodeType === Node.TEXT_NODE) return node.data.length;
214
+ if (!isInlineContent(node)) return 0;
215
+ if (node.tagName === 'BR') return 0; // 硬换行不占字符位:占位 br 会让偏移换算整体错一格
216
+ if (node.tagName === 'IMG' || node.getAttribute('contenteditable') === 'false') return 1;
217
+ let total = 0;
218
+ for (const child of Array.from(node.childNodes)) total += nodeChars(child);
219
+ return total;
220
+ }
221
+
222
+ /** 按文档顺序遍历块内正文,命中 predicate 时返回其之前的累计字符数;未命中返回 -1 */
223
+ function charsBefore(block, predicate) {
224
+ let count = 0;
225
+ const isAtomic = (el) =>
226
+ el.tagName === 'BR' || el.tagName === 'IMG' || el.getAttribute('contenteditable') === 'false' || !el.childNodes.length;
227
+ const walk = (parent) => {
228
+ for (const child of Array.from(parent.childNodes)) {
229
+ if (predicate(child)) return true;
230
+ if (!isInlineContent(child)) continue;
231
+ // 容器递归:未命中时子节点已计入 count,不再重复加整棵子树
232
+ if (child.nodeType === Node.ELEMENT_NODE && !isAtomic(child)) {
233
+ if (walk(child)) return true;
234
+ } else {
235
+ count += nodeChars(child);
236
+ }
237
+ }
238
+ return false;
239
+ };
240
+ return walk(block) ? count : -1;
241
+ }
242
+
243
+ /** (node, offset) 在块内的字符偏移 */
244
+ export function charOffset(block, node, offset) {
245
+ if (!block || !node) return 0;
246
+ if (node === block) return childrenChars(block, offset);
247
+ const base = charsBefore(block, (el) => el === node);
248
+ if (base < 0) return blockLength(block);
249
+ if (node.nodeType === Node.TEXT_NODE) return base + Math.min(offset, node.data.length);
250
+ return base + childrenChars(node, offset);
251
+ }
252
+
253
+ /** 元素内前 index 个子节点占的字符数(光标落在容器边界时用) */
254
+ function childrenChars(el, index) {
255
+ const children = Array.from(el.childNodes);
256
+ let total = 0;
257
+ for (let i = 0; i < Math.min(index, children.length); i++) total += nodeChars(children[i]);
258
+ return total;
259
+ }
260
+
261
+ /** 块的正文长度 */
262
+ export function blockLength(block) {
263
+ let total = 0;
264
+ if (!block) return 0;
265
+ for (const child of Array.from(block.childNodes)) total += nodeChars(child);
266
+ return total;
267
+ }
268
+
269
+ /** 块的纯文本(br → \n、原子 → ),与字符偏移口径同源 */
270
+ export function blockText(block) {
271
+ let text = '';
272
+ const walk = (parent) => {
273
+ for (const child of Array.from(parent.childNodes)) {
274
+ if (child.nodeType === Node.TEXT_NODE) text += child.data;
275
+ else if (child.tagName === 'IMG') text += '';
276
+ // [设计] 笔记行内锚(doc-ref/doc-attach)是 1 字符位原子:输出占位符而非递归取文本,
277
+ // 否则锚点文本长度与「1 字符位」分叉会让其后所有位置换算错位
278
+ else if (child.nodeType === Node.ELEMENT_NODE && ANCHOR_ATTRS.some((a) => child.hasAttribute(a))) text += '';
279
+ // 硬换行不参与正文文本(它与 nodeChars/charOffset/domPoint 的「br 不占位」口径必须一致)
280
+ else if (isInlineContent(child)) walk(child);
281
+ }
282
+ };
283
+ if (block) walk(block);
284
+ return text;
285
+ }
286
+
287
+ /** 字符偏移 → 可落点的 (node, offset);越界收敛到块尾 */
288
+ export function domPoint(block, index) {
289
+ let acc = 0;
290
+ let result = null;
291
+ const walk = (parent) => {
292
+ if (result) return;
293
+ const children = Array.from(parent.childNodes).filter(isInlineContent);
294
+ for (let i = 0; i < children.length; i++) {
295
+ const child = children[i];
296
+ const size = nodeChars(child);
297
+ if (child.nodeType === Node.TEXT_NODE) {
298
+ if (index <= acc + size) {
299
+ result = { node: child, offset: Math.max(0, index - acc) };
300
+ return;
301
+ }
302
+ } else if (child.nodeType === Node.ELEMENT_NODE && (child.tagName === 'IMG' || child.getAttribute('contenteditable') === 'false')) {
303
+ // 原子(图片 / 脚注锚点 / 只读行内锚)只占 1 个字符位,光标只能落在它之前或之后。
304
+ // [坑] 不能递归进它的子节点:脚注锚点里有序号文字,偏移正好等于「原子内部」时
305
+ // 会把 Range 落进 contenteditable=false 元素里,接着插入的锚点就嵌进上一个锚点,
306
+ // 随后重排序号(textContent 覆盖)会把新锚点整枚吃掉
307
+ if (index <= acc) {
308
+ result = { node: parent, offset: indexOfChild(parent, child) };
309
+ return;
310
+ }
311
+ if (index === acc + 1) {
312
+ result = { node: parent, offset: indexOfChild(parent, child) + 1 };
313
+ return;
314
+ }
315
+ } else if (child.nodeType === Node.ELEMENT_NODE && !child.childNodes.length) {
316
+ if (index <= acc) {
317
+ result = { node: parent, offset: indexOfChild(parent, child) };
318
+ return;
319
+ }
320
+ // [坑] 只有真占 1 字符位的原子(img / contenteditable=false)才吃 acc+1;
321
+ // br 按 nodeChars 是 0 字符位,这里跟着匹配就会让硬换行之后的偏移整体错一格——
322
+ // 表现为查找命中/替换落在换行后的前一个字上,把正文改错
323
+ if (size > 0 && index === acc + 1) {
324
+ result = { node: parent, offset: indexOfChild(parent, child) + 1 };
325
+ return;
326
+ }
327
+ } else {
328
+ walk(child);
329
+ if (result) return;
330
+ // [坑] 递归已按子节点推进过 acc,外层再 += nodeChars(child) 会把整棵行内容器数两次,
331
+ // 加粗/链接之后的偏移整体前移——替换与选区复原都会落到错字上(charsBefore 同口径已防)
332
+ continue;
333
+ }
334
+ acc += size;
335
+ }
336
+ if (!children.length && parent === block) result = { node: parent, offset: 0 };
337
+ };
338
+ walk(block);
339
+ return result || { node: block, offset: block.childNodes.length };
340
+ }
341
+
342
+ function indexOfChild(parent, child) {
343
+ return Array.prototype.indexOf.call(parent.childNodes, child);
344
+ }
345
+
346
+ /* ===================== 选区 ===================== */
347
+
348
+ /** 编辑面内的当前选区 Range(不在本编辑面内返回 null;折叠也返回) */
349
+ export function rangeOf(root) {
350
+ const sel = window.getSelection();
351
+ if (!sel || !sel.rangeCount) return null;
352
+ const range = sel.getRangeAt(0);
353
+ if (!root.contains(range.commonAncestorContainer)) return null;
354
+ return range;
355
+ }
356
+
357
+ /** 选中的文本块序列(按文档顺序),各带块内起止字符偏移 */
358
+ export function blocksInRange(root, range) {
359
+ const target = range || rangeOf(root);
360
+ if (!target) return [];
361
+ const anchorBlock = blockOf(target.commonAncestorContainer, root);
362
+ const inBlock = (node, block) => node === block || block.contains(node);
363
+ const out = [];
364
+ for (const block of allTextBlocks(root)) {
365
+ if (block !== anchorBlock && !target.intersectsNode(block)) continue;
366
+ const full = blockLength(block);
367
+ const start = inBlock(target.startContainer, block) ? charOffset(block, target.startContainer, target.startOffset) : 0;
368
+ const end = inBlock(target.endContainer, block) ? charOffset(block, target.endContainer, target.endOffset) : full;
369
+ if (end < start) continue;
370
+ if (end === start && block !== blockOf(target.startContainer, root)) continue;
371
+ out.push({ block, start: Math.min(Math.max(start, 0), full), end: Math.min(Math.max(end, 0), full) });
372
+ }
373
+ return out;
374
+ }
375
+
376
+ /** 编辑面内全部文本块(文档顺序;文本块内部不再下钻,保证「一个文本块只承载一份行内正文」) */
377
+ export function allTextBlocks(root) {
378
+ const out = [];
379
+ const walk = (parent) => {
380
+ for (const el of Array.from(parent.children)) {
381
+ if (!isInlineContent(el)) continue;
382
+ if (isTextBlock(el, root)) {
383
+ out.push(el);
384
+ continue;
385
+ }
386
+ if (el.children.length) walk(el);
387
+ }
388
+ };
389
+ if (root) walk(root);
390
+ return out;
391
+ }
392
+
393
+ /** 落选区:两端各按 (block, offset) 定位;结构已变则收敛 */
394
+ export function selectRange(root, start, end) {
395
+ if (!start?.block?.isConnected || !root.contains(start.block)) return;
396
+ const a = domPoint(start.block, start.offset ?? 0);
397
+ const b = end?.block?.isConnected && root.contains(end.block) ? domPoint(end.block, end.offset ?? 0) : a;
398
+ const range = document.createRange();
399
+ try {
400
+ range.setStart(a.node, a.offset);
401
+ range.setEnd(b.node, b.offset);
402
+ } catch {
403
+ range.selectNodeContents(a.node.nodeType === Node.TEXT_NODE ? a.node : start.block);
404
+ range.collapse(false);
405
+ }
406
+ const sel = window.getSelection();
407
+ sel.removeAllRanges();
408
+ sel.addRange(range);
409
+ }
410
+
411
+ export function setCaret(block, offset = 0) {
412
+ const root = block?.parentElement?.closest('[contenteditable="true"]') || document.body;
413
+ selectRange(root, { block, offset }, { block, offset });
414
+ }
415
+
416
+ /**
417
+ * 把原生选区就地折叠成零长 caret(终点收缩到起点)
418
+ * [设计] 表格框选期间的**兜底**手段:主防线是 editor.js 在 mousedown 上 preventDefault(从源头不让
419
+ * 浏览器起原生拖拽选区)。本函数用于「选区已经存在」的残留场景(shift 扩选、mousedown 前
420
+ * 别处已有选区),把已有选区就地折叠,高亮全部交给宿主浮层里的框选矩形承担。
421
+ * [坑] 单独靠它挡不住拖拽蔓延:Chrome 在 contenteditable 里按自己的拖拽锚点逐帧重算选区,
422
+ * 每帧折叠属于「追着擦」,实测仍会把两侧列的文字选进来 —— 故它只能当兜底,不能当主防线。
423
+ * [坑] 只准动 rangeCount 里已有的 range,绝不新建:先 removeAllRanges 再 addRange 会打断
424
+ * Chrome 正在进行的拖拽状态,表现为「拖到一半光标跳走、后续 mousemove 不再派发」
425
+ * [坑] rangeCount 为 0 时 getRangeAt(0) 抛 IndexSizeError。本函数逐帧调用,绝不能把这个取值写进
426
+ * 默认参数(默认参数在函数体之外求值、绕过 try/catch):mousedown 落在空白处就是「有 selection
427
+ * 对象、但零个 range」,会变成每帧抛一次异常、打断调用方的拖拽处理链
428
+ * @param {Range} [range] 折叠目标;不传则折叠当前原生选区的首个 range
429
+ * @returns {Range|null} 被折叠的 range(供调用方逐帧复用,省掉每帧重新取)
430
+ */
431
+ export function collapseRange(range) {
432
+ let target = range;
433
+ if (!target) {
434
+ const sel = window.getSelection?.();
435
+ // rangeCount 为 0 时 getRangeAt(0) 会抛 IndexSizeError,必须挡在取值之前:
436
+ // mousedown 落在空白处就是「有 selection 对象、但零个 range」,逐帧调用会每帧抛一次
437
+ if (!sel || !sel.rangeCount) return null;
438
+ try {
439
+ target = sel.getRangeAt(0);
440
+ } catch {
441
+ return null;
442
+ }
443
+ }
444
+ if (!target) return null;
445
+ try {
446
+ if (!target.collapsed) target.collapse(true);
447
+ } catch {
448
+ return null;
449
+ }
450
+ return target;
451
+ }
452
+
453
+ /* ===================== 结构改写基元 ===================== */
454
+
455
+ /** 把 source 的子节点全部搬进 target 尾部(source 被搬空,自身保留) */
456
+ export function moveChildren(source, target) {
457
+ while (source.firstChild) target.appendChild(source.firstChild);
458
+ }
459
+
460
+ /** 把 el 的子节点原地搬到 el 前面(只搬内容,el 自身留不留由调用方决定——列表条目正文宿主剥离用) */
461
+ export function moveChildrenBefore(el) {
462
+ const parent = el?.parentNode;
463
+ if (!parent) return;
464
+ while (el.firstChild) parent.insertBefore(el.firstChild, el);
465
+ }
466
+
467
+ /** 拆壳:子节点提到 el 原位后删掉 el(正文一个字都不丢) */
468
+ export function unwrapElement(el) {
469
+ if (!el?.parentNode) return;
470
+ moveChildrenBefore(el);
471
+ el.remove();
472
+ }
473
+
474
+ /** 换标签保内容与属性(p↔h1…) */
475
+ export function renameBlock(el, tag) {
476
+ if (el.tagName.toLowerCase() === tag) return el;
477
+ const next = document.createElement(tag);
478
+ moveAttributes(el, next);
479
+ moveChildren(el, next);
480
+ el.replaceWith(next);
481
+ return next;
482
+ }
483
+
484
+ /** 属性搬运(块级样式都在内联 style 上),顺手剥掉运行期类名
485
+ * [设计] contenteditable 是编辑面运行期态、不是内容属性:搬到新块上会把新块冻成不可编辑 */
486
+ export function moveAttributes(from, to) {
487
+ for (const attr of Array.from(from.attributes)) {
488
+ if (attr.name === 'contenteditable') continue;
489
+ to.setAttribute(attr.name, attr.value);
490
+ }
491
+ stripRuntimeClasses(to);
492
+ }
493
+
494
+ /** 把一批相邻元素包进 wrapper */
495
+ export function wrapElements(elements, wrapper) {
496
+ if (!elements.length) return wrapper;
497
+ elements[0].before(wrapper);
498
+ for (const el of elements) wrapper.appendChild(el);
499
+ return wrapper;
500
+ }
501
+
502
+ /** 块内是否无正文(占位判定与「空条目退出列表」都用它) */
503
+ export function isBlockEmpty(block) {
504
+ if (!block) return true;
505
+ if (block.querySelector('img')) return false;
506
+ if (block.querySelector(ANCHOR_SELECTOR)) return false; // 行内锚是内容:只含锚点的行不算空
507
+ return !blockText(block).replace(/[\n]/g, '').length;
508
+ }
509
+
510
+ /**
511
+ * 块里是否已有可见承载(正文文字,或 img / input / br 任一原子)
512
+ * [坑] 与 isBlockEmpty 是两件事,别再混用:这块判「还要不要补占位 br、空壳能不能剪」——
513
+ * 占位 br 本身就是承载,算 hasBlockBody 却不正文;isBlockEmpty 判的是「这行看起来是不是空的」
514
+ */
515
+ export function hasBlockBody(el) {
516
+ return Boolean(el) && (Boolean(el.textContent?.trim()) || Boolean(el.querySelector('img,input,br,[data-attach],[data-ref-doc]')));
517
+ }
518
+
519
+ /* ===================== 坐标命中 ===================== */
520
+
521
+ /** 坐标命中位置(点留白落光标用):优先文本位置,退回元素 */
522
+ export function pointAtCoords(root, x, y) {
523
+ const doc = root.ownerDocument;
524
+ const hit = doc.caretPositionFromPoint?.(x, y) || null;
525
+ if (hit && root.contains(hit.offsetNode)) return { node: hit.offsetNode, offset: hit.offset };
526
+ const range = doc.caretRangeFromPoint?.(x, y) || null;
527
+ if (range && root.contains(range.startContainer)) return { node: range.startContainer, offset: range.startOffset };
528
+ const el = doc.elementFromPoint(x, y);
529
+ return el && root.contains(el) ? { node: el, offset: 0 } : null;
530
+ }
531
+
532
+ /** 坐标命中的结构块(悬停手柄 / 右键块菜单 / 拖拽落点);表格内不给手柄 */
533
+ export function blockAtCoords(root, x, y) {
534
+ const hit = pointAtCoords(root, x, y);
535
+ if (!hit) return null;
536
+ const el = hit.node.nodeType === Node.TEXT_NODE ? hit.node.parentElement : hit.node;
537
+ const inTable = tableOf(el, root);
538
+ if (inTable) return null;
539
+ const block = structureTarget(el, root) || nearestStructure(root, y);
540
+ if (isRuntimeBlock(block)) return null;
541
+ return block;
542
+ }
543
+
544
+ /** 命不中元素时按矩形就近取块(块间距、行首行尾空白) */
545
+ export function nearestStructure(root, y) {
546
+ let best = null;
547
+ let bestGap = Infinity;
548
+ for (const el of Array.from(root.children)) {
549
+ const rect = el.getBoundingClientRect();
550
+ if (!rect.height && !rect.width) continue;
551
+ const gap = rect.top > y ? rect.top - y : rect.bottom < y ? y - rect.bottom : 0;
552
+ if (gap < bestGap) {
553
+ bestGap = gap;
554
+ best = el;
555
+ }
556
+ }
557
+ return bestGap <= 48 ? best : null;
558
+ }
559
+
560
+ /** 自 node 向上找满足条件的祖先(含自身),越过 root 即停 */
561
+ export function closestWithin(node, predicate, root) {
562
+ let el = node?.nodeType === Node.TEXT_NODE ? node.parentElement : node;
563
+ while (el && el !== root && root.contains(el)) {
564
+ if (predicate(el)) return el;
565
+ el = el.parentElement;
566
+ }
567
+ return null;
568
+ }
569
+
570
+ /** 单元格判据:td/th 都是单一文本块,跨格改写会撕坏网格,一切表格动作先过这关 */
571
+ export const isCell = (el) => !!el && (el.tagName === 'TD' || el.tagName === 'TH');
572
+
573
+ /** 自 node 向上取所在单元格 */
574
+ export const cellOf = (node, root) => closestWithin(node, isCell, root);
575
+
576
+ /** 自 node 向上取所在表格 */
577
+ export const tableOf = (node, root) => closestWithin(node, (el) => el.tagName === 'TABLE', root);
578
+
579
+ /** 结构块的视觉矩形(手柄、落点线、覆盖层定位基准) */
580
+ export function blockRect(el) {
581
+ if (!el) return null;
582
+ const rect = el.getBoundingClientRect();
583
+ if (rect.height) return rect;
584
+ const range = document.createRange();
585
+ range.selectNodeContents(el);
586
+ const line = Array.from(range.getClientRects()).find((r) => r.height > 0);
587
+ return line || rect;
588
+ }
589
+
590
+ /** 读内联样式单条属性 */
591
+ export function styleValue(el, prop) {
592
+ return (el?.style?.getPropertyValue(prop) || '').trim();
593
+ }
594
+
595
+ /** 写内联样式:空值即删除,避免正文积累 `padding-left: 0em` 这类噪声 */
596
+ export function setStyleValue(el, prop, value) {
597
+ if (!el) return;
598
+ if (value === null || value === undefined || value === '') el.style.removeProperty(prop);
599
+ else el.style.setProperty(prop, String(value));
600
+ // 属性清空后不留 style="" 这种噪声壳
601
+ if (el.getAttribute('style') === '') el.removeAttribute('style');
602
+ }
603
+
604
+ /** 块内 [start,end) 字符区间 → Range(查找高亮与替换的唯一出口) */
605
+ export function rangeInBlock(block, start, end) {
606
+ const from = domPoint(block, start);
607
+ const to = domPoint(block, end);
608
+ const range = document.createRange();
609
+ range.setStart(from.node, from.offset);
610
+ range.setEnd(to.node, to.offset);
611
+ return range;
612
+ }
613
+
614
+ /** el 内部(含自身)第一个文本块(转换 / 拆块后按新结构找回光标落点) */
615
+ export function firstTextBlockIn(el, root) {
616
+ if (!el) return null;
617
+ if (isTextBlock(el, root)) return el;
618
+ const stack = Array.from(el.children);
619
+ while (stack.length) {
620
+ const next = stack.shift();
621
+ if (isTextBlock(next, root)) return next;
622
+ stack.unshift(...Array.from(next.children));
623
+ }
624
+ return null;
625
+ }
626
+
627
+ /** 元素在 root 下的子节点路径:innerHTML 重建后元素引用失效,历史与选区复原只能按路径找 */
628
+ export function pathOf(el, root) {
629
+ const path = [];
630
+ let node = el;
631
+ while (node && node !== root && node.parentElement) {
632
+ path.unshift(Array.prototype.indexOf.call(node.parentElement.childNodes, node));
633
+ node = node.parentElement;
634
+ }
635
+ return node === root ? path : null;
636
+ }
637
+
638
+ export function resolvePath(root, path) {
639
+ if (!path?.length) return null;
640
+ let node = root;
641
+ for (const index of path) {
642
+ node = node?.childNodes?.[index] || null;
643
+ if (!node) return null;
644
+ }
645
+ return node.nodeType === Node.ELEMENT_NODE ? node : null;
646
+ }