@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,554 @@
1
+ // [文件] web·editor-kernel·engine·input —— 输入层:快捷键 / 回车退格 Tab / Markdown 输入规则 / 粘贴 / 图片拖入
2
+ // [约束] 按键只走 useKeyboard【强制通道】注册(active 门控 = 编辑器聚焦),禁自行 addEventListener('keydown');
3
+ // beforeinput / input / compositionend / paste / drop 属编辑面自身事件,挂编辑面并在解绑时一并摘掉。
4
+ // [设计] 回车 / Tab / 退格全接管:浏览器默认会在 contenteditable 里造出 `<div>`、嵌套列表等脏结构,
5
+ // 接管后产物口径由 blocks.js 单一决定。
6
+
7
+ import { useKeyboard, KEY_PRIORITY } from '../../keyboard.js';
8
+ import { extractImageFiles } from '../../util/imageFile.js';
9
+ import { eventComboKey } from '../../util/shortcutKey.js';
10
+ import { cleanPastedHtml } from '../pasteClean.js';
11
+ import { parseFragment } from './schema.js';
12
+ import { handleRevisionInput } from './revision.js';
13
+ import { markBlockSlice, canonicalizeInline } from './inline.js';
14
+ import { backspacePlan, insertDivider, liftListItem, listItemOf, setBlockKind, sinkListItem, splitAtCaret } from './blocks.js';
15
+ import { blockLength, blockOf, cellOf, charOffset, closestWithin, domPoint, firstTextBlockIn, hasBlockBody, isBlockEmpty, isTextBlock, moveChildren, rangeOf, setCaret, tableOf } from './dom.js';
16
+
17
+ /** 块级输入规则:整块文本命中即转换(转换后清掉触发文本) */
18
+ const BLOCK_RULES = [
19
+ { re: /^#\s$/, kind: 'heading1' },
20
+ { re: /^##\s$/, kind: 'heading2' },
21
+ { re: /^###\s$/, kind: 'heading3' },
22
+ { re: /^####\s$/, kind: 'heading4' },
23
+ { re: /^#####\s$/, kind: 'heading5' },
24
+ { re: /^######\s$/, kind: 'heading6' },
25
+ { re: /^[-*]\s$/, kind: 'bulletList' },
26
+ { re: /^1\.\s$/, kind: 'orderedList' },
27
+ { re: /^>\s$/, kind: 'blockquote' },
28
+ { re: /^(?:\[[ xX]?\]|\(\s?\))\s$/, kind: 'taskList' },
29
+ { re: /^```$/, kind: 'codeBlock' },
30
+ { re: /^---$/, kind: 'divider' },
31
+ ];
32
+
33
+ /** 行内输入规则:闭合符触发;open / close 为需要抹掉的标记长度 */
34
+ const INLINE_RULES = [
35
+ { re: /\*\*([^*]+)\*\*$/, key: 'bold', open: 2, close: 2 },
36
+ { re: /(?:^|\s)\*([^*\s][^*]*)\*$/, key: 'italic', open: 1, close: 1 },
37
+ { re: /~~([^~]+)~~$/, key: 'strike', open: 2, close: 2 },
38
+ { re: /`([^`]+)`$/, key: 'code', open: 1, close: 1 },
39
+ ];
40
+
41
+ /** 快捷键 → 命令(Mod = Ctrl/Cmd;Mac 上 Mod 取 Cmd;串归一唯一出口见 core/utils/shortcutKey) */
42
+ const SHORTCUTS = {
43
+ 'Mod-z': ['undo'],
44
+ 'Mod-Shift-z': ['redo'],
45
+ 'Mod-y': ['redo'],
46
+ // 显式接管:原生全选在分页结构 / 表格 / 某些浏览器下会只选到局部,甚至因焦点漂移完全不生效
47
+ 'Mod-a': ['selectAll'],
48
+ 'Mod-b': ['toggleBold'],
49
+ 'Mod-i': ['toggleItalic'],
50
+ 'Mod-u': ['toggleUnderline'],
51
+ 'Mod-Shift-x': ['toggleStrike'],
52
+ 'Mod-e': ['toggleCode'],
53
+ // 上下标沿用 Word 键位:Ctrl+= 上标、Ctrl+Shift+=(即 Ctrl++)下标
54
+ 'Mod-=': ['toggleSuperscript'],
55
+ 'Mod-Shift-+': ['toggleSubscript'],
56
+ 'Mod-Shift-7': ['toggleBulletList'],
57
+ 'Mod-Shift-8': ['toggleOrderedList'],
58
+ 'Mod-Shift-9': ['toggleTaskList'],
59
+ 'Mod-Alt-0': ['setParagraph'],
60
+ 'Mod-Alt-1': ['setHeading', 1],
61
+ 'Mod-Alt-2': ['setHeading', 2],
62
+ 'Mod-Alt-3': ['setHeading', 3],
63
+ 'Mod-Alt-4': ['setHeading', 4],
64
+ 'Mod-Alt-5': ['setHeading', 5],
65
+ 'Mod-Alt-6': ['setHeading', 6],
66
+ 'Mod-k': ['requestLink'],
67
+ 'Mod-f': ['requestFind'],
68
+ // 相邻插入沿用思源键位(目标取光标所在块)
69
+ 'Mod-Shift-b': ['insertBlockNear', null, 'before'],
70
+ 'Mod-Shift-a': ['insertBlockNear', null, 'after'],
71
+ };
72
+
73
+ /** 表格内 Tab / Shift+Tab 跳格;末格再 Tab 追加一行 */
74
+ function tabInTable(root, shift) {
75
+ const range = rangeOf(root);
76
+ const cell = range && cellOf(range.startContainer, root);
77
+ if (!cell) return false;
78
+ const table = tableOf(cell, root);
79
+ // 只枚举当前表的格子:嵌套表的 td 也在 table 的 querySelectorAll 结果里,混进来会跳到别的表
80
+ const order = Array.from(table.querySelectorAll('td,th')).filter((item) => item.closest('table') === table);
81
+ const next = order[order.indexOf(cell) + (shift ? -1 : 1)];
82
+ if (next) {
83
+ setCaret(firstTextBlockIn(next, root) || next, 0);
84
+ return true;
85
+ }
86
+ if (shift) return true;
87
+ const row = closestWithin(cell, (el) => el.tagName === 'TR', root);
88
+ const fresh = document.createElement('tr');
89
+ for (const child of Array.from(row.children)) {
90
+ const td = document.createElement(child.tagName.toLowerCase());
91
+ // 追加行沿用当前行的列数口径:跨列格在新行里仍占同样多列
92
+ td.colSpan = Math.max(1, child.colSpan || 1);
93
+ td.appendChild(document.createElement('br'));
94
+ fresh.appendChild(td);
95
+ }
96
+ row.after(fresh);
97
+ // 新行落在首格(与 Word / Notion 一致:末格 Tab 是「开一行接着填」,不是跳到行尾)
98
+ setCaret(firstTextBlockIn(fresh.firstElementChild, root) || fresh.firstElementChild, 0);
99
+ return true;
100
+ }
101
+
102
+ /** 记录块在父级中的位置,转换后据此找回新块(转换会替换元素,旧引用直接失联) */
103
+ function rememberPosition(block) {
104
+ const parent = block.parentElement;
105
+ return { parent, index: Array.from(parent.children).indexOf(block) };
106
+ }
107
+
108
+ function blockRules(editor) {
109
+ const root = editor.root;
110
+ const range = rangeOf(root);
111
+ if (!range || !range.collapsed) return false;
112
+ const block = blockOf(range.startContainer, root);
113
+ if (!block) return false;
114
+ const rule = BLOCK_RULES.find((item) => item.re.test(block.textContent || ''));
115
+ if (!rule) return false;
116
+ editor.run(() => {
117
+ if (rule.kind === 'divider') {
118
+ insertDivider(root);
119
+ return;
120
+ }
121
+ const spot = rememberPosition(block);
122
+ setBlockKind(root, rule.kind, [block]);
123
+ const holder = spot.parent?.children[spot.index] || block;
124
+ const live = firstTextBlockIn(holder, root) || holder;
125
+ live.textContent = '';
126
+ live.appendChild(document.createElement('br'));
127
+ setCaret(live, 0);
128
+ }, { merge: true });
129
+ return true;
130
+ }
131
+
132
+ function inlineRules(editor) {
133
+ const root = editor.root;
134
+ const range = rangeOf(root);
135
+ if (!range || !range.collapsed) return false;
136
+ const block = blockOf(range.startContainer, root);
137
+ if (!block) return false;
138
+ const end = charOffset(block, range.startContainer, range.startOffset);
139
+ const text = (block.textContent || '').slice(0, end);
140
+ const hit = INLINE_RULES.map((rule) => ({ rule, match: text.match(rule.re) })).find((item) => item.match);
141
+ if (!hit) return false;
142
+ const { rule, match } = hit;
143
+ const start = end - match[0].length;
144
+ const innerStart = start + rule.open;
145
+ const innerEnd = innerStart + match[1].length;
146
+ editor.run(() => {
147
+ markBlockSlice(root, block, innerStart, innerEnd, { [rule.key]: true });
148
+ removeChars(block, innerEnd, end);
149
+ removeChars(block, start, innerStart);
150
+ setCaret(block, start + match[1].length);
151
+ }, { merge: true });
152
+ return true;
153
+ }
154
+
155
+ /** 删除块内 [from,to) 字符(行内规则抹触发符用,跨行内壳也能删干净) */
156
+ function removeChars(block, from, to) {
157
+ const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT);
158
+ const cuts = [];
159
+ let acc = 0;
160
+ while (walker.nextNode()) {
161
+ const node = walker.currentNode;
162
+ const size = node.data.length;
163
+ const nodeStart = acc;
164
+ acc += size;
165
+ if (acc <= from || nodeStart >= to) continue;
166
+ cuts.push({ node, start: Math.max(0, from - nodeStart), end: Math.min(size, to - nodeStart) });
167
+ }
168
+ cuts.forEach(({ node, start, end }) => {
169
+ node.data = node.data.slice(0, start) + node.data.slice(end);
170
+ });
171
+ block.normalize();
172
+ }
173
+
174
+ /**
175
+ * 结构摊平:只留文字与行内壳,块与块之间补硬换行
176
+ * 单元格与列表条目在本内核里都是「单一文本块」,容不下第二层块级结构
177
+ */
178
+ function flattenInline(target, nodes) {
179
+ for (const node of nodes) {
180
+ if (node.nodeType === Node.TEXT_NODE) {
181
+ target.appendChild(document.createTextNode(node.data));
182
+ continue;
183
+ }
184
+ const tag = node.tagName;
185
+ if (!tag || /^(BR|IMG|A|STRONG|B|EM|I|U|S|CODE|SPAN)$/.test(tag)) {
186
+ target.appendChild(node.cloneNode(true));
187
+ continue;
188
+ }
189
+ flattenInline(target, Array.from(node.childNodes));
190
+ target.appendChild(document.createElement('br'));
191
+ }
192
+ while (target.lastChild && target.lastChild.tagName === 'BR') target.removeChild(target.lastChild);
193
+ }
194
+
195
+ /** 空文本块补 br:粘贴带出的空段没有 br,只读态会整行消失(与序列化契约同源) */
196
+ function settleEmpty(el) {
197
+ if (!el || el.nodeType !== Node.ELEMENT_NODE) return;
198
+ if (!hasBlockBody(el)) el.appendChild(document.createElement('br'));
199
+ }
200
+
201
+ /** 片段插到光标处:纯行内内容直接并入当前块,含块级结构则先拆块再整块插入 */
202
+ export function insertFragment(editor, fragment) {
203
+ const root = editor.root;
204
+ let range = rangeOf(root);
205
+ if (!range) {
206
+ root.append(...Array.from(fragment.childNodes));
207
+ return;
208
+ }
209
+ const block = blockOf(range.startContainer, root) || root;
210
+ if (!range.collapsed) range.deleteContents();
211
+ // [坑] 光标容器落在 br/img/input 这类空元素上时,Range.insertNode 会把内容塞进空元素内部
212
+ // (粘贴结果等于被吞掉),一律先按「块 + 字符偏移」换算回可承载文字的容器
213
+ const start = range.startContainer;
214
+ if (start.nodeType !== Node.TEXT_NODE && /^(BR|IMG|INPUT)$/.test(start.tagName || '')) {
215
+ const point = domPoint(block, charOffset(block, start, range.startOffset));
216
+ const fixed = document.createRange();
217
+ fixed.setStart(point.node, point.offset);
218
+ fixed.collapse(true);
219
+ range = fixed;
220
+ }
221
+
222
+ const children = Array.from(fragment.children);
223
+ const onlyInline = children.length === 1 && /^(SPAN|STRONG|EM|U|S|CODE|A|B|I|FONT)$/.test(children[0].tagName);
224
+ if (!children.length || onlyInline) {
225
+ const host = onlyInline ? children[0] : null;
226
+ const frag = document.createDocumentFragment();
227
+ moveChildren(host || fragment, frag);
228
+ if (!frag.childNodes.length) return;
229
+ range.insertNode(frag);
230
+ const last = frag.lastChild;
231
+ const caret = document.createRange();
232
+ caret.setStartAfter(last);
233
+ caret.collapse(true);
234
+ const sel = window.getSelection();
235
+ sel.removeAllRanges();
236
+ sel.addRange(caret);
237
+ return;
238
+ }
239
+
240
+ // [坑] 落点在根层(打开文档后直接插块、或焦点回来时没有块级光标)时不能走下面的拆块逻辑:
241
+ // 那里把「当前块到块尾」整段抽出来放进根外的新 <p>,block 就是 root 时会把整篇正文搬空
242
+ if (block === root) {
243
+ range.deleteContents();
244
+ const frag = document.createDocumentFragment();
245
+ for (const child of children) frag.appendChild(child);
246
+ range.insertNode(frag);
247
+ const last = frag.lastChild;
248
+ let next = last?.nextSibling || null;
249
+ while (next && next.nodeType !== Node.ELEMENT_NODE) next = next.nextSibling;
250
+ let target = next ? (isTextBlock(next, root) ? next : firstTextBlockIn(next, root)) : null;
251
+ if (!target) {
252
+ target = document.createElement('p');
253
+ target.appendChild(document.createElement('br'));
254
+ const host = last || (range.startContainer.nodeType === Node.ELEMENT_NODE ? range.startContainer : range.startContainer.parentElement);
255
+ if (host && host !== root) host.after(target);
256
+ else root.appendChild(target);
257
+ }
258
+ setCaret(target, 0);
259
+ return;
260
+ }
261
+
262
+ // [坑] 粘贴落点在单元格或列表条目里时,块不能按「兄弟」插:p 变成 tr/ul 的子节点会当场撕坏
263
+ // 表格网格(列数、格数全错),列表也会长出非法条目——两种落点都摊平/提层后再放
264
+ const cell = cellOf(block, root);
265
+ if (cell) {
266
+ const box = document.createDocumentFragment();
267
+ flattenInline(box, children);
268
+ range.insertNode(box);
269
+ settleEmpty(cell);
270
+ setCaret(cell, blockLength(cell));
271
+ return;
272
+ }
273
+ if (block.tagName === 'LI') {
274
+ const [head, ...rest] = children;
275
+ const box = document.createDocumentFragment();
276
+ flattenInline(box, Array.from(head.childNodes));
277
+ range.insertNode(box);
278
+ if (!rest.length) {
279
+ settleEmpty(block);
280
+ setCaret(block, blockLength(block));
281
+ return;
282
+ }
283
+ const holder = document.createDocumentFragment();
284
+ rest.forEach((el) => {
285
+ settleEmpty(el);
286
+ holder.appendChild(el);
287
+ });
288
+ (block.parentElement || block).after(holder);
289
+ const last = rest[rest.length - 1];
290
+ const target = firstTextBlockIn(last, root) || last;
291
+ setCaret(target, blockLength(target));
292
+ return;
293
+ }
294
+
295
+ const tail = document.createRange();
296
+ tail.setStart(range.startContainer, range.startOffset);
297
+ const point = domPoint(block, blockLength(block));
298
+ tail.setEnd(point.node, point.offset);
299
+ const moved = tail.extractContents();
300
+ const after = document.createElement('p');
301
+ after.appendChild(moved);
302
+ block.after(after);
303
+ for (const child of children) after.before(child);
304
+ // 正文整段搬走后原块只剩空壳,留着就是粘贴带出来的空行
305
+ if (block !== after && isBlockEmpty(block)) block.remove();
306
+ for (const child of children) if (isTextBlock(child, root)) canonicalizeInline(child);
307
+ settleEmpty(after);
308
+ const inserted = after.previousElementSibling;
309
+ const target = firstTextBlockIn(inserted, root) || inserted || block;
310
+ // 只读块(目录/分页符等)内部不能落光标:改落到它后面的尾段,否则接着打字会掉到编辑器外
311
+ if (target.closest?.('[contenteditable="false"]')) setCaret(after, 0);
312
+ else setCaret(target, blockLength(target));
313
+ }
314
+
315
+ function insertPlainText(editor, text) {
316
+ const lines = String(text).split(/\r?\n/);
317
+ if (lines.length === 1) {
318
+ editor.run(() => {
319
+ const node = document.createTextNode(lines[0]);
320
+ const range = rangeOf(editor.root);
321
+ if (range) {
322
+ range.deleteContents();
323
+ range.insertNode(node);
324
+ const caret = document.createRange();
325
+ caret.setStartAfter(node);
326
+ caret.collapse(true);
327
+ const sel = window.getSelection();
328
+ sel.removeAllRanges();
329
+ sel.addRange(caret);
330
+ } else editor.root.appendChild(node);
331
+ });
332
+ return;
333
+ }
334
+ const fragment = document.createDocumentFragment();
335
+ for (const line of lines) {
336
+ const p = document.createElement('p');
337
+ p.textContent = line;
338
+ fragment.appendChild(p);
339
+ }
340
+ editor.run(() => insertFragment(editor, fragment));
341
+ }
342
+
343
+ /** 剪贴板内容是否带行列结构(表格 HTML / 制表符分隔文本)—— 表内粘贴按格子落位的判据 */
344
+ const isTabular = (text, html) => /<table[\s>]/i.test(html || '') || /\t/.test(text || '');
345
+
346
+ /** 粘贴:图片走 base64 内嵌,HTML 先清洗再按块插入(不清洗会把 mso 样式与脚本残留在正文里) */
347
+ function onPaste(editor, event) {
348
+ const data = event.clipboardData;
349
+ if (!data) return;
350
+ const files = extractImageFiles(data);
351
+ if (files.length) {
352
+ event.preventDefault();
353
+ editor.insertImageFiles(files);
354
+ return;
355
+ }
356
+ const html = data.getData('text/html');
357
+ const text = data.getData('text/plain');
358
+ // 单元格内粘贴带行列结构的内容:按格子落位(Excel 口径,不足自动扩表),不走「摊平进当前格」
359
+ // [坑] 必须在普通 HTML 分支之前拦截:否则表结构会被 flattenInline 摊成一行文本,行列表格当场消失
360
+ const range = rangeOf(editor.root);
361
+ if (isTabular(text, html) && range && cellOf(range.startContainer, editor.root)) {
362
+ event.preventDefault();
363
+ editor.pasteTableData({ text, html });
364
+ return;
365
+ }
366
+ if (html) {
367
+ event.preventDefault();
368
+ editor.run(() => insertFragment(editor, parseFragment(cleanPastedHtml(html))));
369
+ return;
370
+ }
371
+ if (text) {
372
+ event.preventDefault();
373
+ insertPlainText(editor, text);
374
+ }
375
+ }
376
+
377
+ /** 拖入图片:按落点插入并 preventDefault,外层壳据 defaultPrevented 让行(否则同一次拖入插两遍) */
378
+ function onDrop(editor, event) {
379
+ const files = extractImageFiles(event.dataTransfer);
380
+ if (!files.length) return;
381
+ event.preventDefault();
382
+ const doc = editor.root.ownerDocument;
383
+ // Chromium 走 caretRangeFromPoint,Firefox 只有 caretPositionFromPoint(标准 API)
384
+ let point = doc.caretRangeFromPoint?.(event.clientX, event.clientY) || null;
385
+ if (!point && doc.caretPositionFromPoint) {
386
+ const pos = doc.caretPositionFromPoint(event.clientX, event.clientY);
387
+ if (pos) {
388
+ point = doc.createRange();
389
+ point.setStart(pos.offsetNode, pos.offset);
390
+ point.collapse(true);
391
+ }
392
+ }
393
+ if (point && editor.root.contains(point.startContainer)) {
394
+ const sel = window.getSelection();
395
+ sel.removeAllRanges();
396
+ sel.addRange(point);
397
+ }
398
+ editor.insertImageFiles(files);
399
+ }
400
+
401
+ /** 待定标记落回刚输入的文字(非截断路径:输入法上屏后补壳)
402
+ * [坑] 只能标「本次上屏的字符」:从块首标到光标会把光标前的存量文字整段重打标记 */
403
+ function applyPendingAfterInput(editor, committed) {
404
+ if (!editor.hasPendingMarks()) return;
405
+ const size = String(committed || '').length;
406
+ if (!size) return;
407
+ const root = editor.root;
408
+ const range = rangeOf(root);
409
+ const block = range && blockOf(range.startContainer, root);
410
+ if (!block) return;
411
+ const end = charOffset(block, range.startContainer, range.startOffset);
412
+ const start = Math.max(0, end - size);
413
+ const marks = editor.pending;
414
+ editor.run(() => markBlockSlice(root, block, start, end, marks));
415
+ }
416
+
417
+ /**
418
+ * 绑定输入层
419
+ * @param {object} editor EditorCore 实例
420
+ * @returns {() => void} 解绑
421
+ */
422
+ export function attachInput(editor) {
423
+ const root = editor.root;
424
+
425
+ const handleKeydown = (event) => {
426
+ if (!editor.isFocused() || event.defaultPrevented) return false;
427
+
428
+ const mapped = SHORTCUTS[eventComboKey(event) || ''];
429
+ if (mapped) {
430
+ event.preventDefault();
431
+ event.stopPropagation();
432
+ if (mapped[0] === 'requestLink') editor.emit('request-link');
433
+ else if (mapped[0] === 'requestFind') editor.emit('open-find');
434
+ else editor.exec(mapped[0], ...mapped.slice(1));
435
+ return true;
436
+ }
437
+
438
+ if (event.key === 'Enter') {
439
+ if (editor.isMenuOpen()) return false; // 斜杠菜单展开时回车归菜单(选中命令)
440
+ event.preventDefault();
441
+ event.stopPropagation();
442
+ editor.run(() => splitAtCaret(root, event.shiftKey));
443
+ return true;
444
+ }
445
+ if (event.key === 'Backspace') {
446
+ const plan = backspacePlan(root);
447
+ if (!plan) return false;
448
+ event.preventDefault();
449
+ event.stopPropagation();
450
+ editor.run(plan);
451
+ return true;
452
+ }
453
+ if (event.key === 'Tab') {
454
+ event.preventDefault();
455
+ event.stopPropagation();
456
+ editor.run(() => handleTab(editor, event.shiftKey));
457
+ return true;
458
+ }
459
+ return false;
460
+ };
461
+
462
+ const offKeys = useKeyboard({ keydown: handleKeydown }, { priority: KEY_PRIORITY.APPLET, active: () => editor.isFocused() });
463
+
464
+ /** 折叠光标 + 有待定标记时接管键入:先插文字再包壳,避免浏览器插进已有壳里 */
465
+ const handleBeforeInput = (event) => {
466
+ // 建议修改模式:键入/删除先走修订拦截;未处理(如非文本边界)放行浏览器默认行为。
467
+ // [设计] 不包 run():改动交给编辑面的 MutationObserver 记账(与正常打字同一条历史合并/上报链,连续输入合并成一条撤销)
468
+ if (editor.suggesting && handleRevisionInput(root, event)) {
469
+ event.preventDefault();
470
+ return;
471
+ }
472
+ if (event.inputType !== 'insertText' || !editor.hasPendingMarks()) return;
473
+ const range = rangeOf(root);
474
+ if (!range || !range.collapsed) return;
475
+ const data = event.data || '';
476
+ event.preventDefault();
477
+ editor.run(() => {
478
+ const node = document.createTextNode(data);
479
+ range.insertNode(node);
480
+ const block = blockOf(node, root);
481
+ if (!block) return;
482
+ const end = charOffset(block, node, node.data.length);
483
+ markBlockSlice(root, block, end - data.length, end, editor.pending);
484
+ const caret = document.createRange();
485
+ caret.setStartAfter(node.parentElement?.lastChild || node);
486
+ caret.collapse(true);
487
+ const sel = window.getSelection();
488
+ sel.removeAllRanges();
489
+ sel.addRange(caret);
490
+ });
491
+ };
492
+
493
+ const handleInput = (event) => {
494
+ // 组合期间的中间态归输入法:此时重建正文 DOM 会打断候选状态
495
+ if (editor.composing || event.isComposing) return;
496
+ if (event.inputType === 'deleteContentBackward' || event.inputType === 'deleteContentForward') editor.clearPendingMarks();
497
+ if (event.inputType === 'insertText' || event.inputType === 'insertCompositionText') {
498
+ if (inlineRules(editor)) return;
499
+ blockRules(editor);
500
+ return;
501
+ }
502
+ if (event.inputType === 'insertParagraph' || event.inputType === 'insertLineBreak') blockRules(editor);
503
+ };
504
+
505
+ /** [坑] 组合期间宿主排版会拆装正文 DOM,输入法候选当场被打断——composing 立起来让宿主挂起,
506
+ * 上屏后再补一次变更上报(正文此时已定),宿主据此补上延迟的那次重排 */
507
+ const handleCompositionStart = () => {
508
+ editor.composing = true;
509
+ };
510
+ const handleCompositionEnd = (event) => {
511
+ editor.composing = false;
512
+ applyPendingAfterInput(editor, event?.data);
513
+ editor.emit('update');
514
+ };
515
+ const handlePaste = (event) => onPaste(editor, event);
516
+ const handleDrop = (event) => onDrop(editor, event);
517
+ const handleDragOver = (event) => {
518
+ if (event.dataTransfer?.types?.includes('Files')) event.preventDefault();
519
+ };
520
+
521
+ root.addEventListener('beforeinput', handleBeforeInput);
522
+ root.addEventListener('input', handleInput);
523
+ root.addEventListener('compositionstart', handleCompositionStart);
524
+ root.addEventListener('compositionend', handleCompositionEnd);
525
+ root.addEventListener('paste', handlePaste);
526
+ root.addEventListener('drop', handleDrop);
527
+ root.addEventListener('dragover', handleDragOver);
528
+
529
+ return () => {
530
+ offKeys();
531
+ root.removeEventListener('beforeinput', handleBeforeInput);
532
+ root.removeEventListener('input', handleInput);
533
+ root.removeEventListener('compositionstart', handleCompositionStart);
534
+ root.removeEventListener('compositionend', handleCompositionEnd);
535
+ root.removeEventListener('paste', handlePaste);
536
+ root.removeEventListener('drop', handleDrop);
537
+ root.removeEventListener('dragover', handleDragOver);
538
+ };
539
+ }
540
+
541
+ /** Tab:表格跳格 → 列表升降级 → 块缩进 */
542
+ function handleTab(editor, shift) {
543
+ const root = editor.root;
544
+ if (tabInTable(root, shift)) return;
545
+ const range = rangeOf(root);
546
+ const block = range && blockOf(range.startContainer, root);
547
+ const li = block ? listItemOf(block, root) : null;
548
+ if (li) {
549
+ if (shift) {
550
+ if (liftListItem(li)) return;
551
+ } else if (sinkListItem(li)) return;
552
+ }
553
+ editor.exec(shift ? 'decreaseBlockIndent' : 'increaseBlockIndent');
554
+ }
@@ -0,0 +1,137 @@
1
+ // [文件] web·editor-kernel·engine·interaction —— 编辑面交互事件处理器(焦点/选区变化/点击原子块/待办勾选)(混入 EditorCore.prototype)
2
+ // [约束] 带 `on*` 前缀的成员是直接挂到编辑面上的事件处理器:由 editor.js 构造时统一 bind(this),
3
+ // 以便 addEventListener / removeEventListener 拿到同一引用(等价原箭头函数字段的绑定语义)。
4
+ import * as D from './dom.js';
5
+ import * as I from './inline.js';
6
+
7
+ /** 需在构造时 bind(this) 的事件处理器名(挂 root/document 监听,必须引用稳定) */
8
+ export const INTERACTION_HANDLERS = ['onFocus', 'onBlur', 'onSelectionChange', 'onPointerState', 'onClick', 'onCheckboxChange'];
9
+
10
+ /** 交互事件方法(装配到 EditorCore.prototype;this 为内核实例) */
11
+ export const interactionMethods = {
12
+ onFocus() {
13
+ this.emit('focus');
14
+ },
15
+
16
+ onBlur() {
17
+ const sel = this.captureSelection();
18
+ if (sel) this.savedRange = sel;
19
+ this.clearBlockSelection();
20
+ this.emit('blur');
21
+ },
22
+
23
+ onSelectionChange() {
24
+ if (!this.isFocused()) return;
25
+ const sel = this.captureSelection();
26
+ if (sel) this.savedRange = sel;
27
+ const range = D.rangeOf(this.root);
28
+ this.pending = range && range.collapsed ? { ...this.inlineSnapshot() } : null;
29
+ this.syncBlockSelection();
30
+ this.syncState();
31
+ this.emit('selection');
32
+ this.emit('selectionUpdate');
33
+ },
34
+
35
+ /** 清掉选区跨块高亮(运行期类) */
36
+ clearBlockSelection() {
37
+ for (const el of Array.from(this.root.querySelectorAll(`.${D.BLOCK_SELECTED}`))) el.classList.remove(D.BLOCK_SELECTED);
38
+ },
39
+
40
+ /**
41
+ * 选区跨块高亮:非折叠选区覆盖到的顶层块整块加淡蓝底(与块标悬浮高亮 gbd-is-block-hover 各管各的)。
42
+ * [设计] 用顶层块(root.children)作高亮单位:选区落在引用/高亮块内部的段落时,高亮的是整个容器,与用户「选中的块」直觉一致。
43
+ * [坑] 桌面式框选(blockMarqueeActive)期间高亮归框选管,本方法直接让位,否则会被每次 selectionchange 抹掉。
44
+ */
45
+ syncBlockSelection() {
46
+ if (this.blockMarqueeActive) return;
47
+ this.clearBlockSelection();
48
+ const range = D.rangeOf(this.root);
49
+ if (!range || range.collapsed) return;
50
+ for (const el of Array.from(this.root.children)) {
51
+ if (D.isRuntimeBlock(el)) continue;
52
+ if (range.intersectsNode(el)) el.classList.add(D.BLOCK_SELECTED);
53
+ }
54
+ },
55
+
56
+ /**
57
+ * 桌面式框选:按客户端矩形给被覆盖到的顶层块打选区高亮(不产生原生 Range,纯视觉块选)。
58
+ * [设计] 用客户端坐标做命中(getBoundingClientRect 同基准),宿主不必换算缩放;
59
+ * 每次调用全量重算并 toggle(移出框的块自动撤高亮),返回命中数供宿主决定是否显示「已选 N 块」。
60
+ */
61
+ marqueeSelect(clientRect) {
62
+ let hits = 0;
63
+ for (const el of Array.from(this.root.children)) {
64
+ if (D.isRuntimeBlock(el)) continue;
65
+ const r = el.getBoundingClientRect();
66
+ const hit = r.width > 0 && r.height > 0 && !(r.left > clientRect.right || r.right < clientRect.left || r.top > clientRect.bottom || r.bottom < clientRect.top);
67
+ el.classList.toggle(D.BLOCK_SELECTED, hit);
68
+ if (hit) hits += 1;
69
+ }
70
+ return hits;
71
+ },
72
+
73
+ onPointerState() {
74
+ this.syncState();
75
+ },
76
+
77
+ /** 折叠光标 → 待定标记态(工具栏切了标记再打字才生效,与主流编辑器一致)。
78
+ * [坑] 判据必须是「与光标处当前格式不同」:在加粗文字里关掉加粗时 pending 全是 false,
79
+ * 只看真值会当成没有待定标记,浏览器直接把新字插进加粗壳里 */
80
+ hasPendingMarks() {
81
+ const marks = this.pending;
82
+ if (!marks) return false;
83
+ const current = this.inlineSnapshot();
84
+ const same = (a, b) => String(a ?? '').trim().toLowerCase() === String(b ?? '').trim().toLowerCase();
85
+ return I.TAG_MARKS.some((key) => Boolean(marks[key]) !== Boolean(current[key]))
86
+ || I.TEXT_STYLE_MARKS.some((key) => !same(marks[key], current[key]))
87
+ || !same(marks.link, current.link);
88
+ },
89
+
90
+ clearPendingMarks() {
91
+ this.pending = null;
92
+ },
93
+
94
+ onClick(event) {
95
+ const target = event.target;
96
+ if (target?.tagName === 'A' && !this.isFocused()) {
97
+ event.preventDefault();
98
+ return;
99
+ }
100
+ const atom = closestAtom(this.root, target);
101
+ // [坑] 只读档(contenteditable=false)点击照样命中原子块,但选中装饰与缩放手柄都是改文档的手段,
102
+ // 只读下必须不给;只留「点图放大」这一条读路径(宿主在 EditorSurface 上挂)
103
+ if (atom && this.isEditable()) this.selectAtom(atom);
104
+ else this.clearAtom();
105
+ },
106
+
107
+ /** 待办条目复选框:change 同步 data-checked(序列化口径) */
108
+ onCheckboxChange(event) {
109
+ const input = event.target;
110
+ if (input?.tagName !== 'INPUT' || input.type !== 'checkbox') return;
111
+ const li = input.closest('li[data-checked]');
112
+ if (!li) return;
113
+ this.run(() => {
114
+ li.setAttribute('data-checked', input.checked ? 'true' : 'false');
115
+ });
116
+ },
117
+
118
+ /** 选中原子块(图片 / 分割线):运行期类名,序列化时剥掉 */
119
+ selectAtom(el) {
120
+ this.clearAtom();
121
+ this.selectedAtom = el;
122
+ el.classList.add(D.ATOM_SELECTED);
123
+ this.emit('atom', el);
124
+ },
125
+
126
+ clearAtom() {
127
+ if (this.selectedAtom) this.selectedAtom.classList.remove(D.ATOM_SELECTED);
128
+ this.selectedAtom = null;
129
+ this.emit('atom', null);
130
+ },
131
+ };
132
+
133
+ function closestAtom(root, node) {
134
+ if (!node) return null;
135
+ const el = node.nodeType === Node.TEXT_NODE ? node.parentElement : node;
136
+ return D.closestWithin(el, (item) => item.tagName === 'IMG' || item.tagName === 'HR', root);
137
+ }