@a200888213/gbdocx 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/package.json +1 -1
  2. package/src/app/file-io.js +122 -122
  3. package/src/app/main.js +9 -9
  4. package/src/app/word/catalog.js +52 -52
  5. package/src/app/word/comments.js +112 -112
  6. package/src/app/word/doc.js +113 -113
  7. package/src/app/word/edit.js +72 -72
  8. package/src/app/word/hf.js +76 -76
  9. package/src/app/word/layout.js +155 -155
  10. package/src/app/word/notes.js +110 -110
  11. package/src/app/word/shared.js +22 -22
  12. package/src/app/word/view.js +3 -0
  13. package/src/app/word-app.js +1 -0
  14. package/src/app/word-sheets.js +101 -101
  15. package/src/kernel/docx/codec/blocks.js +123 -123
  16. package/src/kernel/docx/codec/carry.js +129 -129
  17. package/src/kernel/docx/codec/comments.js +25 -25
  18. package/src/kernel/docx/codec/docx.js +198 -198
  19. package/src/kernel/docx/codec/docxStyles.js +177 -177
  20. package/src/kernel/docx/codec/fonts.js +195 -195
  21. package/src/kernel/docx/codec/helpers.js +161 -161
  22. package/src/kernel/docx/codec/hfHtml.js +152 -152
  23. package/src/kernel/docx/codec/html.js +739 -739
  24. package/src/kernel/docx/codec/losses.js +420 -420
  25. package/src/kernel/docx/codec/markdown.js +170 -170
  26. package/src/kernel/docx/codec/parts.js +249 -249
  27. package/src/kernel/docx/codec/read.js +603 -603
  28. package/src/kernel/docx/codec/render.js +1156 -1156
  29. package/src/kernel/docx/codec/roundtrip.js +236 -236
  30. package/src/kernel/docx/codec/write.js +833 -833
  31. package/src/kernel/docx/comments.js +14 -14
  32. package/src/kernel/docx/pageGeometry.js +123 -123
  33. package/src/kernel/docx/pagination.js +481 -481
  34. package/src/kernel/docx/watermark.js +45 -45
  35. package/src/kernel/editor/constants.js +8 -8
  36. package/src/kernel/editor/engine/blocks.js +594 -594
  37. package/src/kernel/editor/engine/blocksEnter.js +109 -109
  38. package/src/kernel/editor/engine/blocksInsert.js +254 -254
  39. package/src/kernel/editor/engine/blocksStructure.js +226 -226
  40. package/src/kernel/editor/engine/commands.js +181 -181
  41. package/src/kernel/editor/engine/dom.js +646 -646
  42. package/src/kernel/editor/engine/history.js +149 -149
  43. package/src/kernel/editor/engine/inline.js +656 -656
  44. package/src/kernel/editor/engine/input.js +554 -554
  45. package/src/kernel/editor/engine/interaction.js +137 -137
  46. package/src/kernel/editor/engine/pointer.js +39 -39
  47. package/src/kernel/editor/engine/revision.js +138 -138
  48. package/src/kernel/editor/engine/schema.js +417 -417
  49. package/src/kernel/editor/engine/selection.js +119 -119
  50. package/src/kernel/editor/engine/state.js +118 -118
  51. package/src/kernel/editor/engine/tableClip.js +154 -154
  52. package/src/kernel/editor/engine/tableGrid.js +55 -55
  53. package/src/kernel/editor/engine/tableInteraction.js +388 -388
  54. package/src/kernel/editor/engine/tableMenu.js +250 -250
  55. package/src/kernel/editor/engine/tableOps.js +174 -174
  56. package/src/kernel/editor/engine/tables.js +732 -732
  57. package/src/kernel/editor/overlayGeometry.js +20 -20
  58. package/src/kernel/editor/utils.js +48 -48
  59. package/src/kernel/keyboard.js +114 -114
  60. package/src/kernel/textStyles.js +84 -84
  61. package/src/kernel/util/imageFile.js +91 -91
  62. package/src/kernel/util/shortcutKey.js +33 -33
  63. package/src/surface/editor-surface.js +600 -600
  64. package/src/ui/color-panel.js +69 -69
  65. package/src/ui/context-menu.js +133 -133
  66. package/src/ui/find-bar.js +151 -151
  67. package/src/ui/menubar.js +28 -28
  68. package/src/ui/panels.js +115 -115
  69. package/src/ui/prompt.js +89 -89
  70. package/src/ui/ribbon.js +485 -485
  71. package/src/ui/special-chars.js +39 -39
  72. package/src/ui/statusbar.js +81 -81
  73. package/src/ui/toolbar.js +32 -32
  74. package/styles/editor-content.css +440 -440
  75. package/styles/tokens.css +154 -154
  76. package/styles/word-panel.css +1 -1
@@ -1,656 +1,656 @@
1
- // [文件] web·editor-kernel·engine·inline —— 行内片段模型:读取 / 规范化重建 / 行内命令与状态查询
2
- // [设计] 行内样式统一走「把块内正文读成片段序列 → 打补丁 → 整块规范化重建」而不是逐节点 split/unwrap:
3
- // 片段带完整标记签名,重建时相邻同签名片段自动合并,产物永远是规范形态
4
- // (不会出现 `<strong><strong>`、空 `<span>` 这类越编辑越脏的结构),也不必维护边界拆分那套易错逻辑。
5
- // [约束] 块级属性(行高 / 对齐 / 缩进)不在本文件:那是挂在块元素内联 style 上的,见 blocks.js。
6
-
7
- import { ATTACH_ATTR, COMMENT_ATTR, DOC_CLASS, NOTE_ATTR, REF_BLOCK_ATTR, REF_DOC_ATTR, REF_SUB_ATTR, THEME_COLOR_ATTR, THEME_SHADE_ATTR, THEME_TINT_ATTR } from './schema.js';
8
- import { RUNTIME_CLASSES, rangeOf, unwrapElement } from './dom.js';
9
- import { normalizeColor } from 'guabiutils';
10
- import { isSafeHref, sanitizeFontName } from '../../util/safeValue.js';
11
-
12
- /** 标签 → 标记键(HTML 行内标签别名的唯一数据源:docx 编解码读取侧同引此表,禁各自再拼一份)
13
- * [设计] 不含 DEL:HTML 的 <del> 在 docx 语境承载修订语义(走 REV_TAGS),删除线归属由 docx 读取侧单独并入 */
14
- export const TAG_TO_MARK = {
15
- STRONG: 'bold',
16
- B: 'bold',
17
- EM: 'italic',
18
- I: 'italic',
19
- U: 'underline',
20
- S: 'strike',
21
- STRIKE: 'strike',
22
- CODE: 'code',
23
- TT: 'code',
24
- SUP: 'superscript',
25
- SUB: 'subscript',
26
- };
27
-
28
- /** 修订标记标签 → rev 取值(ins/del 是结构标记,不与下划线/删除线混同——
29
- * 混同会把 .docx 修订语义在任意一次编辑重建时抹掉) */
30
- const REV_TAGS = { INS: 'ins', DEL: 'del' };
31
-
32
- /** 标记键 → 标签(由内向外包裹顺序) */
33
- const MARK_TO_TAG = { bold: 'strong', italic: 'em', underline: 'u', strike: 's', code: 'code', superscript: 'sup', subscript: 'sub' };
34
-
35
- /** 内联样式 → 标记键 */
36
- const STYLE_KEYS = [
37
- ['color', 'color'],
38
- ['background-color', 'backgroundColor'],
39
- ['font-size', 'fontSize'],
40
- ['font-family', 'fontFamily'],
41
- ['-webkit-text-stroke', 'textStroke'],
42
- ['text-shadow', 'textShadow'],
43
- ];
44
-
45
- /** 标记键 → 内联样式属性 */
46
- const MARK_STYLE = { color: 'color', backgroundColor: 'background-color', fontSize: 'font-size', fontFamily: 'font-family', textStroke: '-webkit-text-stroke', textShadow: 'text-shadow' };
47
-
48
- export const TEXT_STYLE_MARKS = ['color', 'backgroundColor', 'fontSize', 'fontFamily', 'textStroke', 'textShadow'];
49
-
50
- /** 需要 hex 归一的标记键(其余样式属性原样透传) */
51
- const COLOR_KEYS = new Set(['color', 'backgroundColor']);
52
- export const TAG_MARKS = ['bold', 'italic', 'underline', 'strike', 'code', 'superscript', 'subscript'];
53
-
54
- function emptyMarks() {
55
- return {
56
- bold: false,
57
- italic: false,
58
- underline: false,
59
- strike: false,
60
- code: false,
61
- superscript: false,
62
- subscript: false,
63
- link: '',
64
- rev: '',
65
- cmt: '',
66
- color: '',
67
- colorTheme: '',
68
- colorThemeTint: '',
69
- colorThemeShade: '',
70
- backgroundColor: '',
71
- fontSize: '',
72
- fontFamily: '',
73
- textStroke: '',
74
- textShadow: '',
75
- };
76
- }
77
-
78
- function marksEqual(a, b) {
79
- return TAG_MARKS.every((key) => !!a[key] === !!b[key]) && TEXT_STYLE_MARKS.every((key) => norm(a[key]) === norm(b[key])) && norm(a.link) === norm(b.link) && a.rev === b.rev && a.cmt === b.cmt && a.colorTheme === b.colorTheme && a.colorThemeTint === b.colorThemeTint && a.colorThemeShade === b.colorThemeShade;
80
- }
81
-
82
- /** 颜色 / 字号比较忽略大小写与多余空格 */
83
- function norm(value) {
84
- return String(value ?? '')
85
- .trim()
86
- .toLowerCase();
87
- }
88
-
89
- /** 片段字符数:硬换行不占位(与 dom.js 的偏移口径一致),图片算 1 */
90
- const segLength = (seg) => (seg.text ? seg.text.length : seg.br ? 0 : 1);
91
-
92
- /* ===================== 读:DOM → 片段 ===================== */
93
-
94
- function readInto(parent, marks, out) {
95
- for (const child of Array.from(parent.childNodes)) {
96
- if (child.nodeType === Node.TEXT_NODE) {
97
- if (child.data) out.push({ text: child.data, m: { ...marks } });
98
- continue;
99
- }
100
- if (child.nodeType !== Node.ELEMENT_NODE) continue;
101
- if (child.tagName === 'LABEL') continue; // 待办复选框不是正文
102
- // 运行期装饰壳(高亮等)只穿透取内容,不进片段
103
- if (RUNTIME_CLASSES.some((name) => child.classList?.contains(name))) {
104
- readInto(child, marks, out);
105
- continue;
106
- }
107
- if (child.tagName === 'BR') {
108
- out.push({ br: true, m: { ...marks } });
109
- continue;
110
- }
111
- if (child.tagName === 'IMG') {
112
- out.push({
113
- img: {
114
- src: child.getAttribute('src') || '',
115
- alt: child.getAttribute('alt') || '',
116
- width: child.getAttribute('width') || '',
117
- height: child.getAttribute('height') || '',
118
- },
119
- m: { ...marks },
120
- });
121
- continue;
122
- }
123
- // 脚注/尾注锚点按原子片段保留(带 data-fn 的 sup 不是普通上标;不做原子化会在整块重建时丢引用)
124
- if (child.tagName === 'SUP' && (child.classList.contains(DOC_CLASS.FOOTNOTE) || child.classList.contains(DOC_CLASS.ENDNOTE))) {
125
- out.push({
126
- note: {
127
- id: child.getAttribute(NOTE_ATTR) || '',
128
- end: child.classList.contains(DOC_CLASS.ENDNOTE),
129
- ord: child.textContent || '',
130
- },
131
- m: { ...marks },
132
- });
133
- continue;
134
- }
135
- // 笔记行内锚按属性识别(粘贴链会剥 class):原子片段建模,整块重建时按此回写
136
- if (child.hasAttribute(ATTACH_ATTR)) {
137
- out.push({ attach: { id: child.getAttribute(ATTACH_ATTR) || '', name: child.textContent || '' }, m: { ...marks } });
138
- continue;
139
- }
140
- if (child.hasAttribute(REF_DOC_ATTR)) {
141
- out.push({
142
- ref: {
143
- docId: child.getAttribute(REF_DOC_ATTR) || '',
144
- blockId: child.getAttribute(REF_BLOCK_ATTR) || '',
145
- sub: child.getAttribute(REF_SUB_ATTR) || 'd',
146
- text: child.textContent || '',
147
- },
148
- m: { ...marks },
149
- });
150
- continue;
151
- }
152
- let next = marks;
153
- const tagMark = TAG_TO_MARK[child.tagName];
154
- if (tagMark) next = { ...next, [tagMark]: true };
155
- const rev = REV_TAGS[child.tagName];
156
- if (rev) next = { ...next, rev };
157
- if (child.tagName === 'SPAN' && child.classList?.contains(DOC_CLASS.COMMENT)) {
158
- next = { ...next, cmt: child.getAttribute(COMMENT_ATTR) || '' };
159
- }
160
- for (const [prop, key] of STYLE_KEYS) {
161
- const value = child.style?.getPropertyValue(prop)?.trim();
162
- if (!value) continue;
163
- next = { ...next, [key]: COLOR_KEYS.has(key) ? normalizeColor(value) : value };
164
- }
165
- if (child.tagName === 'A') next = { ...next, link: child.getAttribute('href') || '' };
166
- // 主题色引用(读入渲染带出的 data 属性;显式 color 与引用并存时两者都带,写回端按引用优先)
167
- const themeName = child.getAttribute(THEME_COLOR_ATTR);
168
- if (themeName) {
169
- next = {
170
- ...next,
171
- colorTheme: themeName,
172
- colorThemeTint: child.getAttribute(THEME_TINT_ATTR) || '',
173
- colorThemeShade: child.getAttribute(THEME_SHADE_ATTR) || ''
174
- };
175
- }
176
- readInto(child, next, out);
177
- }
178
- }
179
-
180
- function readSegments(block) {
181
- const segs = [];
182
- if (block) readInto(block, emptyMarks(), segs);
183
- return segs;
184
- }
185
-
186
- /* ===================== 写:片段 → DOM ===================== */
187
-
188
- function leafOf(seg) {
189
- if (seg.text) return document.createTextNode(seg.text);
190
- if (seg.br) return document.createElement('br');
191
- if (seg.note) {
192
- const sup = document.createElement('sup');
193
- sup.className = seg.note.end ? DOC_CLASS.ENDNOTE : DOC_CLASS.FOOTNOTE;
194
- sup.setAttribute(NOTE_ATTR, seg.note.id);
195
- sup.setAttribute('contenteditable', 'false');
196
- sup.textContent = seg.note.ord || '';
197
- return sup;
198
- }
199
- if (seg.attach || seg.ref) return anchorLeafOf(seg);
200
- const img = document.createElement('img');
201
- if (seg.img.src) img.setAttribute('src', seg.img.src);
202
- img.setAttribute('alt', seg.img.alt || '');
203
- for (const key of ['width', 'height']) if (seg.img[key]) img.setAttribute(key, seg.img[key]);
204
- return img;
205
- }
206
-
207
- /** 笔记行内锚叶子(附件引用/块引用):整枚原子,重建时按片段还原(contenteditable=false 与 nodeChars 的 1 字符位口径配套) */
208
- function anchorLeafOf(seg) {
209
- const span = document.createElement('span');
210
- if (seg.attach) {
211
- span.className = DOC_CLASS.ATTACH;
212
- span.setAttribute(ATTACH_ATTR, seg.attach.id);
213
- span.textContent = seg.attach.name || '';
214
- } else {
215
- span.className = DOC_CLASS.REF;
216
- span.setAttribute(REF_DOC_ATTR, seg.ref.docId);
217
- if (seg.ref.blockId) span.setAttribute(REF_BLOCK_ATTR, seg.ref.blockId);
218
- span.setAttribute(REF_SUB_ATTR, seg.ref.sub === 's' ? 's' : 'd');
219
- span.textContent = seg.ref.text || '';
220
- }
221
- span.setAttribute('contenteditable', 'false');
222
- return span;
223
- }
224
-
225
- /** 按规范嵌套包壳(strong 最内、a 最外);入参可以是单叶子或整组的 fragment */
226
- function wrapMarks(marks, node) {
227
- for (const key of ['code', 'strike', 'underline', 'italic', 'superscript', 'subscript', 'bold']) {
228
- if (!marks[key]) continue;
229
- const el = document.createElement(MARK_TO_TAG[key]);
230
- el.appendChild(node);
231
- node = el;
232
- }
233
- const style = TEXT_STYLE_MARKS.filter((key) => marks[key]).map((key) => `${MARK_STYLE[key]}: ${marks[key]}`);
234
- if (style.length || marks.colorTheme) {
235
- const span = document.createElement('span');
236
- if (style.length) span.setAttribute('style', style.join('; '));
237
- if (marks.colorTheme) {
238
- span.setAttribute(THEME_COLOR_ATTR, marks.colorTheme);
239
- if (marks.colorThemeTint) span.setAttribute(THEME_TINT_ATTR, marks.colorThemeTint);
240
- if (marks.colorThemeShade) span.setAttribute(THEME_SHADE_ATTR, marks.colorThemeShade);
241
- }
242
- span.appendChild(node);
243
- node = span;
244
- }
245
- // 结构标记在样式壳之外、链接之内:批注范围最外(可包住整段修订),修订其次
246
- if (marks.rev) {
247
- const rev = document.createElement(marks.rev === 'del' ? 'del' : 'ins');
248
- rev.className = marks.rev === 'del' ? DOC_CLASS.DEL : DOC_CLASS.INS;
249
- rev.appendChild(node);
250
- node = rev;
251
- }
252
- if (marks.cmt) {
253
- const span = document.createElement('span');
254
- span.className = DOC_CLASS.COMMENT;
255
- span.setAttribute(COMMENT_ATTR, marks.cmt);
256
- span.appendChild(node);
257
- node = span;
258
- }
259
- if (marks.link) {
260
- const a = document.createElement('a');
261
- a.setAttribute('href', marks.link);
262
- a.setAttribute('target', '_blank');
263
- a.setAttribute('rel', 'noopener noreferrer nofollow');
264
- a.appendChild(node);
265
- node = a;
266
- }
267
- return node;
268
- }
269
-
270
- /** 相邻同签名片段合成一组、共用一层壳(拆边界后必须合回来,否则正文里全是 <strong><strong>) */
271
- function renderSegments(segs) {
272
- const frag = document.createDocumentFragment();
273
- let group = [];
274
- let groupMarks = null;
275
- const flush = () => {
276
- if (!group.length) return;
277
- const inner = document.createDocumentFragment();
278
- for (const seg of group) inner.appendChild(leafOf(seg));
279
- frag.appendChild(wrapMarks(groupMarks, inner));
280
- group = [];
281
- groupMarks = null;
282
- };
283
- for (const seg of segs) {
284
- if (groupMarks && marksEqual(groupMarks, seg.m)) {
285
- group.push(seg);
286
- continue;
287
- }
288
- flush();
289
- group = [seg];
290
- groupMarks = seg.m;
291
- }
292
- flush();
293
- return frag;
294
- }
295
-
296
- /* ===================== 片段切片与打补丁 ===================== */
297
-
298
- /** 按字符区间 [start,end) 把片段切成 before / inside / after 三段(边界处拆片段) */
299
- function splitAt(segs, start, end) {
300
- const before = [];
301
- const inside = [];
302
- const after = [];
303
- let cursor = 0;
304
- for (const seg of segs) {
305
- const size = segLength(seg);
306
- const segStart = cursor;
307
- const segEnd = cursor + size;
308
- cursor = segEnd;
309
- if (segEnd <= start) {
310
- before.push(seg);
311
- continue;
312
- }
313
- if (segStart >= end) {
314
- after.push(seg);
315
- continue;
316
- }
317
- if (!seg.text) {
318
- // 原子片段(图 / 换行)不可切:整枚归属
319
- (segStart >= start && segEnd <= end ? inside : segStart < start ? before : after).push(seg);
320
- continue;
321
- }
322
- const cutStart = Math.max(0, start - segStart);
323
- const cutEnd = Math.min(size, end - segStart);
324
- if (cutStart > 0) before.push({ text: seg.text.slice(0, cutStart), m: { ...seg.m } });
325
- if (cutEnd > cutStart) inside.push({ text: seg.text.slice(cutStart, cutEnd), m: { ...seg.m } });
326
- if (cutEnd < size) after.push({ text: seg.text.slice(cutEnd), m: { ...seg.m } });
327
- }
328
- return { before, inside, after };
329
- }
330
-
331
- /**
332
- * 对块内 [start,end) 施加行内补丁
333
- * @param {object} patch { set?:{key:bool}, style?:{color:value|null}, link?:href|null, clear?:true }
334
- * @returns {boolean} 是否真的改动了内容
335
- */
336
- function patchBlock(block, start, end, patch) {
337
- const segs = readSegments(block);
338
- const { before, inside, after } = splitAt(segs, start, end);
339
- if (!inside.length) return false;
340
-
341
- const changed = inside.map((seg) => {
342
- const m = { ...seg.m };
343
- // [设计] 清除格式不碰结构标记:批注锚点/修订标记是内容语义不是样式,跟着“清除格式”被剥掉等于丢内容
344
- if (patch.clear) Object.assign(m, emptyMarks(), { rev: m.rev, cmt: m.cmt });
345
- for (const [key, value] of Object.entries(patch.set || {})) m[key] = Boolean(value);
346
- for (const [key, value] of Object.entries(patch.style || {})) m[key] = value || '';
347
- if (patch.link !== undefined) m.link = patch.link || '';
348
- return { ...seg, m };
349
- });
350
- if (!changed.some((seg, i) => !marksEqual(seg.m, inside[i].m))) return false;
351
-
352
- block.replaceChildren(renderSegments([...before, ...changed, ...after]));
353
- return true;
354
- }
355
-
356
- /** 按内核口径重建块的行内容(粘贴/外部 HTML 里的 <b> <i> <font> 等在此归一) */
357
- export function canonicalizeInline(block) {
358
- if (!block?.isConnected) return;
359
- block.replaceChildren(renderSegments(readSegments(block)));
360
- }
361
-
362
- /** 选区内逐块打补丁 */
363
- function patchSelection(root, ranges, patch) {
364
- let applied = false;
365
- for (const { block, start, end } of ranges) {
366
- if (patchBlock(block, start, end, patch)) applied = true;
367
- }
368
- return applied;
369
- }
370
-
371
- /* ===================== 命令 ===================== */
372
-
373
- /**
374
- * 切换标签类标记(加粗 / 斜体 / 下划线 / 删除线 / 行内代码 / 上下标)
375
- * @param {object} ctx { root, marks: 行内状态快照, pending: 待应用标记集(折叠光标) }
376
- */
377
- export function toggleTagMark(ctx, key) {
378
- const active = Boolean(ctx.marks[key]);
379
- const set = { [key]: !active };
380
- // 上下标互斥(一条 run 的 vertAlign 只有一个值):开一个必须关另一个
381
- if (!active && (key === 'superscript' || key === 'subscript')) {
382
- set[key === 'superscript' ? 'subscript' : 'superscript'] = false;
383
- }
384
- if (ctx.pending) {
385
- Object.assign(ctx.pending, set);
386
- return true;
387
- }
388
- return patchSelection(ctx.root, ctx.ranges, { set });
389
- }
390
-
391
- /** 设置内联样式属性(颜色 / 背景 / 字号 / 字体);value 空表示取消 */
392
- export function setStyleMark(ctx, key, value) {
393
- // 字体名可能来自任意来源(粘贴 / 程序化调用):进标记前统一净化,净化后为空等价取消
394
- const v = key === 'fontFamily' ? sanitizeFontName(value) : value || '';
395
- // 手选颜色即脱离主题引用(显式值与引用二选一,禁并存两个真值源)
396
- const patch = key === 'color' ? { color: v, colorTheme: '', colorThemeTint: '', colorThemeShade: '' } : { [key]: v };
397
- if (ctx.pending) {
398
- Object.assign(ctx.pending, patch);
399
- return true;
400
- }
401
- return patchSelection(ctx.root, ctx.ranges, { style: patch });
402
- }
403
-
404
- /**
405
- * 一次设置多个内联样式属性(如组合色的前景 + 背景)。
406
- * [坑] 拆成多次 setStyleMark 调用会失败:第一次 patch 就重建了块的行 DOM,
407
- * 之前算好的选区 range 随之失效,第二次会落到空选区上。
408
- */
409
- export function setStyleMarks(ctx, values) {
410
- const patch = {};
411
- for (const [key, value] of Object.entries(values || {})) {
412
- patch[key] = key === 'fontFamily' ? sanitizeFontName(value) : value || '';
413
- }
414
- if (patch.color !== undefined) {
415
- patch.colorTheme = '';
416
- patch.colorThemeTint = '';
417
- patch.colorThemeShade = '';
418
- }
419
- if (ctx.pending) {
420
- Object.assign(ctx.pending, patch);
421
- return true;
422
- }
423
- return patchSelection(ctx.root, ctx.ranges, { style: patch });
424
- }
425
-
426
- /** 应用 / 移除链接(href 空等价移除);非白名单协议(javascript: 等)拒绝,调用方据此提示 */
427
- export function setLinkMark(ctx, href) {
428
- const url = String(href || '').trim();
429
- if (url !== '' && !isSafeHref(url)) return false;
430
- if (ctx.pending) {
431
- ctx.pending.link = url;
432
- return true;
433
- }
434
- return patchSelection(ctx.root, ctx.ranges, { link: url || null });
435
- }
436
-
437
- /** 批注范围:给选区打上批注键(key 空等价移除);待定标记口径与样式标记一致 */
438
- export function setCommentMark(ctx, key) {
439
- const value = String(key || '');
440
- if (ctx.pending) {
441
- ctx.pending.cmt = value;
442
- return true;
443
- }
444
- return patchSelection(ctx.root, ctx.ranges, { style: { cmt: value } });
445
- }
446
-
447
- /** 接受 / 拒绝全部修订见 revision.js(resolveRevisions);此处只管标记模型与批注壳 */
448
-
449
- /** 删除批注锚点:剥掉 span.doc-comment 壳保留文字(批注条目由宿主数据侧同步维护) */
450
- export function removeCommentRange(root, key) {
451
- const value = String(key || '');
452
- let count = 0;
453
- for (const el of Array.from(root?.querySelectorAll(`.${DOC_CLASS.COMMENT}`) || [])) {
454
- if (el.getAttribute(COMMENT_ATTR) !== value) continue;
455
- unwrapElement(el);
456
- count += 1;
457
- }
458
- if (count) root.normalize();
459
- return count;
460
- }
461
-
462
- /** 在光标处插入脚注/尾注锚点(sup.doc-footnote[data-fn];Word 应用消费,序号文字由宿主传入) */
463
- export function insertNoteAnchor(root, spec) {
464
- const range = rangeOf(root);
465
- if (!range || !range.collapsed) return false;
466
- const sup = document.createElement('sup');
467
- sup.className = spec?.end ? DOC_CLASS.ENDNOTE : DOC_CLASS.FOOTNOTE;
468
- sup.setAttribute(NOTE_ATTR, String(spec?.id ?? ''));
469
- sup.setAttribute('contenteditable', 'false');
470
- sup.textContent = String(spec?.ord ?? '');
471
- range.insertNode(sup);
472
- return true;
473
- }
474
-
475
- /** 删除指定 id 的脚注/尾注锚点(插入未提交的回滚用) */
476
- export function removeNoteAnchor(root, id) {
477
- const value = String(id ?? '');
478
- let count = 0;
479
- for (const el of Array.from(root?.querySelectorAll(`sup.${DOC_CLASS.FOOTNOTE}, sup.${DOC_CLASS.ENDNOTE}`) || [])) {
480
- if (el.getAttribute(NOTE_ATTR) !== value) continue;
481
- el.remove();
482
- count += 1;
483
- }
484
- return count > 0;
485
- }
486
-
487
- /** 在光标处插入笔记行内锚(折叠光标;attach=附件引用、ref=块/文档引用) */
488
- export function insertAnchorAtCursor(root, kind, spec) {
489
- const range = rangeOf(root);
490
- if (!range || !range.collapsed) return false;
491
- const span = document.createElement('span');
492
- if (kind === 'attach') {
493
- span.className = DOC_CLASS.ATTACH;
494
- span.setAttribute(ATTACH_ATTR, String(spec?.id ?? ''));
495
- span.textContent = String(spec?.name ?? '');
496
- } else {
497
- span.className = DOC_CLASS.REF;
498
- span.setAttribute(REF_DOC_ATTR, String(spec?.docId ?? ''));
499
- if (spec?.blockId) span.setAttribute(REF_BLOCK_ATTR, String(spec.blockId));
500
- span.setAttribute(REF_SUB_ATTR, spec?.sub === 's' ? 's' : 'd');
501
- span.textContent = String(spec?.text ?? '');
502
- }
503
- span.setAttribute('contenteditable', 'false');
504
- range.insertNode(span);
505
- // 光标落到锚点之后(与 insertImageInline 同口径:插完能接着打字)
506
- const after = document.createRange();
507
- after.setStartAfter(span);
508
- after.collapse(true);
509
- const sel = window.getSelection();
510
- sel.removeAllRanges();
511
- sel.addRange(after);
512
- return true;
513
- }
514
-
515
- /** 按属性值删除全部行内锚(附件移除时同删正文引用用;返回是否有删除) */
516
- export function removeAnchorsByAttr(root, attr, value) {
517
- const key = String(attr || '');
518
- const val = String(value ?? '');
519
- if (!key) return false;
520
- let count = 0;
521
- for (const el of Array.from(root?.querySelectorAll(`span[${key}]`) || [])) {
522
- if (el.getAttribute(key) !== val) continue;
523
- el.remove();
524
- count += 1;
525
- }
526
- return count > 0;
527
- }
528
-
529
- /* ===================== 引用节点转换(右键菜单入口) ===================== */
530
-
531
- /** 取 el 所属的顶层块(root 的直接子元素;找不到返回 null) */
532
- function topBlockOf(root, el) {
533
- let node = el;
534
- while (node && node.parentElement && node.parentElement !== root) node = node.parentElement;
535
- return node && node.parentElement === root ? node : null;
536
- }
537
-
538
- /** 行内引用 → 嵌入块(先从正文摘掉引用,再把嵌入块插到所在块之后)。
539
- * [设计] 嵌入是块级节点,不能塞进段落内部(DOM 解析会拆段);转换=卡片外置。渲染产物由宿主传入。 */
540
- export function convertRefToEmbed(root, el, html = '') {
541
- if (!el || !el.hasAttribute(REF_DOC_ATTR) || !el.isConnected) return false;
542
- const docId = el.getAttribute(REF_DOC_ATTR) || '';
543
- const blockId = el.getAttribute(REF_BLOCK_ATTR) || '';
544
- const block = topBlockOf(root, el);
545
- el.remove();
546
- const div = document.createElement('div');
547
- div.className = DOC_CLASS.EMBED;
548
- div.setAttribute(REF_DOC_ATTR, docId);
549
- if (blockId) div.setAttribute(REF_BLOCK_ATTR, blockId);
550
- div.setAttribute('contenteditable', 'false');
551
- if (html) div.innerHTML = html;
552
- if (block) block.after(div);
553
- else root.appendChild(div);
554
- return true;
555
- }
556
-
557
- /** 嵌入块 → 行内引用(整块替换为一个只含引用的段落;锚文本由装载期 d 型刷新补) */
558
- export function convertEmbedToRef(el) {
559
- if (!el || el.tagName !== 'DIV' || !el.hasAttribute(REF_DOC_ATTR) || !el.isConnected) return false;
560
- const p = document.createElement('p');
561
- const span = document.createElement('span');
562
- span.className = DOC_CLASS.REF;
563
- span.setAttribute(REF_DOC_ATTR, el.getAttribute(REF_DOC_ATTR) || '');
564
- const blockId = el.getAttribute(REF_BLOCK_ATTR) || '';
565
- if (blockId) span.setAttribute(REF_BLOCK_ATTR, blockId);
566
- span.setAttribute(REF_SUB_ATTR, 'd');
567
- span.setAttribute('contenteditable', 'false');
568
- p.appendChild(span);
569
- p.appendChild(document.createElement('br'));
570
- el.replaceWith(p);
571
- return true;
572
- }
573
-
574
- /** 切换引用锚文本类型(d=动态跟随目标 / s=静态快照永不回写) */
575
- export function setRefSub(el, sub) {
576
- if (!el || !el.hasAttribute(REF_DOC_ATTR)) return false;
577
- el.setAttribute(REF_SUB_ATTR, sub === 's' ? 's' : 'd');
578
- return true;
579
- }
580
-
581
- /** 删除节点(引用锚 / 嵌入块共用;宿主右键「删除」入口) */
582
- export function removeAnchorNode(el) {
583
- if (!el || !el.isConnected) return false;
584
- el.remove();
585
- return true;
586
- }
587
-
588
- /** 清除选区全部行内格式 */
589
- export function clearInlineMarks(ctx) {
590
- if (!ctx.ranges.length) return false;
591
- return patchSelection(ctx.root, ctx.ranges, { clear: true });
592
- }
593
-
594
- /** 给块内 [start,end) 追加标记(待定标记落到刚输入的文字上) */
595
- export function markBlockSlice(root, block, start, end, marks) {
596
- if (!block?.isConnected) return false;
597
- // 结构标记只增不清:pending 里没设 rev/cmt 时不能把输入处继承来的修订/批注壳抹掉
598
- const structural = {};
599
- if (marks.rev) structural.rev = marks.rev;
600
- if (marks.cmt) structural.cmt = marks.cmt;
601
- return patchBlock(block, start, end, { set: pickTags(marks), style: { ...pickStyles(marks), ...structural }, link: marks.link || undefined });
602
- }
603
-
604
- // [坑] 待定标记必须保留「显式关闭」语义:在加粗文字里关掉加粗再打字,pending.bold === false
605
- // 必须作为 set 下发给刚输入的文字,只挑真值会让新字继续继承原壳的加粗/样式
606
- const pickTags = (marks) => Object.fromEntries(TAG_MARKS.filter((key) => key in marks).map((key) => [key, Boolean(marks[key])]));
607
- const pickStyles = (marks) => Object.fromEntries(TEXT_STYLE_MARKS.filter((key) => key in marks).map((key) => [key, marks[key] || '']));
608
-
609
- /* ===================== 状态查询 ===================== */
610
-
611
- /**
612
- * 选区行内状态:标记取「选区是否全部命中」,样式属性取光标所在首片段
613
- * @returns {{marks:object, pendingEmpty:boolean}}
614
- */
615
- export function inlineState(root, ranges) {
616
- const segs = [];
617
- for (const { block, start, end } of ranges) {
618
- const all = readSegments(block);
619
- let cursor = 0;
620
- if (start === end) {
621
- // [坑] 折叠光标必须落到「左邻字符」的标记上:窗口判据 cursor<end && cursor+size>start 对零宽选区
622
- // 永远落空,结果在加粗文字末尾按 Ctrl+B 会被当成「从没加粗过」,第二次按反而又开加粗(关不掉)
623
- let left = null;
624
- let right = null;
625
- for (const seg of all) {
626
- const size = segLength(seg);
627
- if (size && cursor + size === start) left = seg;
628
- if (size && cursor === start && !right) right = seg;
629
- cursor += size;
630
- }
631
- const pick = left || right;
632
- if (pick) segs.push(pick);
633
- continue;
634
- }
635
- for (const seg of all) {
636
- const size = segLength(seg);
637
- if (cursor < end && cursor + size > start) segs.push(seg);
638
- cursor += size;
639
- }
640
- }
641
- if (!segs.length) return { marks: emptyMarks(), hasText: false };
642
-
643
- const first = segs[0].m;
644
- const marks = { ...emptyMarks() };
645
- for (const key of TAG_MARKS) marks[key] = segs.every((seg) => Boolean(seg.m[key]));
646
- for (const key of TEXT_STYLE_MARKS) marks[key] = first[key] || '';
647
- marks.link = first.link || '';
648
- marks.rev = first.rev || '';
649
- marks.cmt = first.cmt || '';
650
- marks.colorTheme = first.colorTheme || '';
651
- marks.colorThemeTint = first.colorThemeTint || '';
652
- marks.colorThemeShade = first.colorThemeShade || '';
653
- return { marks, hasText: true };
654
- }
655
-
656
- /** 折叠光标处的插入点(待定标记生效的位置) */
1
+ // [文件] web·editor-kernel·engine·inline —— 行内片段模型:读取 / 规范化重建 / 行内命令与状态查询
2
+ // [设计] 行内样式统一走「把块内正文读成片段序列 → 打补丁 → 整块规范化重建」而不是逐节点 split/unwrap:
3
+ // 片段带完整标记签名,重建时相邻同签名片段自动合并,产物永远是规范形态
4
+ // (不会出现 `<strong><strong>`、空 `<span>` 这类越编辑越脏的结构),也不必维护边界拆分那套易错逻辑。
5
+ // [约束] 块级属性(行高 / 对齐 / 缩进)不在本文件:那是挂在块元素内联 style 上的,见 blocks.js。
6
+
7
+ import { ATTACH_ATTR, COMMENT_ATTR, DOC_CLASS, NOTE_ATTR, REF_BLOCK_ATTR, REF_DOC_ATTR, REF_SUB_ATTR, THEME_COLOR_ATTR, THEME_SHADE_ATTR, THEME_TINT_ATTR } from './schema.js';
8
+ import { RUNTIME_CLASSES, rangeOf, unwrapElement } from './dom.js';
9
+ import { normalizeColor } from 'guabiutils';
10
+ import { isSafeHref, sanitizeFontName } from '../../util/safeValue.js';
11
+
12
+ /** 标签 → 标记键(HTML 行内标签别名的唯一数据源:docx 编解码读取侧同引此表,禁各自再拼一份)
13
+ * [设计] 不含 DEL:HTML 的 <del> 在 docx 语境承载修订语义(走 REV_TAGS),删除线归属由 docx 读取侧单独并入 */
14
+ export const TAG_TO_MARK = {
15
+ STRONG: 'bold',
16
+ B: 'bold',
17
+ EM: 'italic',
18
+ I: 'italic',
19
+ U: 'underline',
20
+ S: 'strike',
21
+ STRIKE: 'strike',
22
+ CODE: 'code',
23
+ TT: 'code',
24
+ SUP: 'superscript',
25
+ SUB: 'subscript',
26
+ };
27
+
28
+ /** 修订标记标签 → rev 取值(ins/del 是结构标记,不与下划线/删除线混同——
29
+ * 混同会把 .docx 修订语义在任意一次编辑重建时抹掉) */
30
+ const REV_TAGS = { INS: 'ins', DEL: 'del' };
31
+
32
+ /** 标记键 → 标签(由内向外包裹顺序) */
33
+ const MARK_TO_TAG = { bold: 'strong', italic: 'em', underline: 'u', strike: 's', code: 'code', superscript: 'sup', subscript: 'sub' };
34
+
35
+ /** 内联样式 → 标记键 */
36
+ const STYLE_KEYS = [
37
+ ['color', 'color'],
38
+ ['background-color', 'backgroundColor'],
39
+ ['font-size', 'fontSize'],
40
+ ['font-family', 'fontFamily'],
41
+ ['-webkit-text-stroke', 'textStroke'],
42
+ ['text-shadow', 'textShadow'],
43
+ ];
44
+
45
+ /** 标记键 → 内联样式属性 */
46
+ const MARK_STYLE = { color: 'color', backgroundColor: 'background-color', fontSize: 'font-size', fontFamily: 'font-family', textStroke: '-webkit-text-stroke', textShadow: 'text-shadow' };
47
+
48
+ export const TEXT_STYLE_MARKS = ['color', 'backgroundColor', 'fontSize', 'fontFamily', 'textStroke', 'textShadow'];
49
+
50
+ /** 需要 hex 归一的标记键(其余样式属性原样透传) */
51
+ const COLOR_KEYS = new Set(['color', 'backgroundColor']);
52
+ export const TAG_MARKS = ['bold', 'italic', 'underline', 'strike', 'code', 'superscript', 'subscript'];
53
+
54
+ function emptyMarks() {
55
+ return {
56
+ bold: false,
57
+ italic: false,
58
+ underline: false,
59
+ strike: false,
60
+ code: false,
61
+ superscript: false,
62
+ subscript: false,
63
+ link: '',
64
+ rev: '',
65
+ cmt: '',
66
+ color: '',
67
+ colorTheme: '',
68
+ colorThemeTint: '',
69
+ colorThemeShade: '',
70
+ backgroundColor: '',
71
+ fontSize: '',
72
+ fontFamily: '',
73
+ textStroke: '',
74
+ textShadow: '',
75
+ };
76
+ }
77
+
78
+ function marksEqual(a, b) {
79
+ return TAG_MARKS.every((key) => !!a[key] === !!b[key]) && TEXT_STYLE_MARKS.every((key) => norm(a[key]) === norm(b[key])) && norm(a.link) === norm(b.link) && a.rev === b.rev && a.cmt === b.cmt && a.colorTheme === b.colorTheme && a.colorThemeTint === b.colorThemeTint && a.colorThemeShade === b.colorThemeShade;
80
+ }
81
+
82
+ /** 颜色 / 字号比较忽略大小写与多余空格 */
83
+ function norm(value) {
84
+ return String(value ?? '')
85
+ .trim()
86
+ .toLowerCase();
87
+ }
88
+
89
+ /** 片段字符数:硬换行不占位(与 dom.js 的偏移口径一致),图片算 1 */
90
+ const segLength = (seg) => (seg.text ? seg.text.length : seg.br ? 0 : 1);
91
+
92
+ /* ===================== 读:DOM → 片段 ===================== */
93
+
94
+ function readInto(parent, marks, out) {
95
+ for (const child of Array.from(parent.childNodes)) {
96
+ if (child.nodeType === Node.TEXT_NODE) {
97
+ if (child.data) out.push({ text: child.data, m: { ...marks } });
98
+ continue;
99
+ }
100
+ if (child.nodeType !== Node.ELEMENT_NODE) continue;
101
+ if (child.tagName === 'LABEL') continue; // 待办复选框不是正文
102
+ // 运行期装饰壳(高亮等)只穿透取内容,不进片段
103
+ if (RUNTIME_CLASSES.some((name) => child.classList?.contains(name))) {
104
+ readInto(child, marks, out);
105
+ continue;
106
+ }
107
+ if (child.tagName === 'BR') {
108
+ out.push({ br: true, m: { ...marks } });
109
+ continue;
110
+ }
111
+ if (child.tagName === 'IMG') {
112
+ out.push({
113
+ img: {
114
+ src: child.getAttribute('src') || '',
115
+ alt: child.getAttribute('alt') || '',
116
+ width: child.getAttribute('width') || '',
117
+ height: child.getAttribute('height') || '',
118
+ },
119
+ m: { ...marks },
120
+ });
121
+ continue;
122
+ }
123
+ // 脚注/尾注锚点按原子片段保留(带 data-fn 的 sup 不是普通上标;不做原子化会在整块重建时丢引用)
124
+ if (child.tagName === 'SUP' && (child.classList.contains(DOC_CLASS.FOOTNOTE) || child.classList.contains(DOC_CLASS.ENDNOTE))) {
125
+ out.push({
126
+ note: {
127
+ id: child.getAttribute(NOTE_ATTR) || '',
128
+ end: child.classList.contains(DOC_CLASS.ENDNOTE),
129
+ ord: child.textContent || '',
130
+ },
131
+ m: { ...marks },
132
+ });
133
+ continue;
134
+ }
135
+ // 笔记行内锚按属性识别(粘贴链会剥 class):原子片段建模,整块重建时按此回写
136
+ if (child.hasAttribute(ATTACH_ATTR)) {
137
+ out.push({ attach: { id: child.getAttribute(ATTACH_ATTR) || '', name: child.textContent || '' }, m: { ...marks } });
138
+ continue;
139
+ }
140
+ if (child.hasAttribute(REF_DOC_ATTR)) {
141
+ out.push({
142
+ ref: {
143
+ docId: child.getAttribute(REF_DOC_ATTR) || '',
144
+ blockId: child.getAttribute(REF_BLOCK_ATTR) || '',
145
+ sub: child.getAttribute(REF_SUB_ATTR) || 'd',
146
+ text: child.textContent || '',
147
+ },
148
+ m: { ...marks },
149
+ });
150
+ continue;
151
+ }
152
+ let next = marks;
153
+ const tagMark = TAG_TO_MARK[child.tagName];
154
+ if (tagMark) next = { ...next, [tagMark]: true };
155
+ const rev = REV_TAGS[child.tagName];
156
+ if (rev) next = { ...next, rev };
157
+ if (child.tagName === 'SPAN' && child.classList?.contains(DOC_CLASS.COMMENT)) {
158
+ next = { ...next, cmt: child.getAttribute(COMMENT_ATTR) || '' };
159
+ }
160
+ for (const [prop, key] of STYLE_KEYS) {
161
+ const value = child.style?.getPropertyValue(prop)?.trim();
162
+ if (!value) continue;
163
+ next = { ...next, [key]: COLOR_KEYS.has(key) ? normalizeColor(value) : value };
164
+ }
165
+ if (child.tagName === 'A') next = { ...next, link: child.getAttribute('href') || '' };
166
+ // 主题色引用(读入渲染带出的 data 属性;显式 color 与引用并存时两者都带,写回端按引用优先)
167
+ const themeName = child.getAttribute(THEME_COLOR_ATTR);
168
+ if (themeName) {
169
+ next = {
170
+ ...next,
171
+ colorTheme: themeName,
172
+ colorThemeTint: child.getAttribute(THEME_TINT_ATTR) || '',
173
+ colorThemeShade: child.getAttribute(THEME_SHADE_ATTR) || ''
174
+ };
175
+ }
176
+ readInto(child, next, out);
177
+ }
178
+ }
179
+
180
+ function readSegments(block) {
181
+ const segs = [];
182
+ if (block) readInto(block, emptyMarks(), segs);
183
+ return segs;
184
+ }
185
+
186
+ /* ===================== 写:片段 → DOM ===================== */
187
+
188
+ function leafOf(seg) {
189
+ if (seg.text) return document.createTextNode(seg.text);
190
+ if (seg.br) return document.createElement('br');
191
+ if (seg.note) {
192
+ const sup = document.createElement('sup');
193
+ sup.className = seg.note.end ? DOC_CLASS.ENDNOTE : DOC_CLASS.FOOTNOTE;
194
+ sup.setAttribute(NOTE_ATTR, seg.note.id);
195
+ sup.setAttribute('contenteditable', 'false');
196
+ sup.textContent = seg.note.ord || '';
197
+ return sup;
198
+ }
199
+ if (seg.attach || seg.ref) return anchorLeafOf(seg);
200
+ const img = document.createElement('img');
201
+ if (seg.img.src) img.setAttribute('src', seg.img.src);
202
+ img.setAttribute('alt', seg.img.alt || '');
203
+ for (const key of ['width', 'height']) if (seg.img[key]) img.setAttribute(key, seg.img[key]);
204
+ return img;
205
+ }
206
+
207
+ /** 笔记行内锚叶子(附件引用/块引用):整枚原子,重建时按片段还原(contenteditable=false 与 nodeChars 的 1 字符位口径配套) */
208
+ function anchorLeafOf(seg) {
209
+ const span = document.createElement('span');
210
+ if (seg.attach) {
211
+ span.className = DOC_CLASS.ATTACH;
212
+ span.setAttribute(ATTACH_ATTR, seg.attach.id);
213
+ span.textContent = seg.attach.name || '';
214
+ } else {
215
+ span.className = DOC_CLASS.REF;
216
+ span.setAttribute(REF_DOC_ATTR, seg.ref.docId);
217
+ if (seg.ref.blockId) span.setAttribute(REF_BLOCK_ATTR, seg.ref.blockId);
218
+ span.setAttribute(REF_SUB_ATTR, seg.ref.sub === 's' ? 's' : 'd');
219
+ span.textContent = seg.ref.text || '';
220
+ }
221
+ span.setAttribute('contenteditable', 'false');
222
+ return span;
223
+ }
224
+
225
+ /** 按规范嵌套包壳(strong 最内、a 最外);入参可以是单叶子或整组的 fragment */
226
+ function wrapMarks(marks, node) {
227
+ for (const key of ['code', 'strike', 'underline', 'italic', 'superscript', 'subscript', 'bold']) {
228
+ if (!marks[key]) continue;
229
+ const el = document.createElement(MARK_TO_TAG[key]);
230
+ el.appendChild(node);
231
+ node = el;
232
+ }
233
+ const style = TEXT_STYLE_MARKS.filter((key) => marks[key]).map((key) => `${MARK_STYLE[key]}: ${marks[key]}`);
234
+ if (style.length || marks.colorTheme) {
235
+ const span = document.createElement('span');
236
+ if (style.length) span.setAttribute('style', style.join('; '));
237
+ if (marks.colorTheme) {
238
+ span.setAttribute(THEME_COLOR_ATTR, marks.colorTheme);
239
+ if (marks.colorThemeTint) span.setAttribute(THEME_TINT_ATTR, marks.colorThemeTint);
240
+ if (marks.colorThemeShade) span.setAttribute(THEME_SHADE_ATTR, marks.colorThemeShade);
241
+ }
242
+ span.appendChild(node);
243
+ node = span;
244
+ }
245
+ // 结构标记在样式壳之外、链接之内:批注范围最外(可包住整段修订),修订其次
246
+ if (marks.rev) {
247
+ const rev = document.createElement(marks.rev === 'del' ? 'del' : 'ins');
248
+ rev.className = marks.rev === 'del' ? DOC_CLASS.DEL : DOC_CLASS.INS;
249
+ rev.appendChild(node);
250
+ node = rev;
251
+ }
252
+ if (marks.cmt) {
253
+ const span = document.createElement('span');
254
+ span.className = DOC_CLASS.COMMENT;
255
+ span.setAttribute(COMMENT_ATTR, marks.cmt);
256
+ span.appendChild(node);
257
+ node = span;
258
+ }
259
+ if (marks.link) {
260
+ const a = document.createElement('a');
261
+ a.setAttribute('href', marks.link);
262
+ a.setAttribute('target', '_blank');
263
+ a.setAttribute('rel', 'noopener noreferrer nofollow');
264
+ a.appendChild(node);
265
+ node = a;
266
+ }
267
+ return node;
268
+ }
269
+
270
+ /** 相邻同签名片段合成一组、共用一层壳(拆边界后必须合回来,否则正文里全是 <strong><strong>) */
271
+ function renderSegments(segs) {
272
+ const frag = document.createDocumentFragment();
273
+ let group = [];
274
+ let groupMarks = null;
275
+ const flush = () => {
276
+ if (!group.length) return;
277
+ const inner = document.createDocumentFragment();
278
+ for (const seg of group) inner.appendChild(leafOf(seg));
279
+ frag.appendChild(wrapMarks(groupMarks, inner));
280
+ group = [];
281
+ groupMarks = null;
282
+ };
283
+ for (const seg of segs) {
284
+ if (groupMarks && marksEqual(groupMarks, seg.m)) {
285
+ group.push(seg);
286
+ continue;
287
+ }
288
+ flush();
289
+ group = [seg];
290
+ groupMarks = seg.m;
291
+ }
292
+ flush();
293
+ return frag;
294
+ }
295
+
296
+ /* ===================== 片段切片与打补丁 ===================== */
297
+
298
+ /** 按字符区间 [start,end) 把片段切成 before / inside / after 三段(边界处拆片段) */
299
+ function splitAt(segs, start, end) {
300
+ const before = [];
301
+ const inside = [];
302
+ const after = [];
303
+ let cursor = 0;
304
+ for (const seg of segs) {
305
+ const size = segLength(seg);
306
+ const segStart = cursor;
307
+ const segEnd = cursor + size;
308
+ cursor = segEnd;
309
+ if (segEnd <= start) {
310
+ before.push(seg);
311
+ continue;
312
+ }
313
+ if (segStart >= end) {
314
+ after.push(seg);
315
+ continue;
316
+ }
317
+ if (!seg.text) {
318
+ // 原子片段(图 / 换行)不可切:整枚归属
319
+ (segStart >= start && segEnd <= end ? inside : segStart < start ? before : after).push(seg);
320
+ continue;
321
+ }
322
+ const cutStart = Math.max(0, start - segStart);
323
+ const cutEnd = Math.min(size, end - segStart);
324
+ if (cutStart > 0) before.push({ text: seg.text.slice(0, cutStart), m: { ...seg.m } });
325
+ if (cutEnd > cutStart) inside.push({ text: seg.text.slice(cutStart, cutEnd), m: { ...seg.m } });
326
+ if (cutEnd < size) after.push({ text: seg.text.slice(cutEnd), m: { ...seg.m } });
327
+ }
328
+ return { before, inside, after };
329
+ }
330
+
331
+ /**
332
+ * 对块内 [start,end) 施加行内补丁
333
+ * @param {object} patch { set?:{key:bool}, style?:{color:value|null}, link?:href|null, clear?:true }
334
+ * @returns {boolean} 是否真的改动了内容
335
+ */
336
+ function patchBlock(block, start, end, patch) {
337
+ const segs = readSegments(block);
338
+ const { before, inside, after } = splitAt(segs, start, end);
339
+ if (!inside.length) return false;
340
+
341
+ const changed = inside.map((seg) => {
342
+ const m = { ...seg.m };
343
+ // [设计] 清除格式不碰结构标记:批注锚点/修订标记是内容语义不是样式,跟着“清除格式”被剥掉等于丢内容
344
+ if (patch.clear) Object.assign(m, emptyMarks(), { rev: m.rev, cmt: m.cmt });
345
+ for (const [key, value] of Object.entries(patch.set || {})) m[key] = Boolean(value);
346
+ for (const [key, value] of Object.entries(patch.style || {})) m[key] = value || '';
347
+ if (patch.link !== undefined) m.link = patch.link || '';
348
+ return { ...seg, m };
349
+ });
350
+ if (!changed.some((seg, i) => !marksEqual(seg.m, inside[i].m))) return false;
351
+
352
+ block.replaceChildren(renderSegments([...before, ...changed, ...after]));
353
+ return true;
354
+ }
355
+
356
+ /** 按内核口径重建块的行内容(粘贴/外部 HTML 里的 <b> <i> <font> 等在此归一) */
357
+ export function canonicalizeInline(block) {
358
+ if (!block?.isConnected) return;
359
+ block.replaceChildren(renderSegments(readSegments(block)));
360
+ }
361
+
362
+ /** 选区内逐块打补丁 */
363
+ function patchSelection(root, ranges, patch) {
364
+ let applied = false;
365
+ for (const { block, start, end } of ranges) {
366
+ if (patchBlock(block, start, end, patch)) applied = true;
367
+ }
368
+ return applied;
369
+ }
370
+
371
+ /* ===================== 命令 ===================== */
372
+
373
+ /**
374
+ * 切换标签类标记(加粗 / 斜体 / 下划线 / 删除线 / 行内代码 / 上下标)
375
+ * @param {object} ctx { root, marks: 行内状态快照, pending: 待应用标记集(折叠光标) }
376
+ */
377
+ export function toggleTagMark(ctx, key) {
378
+ const active = Boolean(ctx.marks[key]);
379
+ const set = { [key]: !active };
380
+ // 上下标互斥(一条 run 的 vertAlign 只有一个值):开一个必须关另一个
381
+ if (!active && (key === 'superscript' || key === 'subscript')) {
382
+ set[key === 'superscript' ? 'subscript' : 'superscript'] = false;
383
+ }
384
+ if (ctx.pending) {
385
+ Object.assign(ctx.pending, set);
386
+ return true;
387
+ }
388
+ return patchSelection(ctx.root, ctx.ranges, { set });
389
+ }
390
+
391
+ /** 设置内联样式属性(颜色 / 背景 / 字号 / 字体);value 空表示取消 */
392
+ export function setStyleMark(ctx, key, value) {
393
+ // 字体名可能来自任意来源(粘贴 / 程序化调用):进标记前统一净化,净化后为空等价取消
394
+ const v = key === 'fontFamily' ? sanitizeFontName(value) : value || '';
395
+ // 手选颜色即脱离主题引用(显式值与引用二选一,禁并存两个真值源)
396
+ const patch = key === 'color' ? { color: v, colorTheme: '', colorThemeTint: '', colorThemeShade: '' } : { [key]: v };
397
+ if (ctx.pending) {
398
+ Object.assign(ctx.pending, patch);
399
+ return true;
400
+ }
401
+ return patchSelection(ctx.root, ctx.ranges, { style: patch });
402
+ }
403
+
404
+ /**
405
+ * 一次设置多个内联样式属性(如组合色的前景 + 背景)。
406
+ * [坑] 拆成多次 setStyleMark 调用会失败:第一次 patch 就重建了块的行 DOM,
407
+ * 之前算好的选区 range 随之失效,第二次会落到空选区上。
408
+ */
409
+ export function setStyleMarks(ctx, values) {
410
+ const patch = {};
411
+ for (const [key, value] of Object.entries(values || {})) {
412
+ patch[key] = key === 'fontFamily' ? sanitizeFontName(value) : value || '';
413
+ }
414
+ if (patch.color !== undefined) {
415
+ patch.colorTheme = '';
416
+ patch.colorThemeTint = '';
417
+ patch.colorThemeShade = '';
418
+ }
419
+ if (ctx.pending) {
420
+ Object.assign(ctx.pending, patch);
421
+ return true;
422
+ }
423
+ return patchSelection(ctx.root, ctx.ranges, { style: patch });
424
+ }
425
+
426
+ /** 应用 / 移除链接(href 空等价移除);非白名单协议(javascript: 等)拒绝,调用方据此提示 */
427
+ export function setLinkMark(ctx, href) {
428
+ const url = String(href || '').trim();
429
+ if (url !== '' && !isSafeHref(url)) return false;
430
+ if (ctx.pending) {
431
+ ctx.pending.link = url;
432
+ return true;
433
+ }
434
+ return patchSelection(ctx.root, ctx.ranges, { link: url || null });
435
+ }
436
+
437
+ /** 批注范围:给选区打上批注键(key 空等价移除);待定标记口径与样式标记一致 */
438
+ export function setCommentMark(ctx, key) {
439
+ const value = String(key || '');
440
+ if (ctx.pending) {
441
+ ctx.pending.cmt = value;
442
+ return true;
443
+ }
444
+ return patchSelection(ctx.root, ctx.ranges, { style: { cmt: value } });
445
+ }
446
+
447
+ /** 接受 / 拒绝全部修订见 revision.js(resolveRevisions);此处只管标记模型与批注壳 */
448
+
449
+ /** 删除批注锚点:剥掉 span.doc-comment 壳保留文字(批注条目由宿主数据侧同步维护) */
450
+ export function removeCommentRange(root, key) {
451
+ const value = String(key || '');
452
+ let count = 0;
453
+ for (const el of Array.from(root?.querySelectorAll(`.${DOC_CLASS.COMMENT}`) || [])) {
454
+ if (el.getAttribute(COMMENT_ATTR) !== value) continue;
455
+ unwrapElement(el);
456
+ count += 1;
457
+ }
458
+ if (count) root.normalize();
459
+ return count;
460
+ }
461
+
462
+ /** 在光标处插入脚注/尾注锚点(sup.doc-footnote[data-fn];Word 应用消费,序号文字由宿主传入) */
463
+ export function insertNoteAnchor(root, spec) {
464
+ const range = rangeOf(root);
465
+ if (!range || !range.collapsed) return false;
466
+ const sup = document.createElement('sup');
467
+ sup.className = spec?.end ? DOC_CLASS.ENDNOTE : DOC_CLASS.FOOTNOTE;
468
+ sup.setAttribute(NOTE_ATTR, String(spec?.id ?? ''));
469
+ sup.setAttribute('contenteditable', 'false');
470
+ sup.textContent = String(spec?.ord ?? '');
471
+ range.insertNode(sup);
472
+ return true;
473
+ }
474
+
475
+ /** 删除指定 id 的脚注/尾注锚点(插入未提交的回滚用) */
476
+ export function removeNoteAnchor(root, id) {
477
+ const value = String(id ?? '');
478
+ let count = 0;
479
+ for (const el of Array.from(root?.querySelectorAll(`sup.${DOC_CLASS.FOOTNOTE}, sup.${DOC_CLASS.ENDNOTE}`) || [])) {
480
+ if (el.getAttribute(NOTE_ATTR) !== value) continue;
481
+ el.remove();
482
+ count += 1;
483
+ }
484
+ return count > 0;
485
+ }
486
+
487
+ /** 在光标处插入笔记行内锚(折叠光标;attach=附件引用、ref=块/文档引用) */
488
+ export function insertAnchorAtCursor(root, kind, spec) {
489
+ const range = rangeOf(root);
490
+ if (!range || !range.collapsed) return false;
491
+ const span = document.createElement('span');
492
+ if (kind === 'attach') {
493
+ span.className = DOC_CLASS.ATTACH;
494
+ span.setAttribute(ATTACH_ATTR, String(spec?.id ?? ''));
495
+ span.textContent = String(spec?.name ?? '');
496
+ } else {
497
+ span.className = DOC_CLASS.REF;
498
+ span.setAttribute(REF_DOC_ATTR, String(spec?.docId ?? ''));
499
+ if (spec?.blockId) span.setAttribute(REF_BLOCK_ATTR, String(spec.blockId));
500
+ span.setAttribute(REF_SUB_ATTR, spec?.sub === 's' ? 's' : 'd');
501
+ span.textContent = String(spec?.text ?? '');
502
+ }
503
+ span.setAttribute('contenteditable', 'false');
504
+ range.insertNode(span);
505
+ // 光标落到锚点之后(与 insertImageInline 同口径:插完能接着打字)
506
+ const after = document.createRange();
507
+ after.setStartAfter(span);
508
+ after.collapse(true);
509
+ const sel = window.getSelection();
510
+ sel.removeAllRanges();
511
+ sel.addRange(after);
512
+ return true;
513
+ }
514
+
515
+ /** 按属性值删除全部行内锚(附件移除时同删正文引用用;返回是否有删除) */
516
+ export function removeAnchorsByAttr(root, attr, value) {
517
+ const key = String(attr || '');
518
+ const val = String(value ?? '');
519
+ if (!key) return false;
520
+ let count = 0;
521
+ for (const el of Array.from(root?.querySelectorAll(`span[${key}]`) || [])) {
522
+ if (el.getAttribute(key) !== val) continue;
523
+ el.remove();
524
+ count += 1;
525
+ }
526
+ return count > 0;
527
+ }
528
+
529
+ /* ===================== 引用节点转换(右键菜单入口) ===================== */
530
+
531
+ /** 取 el 所属的顶层块(root 的直接子元素;找不到返回 null) */
532
+ function topBlockOf(root, el) {
533
+ let node = el;
534
+ while (node && node.parentElement && node.parentElement !== root) node = node.parentElement;
535
+ return node && node.parentElement === root ? node : null;
536
+ }
537
+
538
+ /** 行内引用 → 嵌入块(先从正文摘掉引用,再把嵌入块插到所在块之后)。
539
+ * [设计] 嵌入是块级节点,不能塞进段落内部(DOM 解析会拆段);转换=卡片外置。渲染产物由宿主传入。 */
540
+ export function convertRefToEmbed(root, el, html = '') {
541
+ if (!el || !el.hasAttribute(REF_DOC_ATTR) || !el.isConnected) return false;
542
+ const docId = el.getAttribute(REF_DOC_ATTR) || '';
543
+ const blockId = el.getAttribute(REF_BLOCK_ATTR) || '';
544
+ const block = topBlockOf(root, el);
545
+ el.remove();
546
+ const div = document.createElement('div');
547
+ div.className = DOC_CLASS.EMBED;
548
+ div.setAttribute(REF_DOC_ATTR, docId);
549
+ if (blockId) div.setAttribute(REF_BLOCK_ATTR, blockId);
550
+ div.setAttribute('contenteditable', 'false');
551
+ if (html) div.innerHTML = html;
552
+ if (block) block.after(div);
553
+ else root.appendChild(div);
554
+ return true;
555
+ }
556
+
557
+ /** 嵌入块 → 行内引用(整块替换为一个只含引用的段落;锚文本由装载期 d 型刷新补) */
558
+ export function convertEmbedToRef(el) {
559
+ if (!el || el.tagName !== 'DIV' || !el.hasAttribute(REF_DOC_ATTR) || !el.isConnected) return false;
560
+ const p = document.createElement('p');
561
+ const span = document.createElement('span');
562
+ span.className = DOC_CLASS.REF;
563
+ span.setAttribute(REF_DOC_ATTR, el.getAttribute(REF_DOC_ATTR) || '');
564
+ const blockId = el.getAttribute(REF_BLOCK_ATTR) || '';
565
+ if (blockId) span.setAttribute(REF_BLOCK_ATTR, blockId);
566
+ span.setAttribute(REF_SUB_ATTR, 'd');
567
+ span.setAttribute('contenteditable', 'false');
568
+ p.appendChild(span);
569
+ p.appendChild(document.createElement('br'));
570
+ el.replaceWith(p);
571
+ return true;
572
+ }
573
+
574
+ /** 切换引用锚文本类型(d=动态跟随目标 / s=静态快照永不回写) */
575
+ export function setRefSub(el, sub) {
576
+ if (!el || !el.hasAttribute(REF_DOC_ATTR)) return false;
577
+ el.setAttribute(REF_SUB_ATTR, sub === 's' ? 's' : 'd');
578
+ return true;
579
+ }
580
+
581
+ /** 删除节点(引用锚 / 嵌入块共用;宿主右键「删除」入口) */
582
+ export function removeAnchorNode(el) {
583
+ if (!el || !el.isConnected) return false;
584
+ el.remove();
585
+ return true;
586
+ }
587
+
588
+ /** 清除选区全部行内格式 */
589
+ export function clearInlineMarks(ctx) {
590
+ if (!ctx.ranges.length) return false;
591
+ return patchSelection(ctx.root, ctx.ranges, { clear: true });
592
+ }
593
+
594
+ /** 给块内 [start,end) 追加标记(待定标记落到刚输入的文字上) */
595
+ export function markBlockSlice(root, block, start, end, marks) {
596
+ if (!block?.isConnected) return false;
597
+ // 结构标记只增不清:pending 里没设 rev/cmt 时不能把输入处继承来的修订/批注壳抹掉
598
+ const structural = {};
599
+ if (marks.rev) structural.rev = marks.rev;
600
+ if (marks.cmt) structural.cmt = marks.cmt;
601
+ return patchBlock(block, start, end, { set: pickTags(marks), style: { ...pickStyles(marks), ...structural }, link: marks.link || undefined });
602
+ }
603
+
604
+ // [坑] 待定标记必须保留「显式关闭」语义:在加粗文字里关掉加粗再打字,pending.bold === false
605
+ // 必须作为 set 下发给刚输入的文字,只挑真值会让新字继续继承原壳的加粗/样式
606
+ const pickTags = (marks) => Object.fromEntries(TAG_MARKS.filter((key) => key in marks).map((key) => [key, Boolean(marks[key])]));
607
+ const pickStyles = (marks) => Object.fromEntries(TEXT_STYLE_MARKS.filter((key) => key in marks).map((key) => [key, marks[key] || '']));
608
+
609
+ /* ===================== 状态查询 ===================== */
610
+
611
+ /**
612
+ * 选区行内状态:标记取「选区是否全部命中」,样式属性取光标所在首片段
613
+ * @returns {{marks:object, pendingEmpty:boolean}}
614
+ */
615
+ export function inlineState(root, ranges) {
616
+ const segs = [];
617
+ for (const { block, start, end } of ranges) {
618
+ const all = readSegments(block);
619
+ let cursor = 0;
620
+ if (start === end) {
621
+ // [坑] 折叠光标必须落到「左邻字符」的标记上:窗口判据 cursor<end && cursor+size>start 对零宽选区
622
+ // 永远落空,结果在加粗文字末尾按 Ctrl+B 会被当成「从没加粗过」,第二次按反而又开加粗(关不掉)
623
+ let left = null;
624
+ let right = null;
625
+ for (const seg of all) {
626
+ const size = segLength(seg);
627
+ if (size && cursor + size === start) left = seg;
628
+ if (size && cursor === start && !right) right = seg;
629
+ cursor += size;
630
+ }
631
+ const pick = left || right;
632
+ if (pick) segs.push(pick);
633
+ continue;
634
+ }
635
+ for (const seg of all) {
636
+ const size = segLength(seg);
637
+ if (cursor < end && cursor + size > start) segs.push(seg);
638
+ cursor += size;
639
+ }
640
+ }
641
+ if (!segs.length) return { marks: emptyMarks(), hasText: false };
642
+
643
+ const first = segs[0].m;
644
+ const marks = { ...emptyMarks() };
645
+ for (const key of TAG_MARKS) marks[key] = segs.every((seg) => Boolean(seg.m[key]));
646
+ for (const key of TEXT_STYLE_MARKS) marks[key] = first[key] || '';
647
+ marks.link = first.link || '';
648
+ marks.rev = first.rev || '';
649
+ marks.cmt = first.cmt || '';
650
+ marks.colorTheme = first.colorTheme || '';
651
+ marks.colorThemeTint = first.colorThemeTint || '';
652
+ marks.colorThemeShade = first.colorThemeShade || '';
653
+ return { marks, hasText: true };
654
+ }
655
+
656
+ /** 折叠光标处的插入点(待定标记生效的位置) */