@a200888213/gbdocx 0.6.1 → 0.6.3

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 -21
  2. package/README.md +215 -215
  3. package/index.html +31 -30
  4. package/package.json +49 -48
  5. package/serve.mjs +27 -23
  6. package/src/app/file-io.js +122 -122
  7. package/src/app/main.js +9 -9
  8. package/src/app/word/catalog.js +52 -52
  9. package/src/app/word/comments.js +112 -112
  10. package/src/app/word/doc.js +113 -113
  11. package/src/app/word/edit.js +72 -72
  12. package/src/app/word/file.js +191 -191
  13. package/src/app/word/hf.js +76 -76
  14. package/src/app/word/layout.js +155 -155
  15. package/src/app/word/menus.js +201 -201
  16. package/src/app/word/notes.js +110 -110
  17. package/src/app/word/shared.js +22 -22
  18. package/src/app/word/view.js +159 -159
  19. package/src/app/word-app.js +487 -487
  20. package/src/app/word-sheets.js +101 -101
  21. package/src/kernel/docx/catalog.js +41 -41
  22. package/src/kernel/docx/codec/blocks.js +123 -123
  23. package/src/kernel/docx/codec/carry.js +129 -129
  24. package/src/kernel/docx/codec/comments.js +25 -25
  25. package/src/kernel/docx/codec/docx.js +198 -198
  26. package/src/kernel/docx/codec/docxStyles.js +177 -177
  27. package/src/kernel/docx/codec/fonts.js +195 -195
  28. package/src/kernel/docx/codec/helpers.js +161 -161
  29. package/src/kernel/docx/codec/hfHtml.js +152 -152
  30. package/src/kernel/docx/codec/html.js +739 -739
  31. package/src/kernel/docx/codec/losses.js +420 -420
  32. package/src/kernel/docx/codec/markdown.js +170 -170
  33. package/src/kernel/docx/codec/parts.js +249 -249
  34. package/src/kernel/docx/codec/read.js +603 -603
  35. package/src/kernel/docx/codec/render.js +1156 -1156
  36. package/src/kernel/docx/codec/roundtrip.js +236 -236
  37. package/src/kernel/docx/codec/write.js +833 -833
  38. package/src/kernel/docx/comments.js +14 -14
  39. package/src/kernel/docx/menus.js +348 -348
  40. package/src/kernel/docx/pageGeometry.js +123 -123
  41. package/src/kernel/docx/pagination.js +481 -481
  42. package/src/kernel/docx/watermark.js +45 -45
  43. package/src/kernel/docx/wordShortcuts.js +37 -37
  44. package/src/kernel/editor/constants.js +8 -8
  45. package/src/kernel/editor/engine/blocks.js +594 -594
  46. package/src/kernel/editor/engine/blocksEnter.js +109 -109
  47. package/src/kernel/editor/engine/blocksInsert.js +254 -254
  48. package/src/kernel/editor/engine/blocksStructure.js +226 -226
  49. package/src/kernel/editor/engine/commands.js +181 -181
  50. package/src/kernel/editor/engine/dom.js +646 -646
  51. package/src/kernel/editor/engine/editor.js +213 -213
  52. package/src/kernel/editor/engine/history.js +149 -149
  53. package/src/kernel/editor/engine/inline.js +656 -656
  54. package/src/kernel/editor/engine/input.js +554 -554
  55. package/src/kernel/editor/engine/interaction.js +137 -137
  56. package/src/kernel/editor/engine/pointer.js +39 -39
  57. package/src/kernel/editor/engine/revision.js +138 -138
  58. package/src/kernel/editor/engine/schema.js +417 -417
  59. package/src/kernel/editor/engine/search.js +113 -113
  60. package/src/kernel/editor/engine/selection.js +119 -119
  61. package/src/kernel/editor/engine/state.js +118 -118
  62. package/src/kernel/editor/engine/tableClip.js +154 -154
  63. package/src/kernel/editor/engine/tableGrid.js +55 -55
  64. package/src/kernel/editor/engine/tableInteraction.js +388 -388
  65. package/src/kernel/editor/engine/tableMenu.js +250 -250
  66. package/src/kernel/editor/engine/tableOps.js +174 -174
  67. package/src/kernel/editor/engine/tables.js +732 -732
  68. package/src/kernel/editor/overlayGeometry.js +20 -20
  69. package/src/kernel/editor/pasteClean.js +293 -293
  70. package/src/kernel/editor/utils.js +48 -48
  71. package/src/kernel/keyboard.js +114 -114
  72. package/src/kernel/notify.js +54 -54
  73. package/src/kernel/textStyles.js +84 -84
  74. package/src/kernel/util/clipboard.js +89 -89
  75. package/src/kernel/util/imageFile.js +91 -91
  76. package/src/kernel/util/safeValue.js +25 -25
  77. package/src/kernel/util/shortcutKey.js +33 -33
  78. package/src/surface/editor-surface.js +603 -600
  79. package/src/ui/color-panel.js +69 -69
  80. package/src/ui/context-menu.js +135 -133
  81. package/src/ui/dialogs.js +249 -249
  82. package/src/ui/find-bar.js +151 -151
  83. package/src/ui/icons.js +245 -137
  84. package/src/ui/menubar.js +28 -28
  85. package/src/ui/panels.js +115 -115
  86. package/src/ui/popup.js +79 -79
  87. package/src/ui/prompt.js +89 -89
  88. package/src/ui/ribbon.js +485 -485
  89. package/src/ui/special-chars.js +39 -39
  90. package/src/ui/statusbar.js +81 -81
  91. package/src/ui/toolbar.js +32 -32
  92. package/styles/app.css +970 -970
  93. package/styles/editor-content.css +440 -440
  94. package/styles/tokens.css +154 -154
  95. package/styles/word-panel.css +410 -410
@@ -1,20 +1,20 @@
1
- // [文件] web·editor-kernel·overlayGeometry —— 编辑面浮件坐标基准:把 getBoundingClientRect 的视觉坐标折算回滚动容器的局部坐标
2
- // [通用:工具] overlayOrigin —— 浮件坐标基准(视觉 → 局部,缩放感知)【强制通道】
3
- // [坑] 屏幕缩放(Word 应用挂在 .word-editor 的 CSS zoom 上)会让「视觉差值」≠「局部 left/top」:
4
- // 局部 px × 缩放 = 视觉 px,直接把视觉差值当 left/top 用,非 100% 缩放时浮件会整体偏移。
5
- // 故基准点与缩放系数都从一枚探针现量——探针挂在滚动容器 padding box 原点、局部宽恒 PROBE_WIDTH,
6
- // 它随内容滚动,故原点、滚动量、缩放三件事一次量全(不必碰 scrollLeft / clientLeft 的缩放口径)。
7
-
8
- /** 探针的局部宽度(px):量到的视觉宽度 ÷ 此值 = 所在子树的缩放系数 */
9
- export const PROBE_WIDTH = 100;
10
-
11
- /**
12
- * 浮件坐标基准
13
- * @param {HTMLElement|null} probe 探针元素(挂在滚动容器 padding box 原点、局部宽 = PROBE_WIDTH)
14
- * @returns {{x:number, y:number, z:number}} x/y = 局部 (0,0) 的视觉坐标;z = 缩放系数
15
- */
16
- export function overlayOrigin(probe) {
17
- const rect = probe?.getBoundingClientRect?.();
18
- if (!rect) return { x: 0, y: 0, z: 1 };
19
- return { x: rect.left, y: rect.top, z: rect.width > 0 ? rect.width / PROBE_WIDTH : 1 };
20
- }
1
+ // [文件] web·editor-kernel·overlayGeometry —— 编辑面浮件坐标基准:把 getBoundingClientRect 的视觉坐标折算回滚动容器的局部坐标
2
+ // [通用:工具] overlayOrigin —— 浮件坐标基准(视觉 → 局部,缩放感知)【强制通道】
3
+ // [坑] 屏幕缩放(Word 应用挂在 .word-editor 的 CSS zoom 上)会让「视觉差值」≠「局部 left/top」:
4
+ // 局部 px × 缩放 = 视觉 px,直接把视觉差值当 left/top 用,非 100% 缩放时浮件会整体偏移。
5
+ // 故基准点与缩放系数都从一枚探针现量——探针挂在滚动容器 padding box 原点、局部宽恒 PROBE_WIDTH,
6
+ // 它随内容滚动,故原点、滚动量、缩放三件事一次量全(不必碰 scrollLeft / clientLeft 的缩放口径)。
7
+
8
+ /** 探针的局部宽度(px):量到的视觉宽度 ÷ 此值 = 所在子树的缩放系数 */
9
+ export const PROBE_WIDTH = 100;
10
+
11
+ /**
12
+ * 浮件坐标基准
13
+ * @param {HTMLElement|null} probe 探针元素(挂在滚动容器 padding box 原点、局部宽 = PROBE_WIDTH)
14
+ * @returns {{x:number, y:number, z:number}} x/y = 局部 (0,0) 的视觉坐标;z = 缩放系数
15
+ */
16
+ export function overlayOrigin(probe) {
17
+ const rect = probe?.getBoundingClientRect?.();
18
+ if (!rect) return { x: 0, y: 0, z: 1 };
19
+ return { x: rect.left, y: rect.top, z: rect.width > 0 ? rect.width / PROBE_WIDTH : 1 };
20
+ }
@@ -1,293 +1,293 @@
1
- // [文件] web·editor-kernel·pasteClean —— 粘贴内容清洗
2
- // [设计] 分两档处理,不做一刀切:
3
- // · Office(Word/Outlook)粘贴:stripping 最凶——要去掉 mso-* 与命名空间标签,把 pt 字号归一成
4
- // 预设档位(否则工具栏字号下拉回显不出来),行高同理;丢弃 font-family(Word 会带一堆本机字体)。
5
- // · 其它来源(内部复制、网页):保留字号字体原样,保证编辑器内复制粘贴不失真,只清掉结构性垃圾。
6
- // 判断依据是 Office 特征串:Word 的 HTML 必然含 <o:p> / mso- 样式 / microsoft-com 命名空间。
7
-
8
- import { LINE_HEIGHTS } from './constants.js';
9
- import { moveChildren } from './engine/dom.js';
10
- import { SAFE_IMG } from '../util/safeValue.js';
11
- import { FONT_SIZES } from '../textStyles.js';
12
-
13
- /** 结构性垃圾标签:样式块、脚本、外链声明、可执行/可嵌入内容,以及 Word 的命名空间标签(o:p、w:*、v:*) */
14
- const DROP_TAGS = new Set([
15
- 'style', 'script', 'meta', 'link', 'title', 'base', 'xml',
16
- 'iframe', 'object', 'embed', 'form', 'button', 'select', 'textarea',
17
- 'svg', 'math'
18
- ]);
19
-
20
- /** 允许保留的内联样式;其余(margin/padding/border/background-image/mso-*…)一律丢弃 */
21
- const KEEP_PROPS = new Set([
22
- 'text-align',
23
- 'font-weight',
24
- 'font-style',
25
- 'text-decoration',
26
- 'color',
27
- 'background-color',
28
- 'font-size',
29
- 'font-family',
30
- 'line-height',
31
- 'width',
32
- 'min-width',
33
- ]);
34
-
35
- /** Office 粘贴特征 */
36
- const OFFICE_SIGNATURE = /<o:p|mso-|urn:schemas-microsoft-com|<!--\[if/i;
37
-
38
- const SAFE_LINE_HEIGHT_MIN = 1;
39
- const SAFE_LINE_HEIGHT_MAX = 4;
40
-
41
- /** pt / px → 归档到预设字号;无法安全换算或超出范围的返回 ''(丢弃该声明) */
42
- function snapFontSize(value) {
43
- const matched = String(value)
44
- .trim()
45
- .match(/^([\d.]+)\s*(pt|px)$/i);
46
- if (!matched) return '';
47
- const num = Number(matched[1]);
48
- if (!Number.isFinite(num)) return '';
49
- const px = Math.round(matched[2].toLowerCase() === 'pt' ? num * (4 / 3) : num);
50
- if (px < FONT_SIZES[0] || px > FONT_SIZES[FONT_SIZES.length - 1]) return '';
51
- return `${FONT_SIZES.reduce((best, size) => (Math.abs(size - px) < Math.abs(best - px) ? size : best), FONT_SIZES[0])}px`;
52
- }
53
-
54
- /**
55
- * 行高 → 归档到预设档位
56
- * [坑] 必须设下限:Word 里 30% 这种行高换算成倍数就是 0.3,落到预设档会变成 0.25,
57
- * 直接导致文字互相压叠(这正是踩过的那个坑)。低于 1 倍一律丢弃。
58
- */
59
- function snapLineHeight(value) {
60
- const raw = String(value).trim();
61
- let ratio = null;
62
- const percent = raw.match(/^([\d.]+)%$/);
63
- if (percent) ratio = Number(percent[1]) / 100;
64
- else {
65
- const plain = raw.match(/^([\d.]+)$/);
66
- if (plain) ratio = Number(plain[1]);
67
- }
68
- if (!ratio || !Number.isFinite(ratio)) return '';
69
- if (ratio < SAFE_LINE_HEIGHT_MIN || ratio > SAFE_LINE_HEIGHT_MAX) return '';
70
- return LINE_HEIGHTS.reduce(
71
- (best, item) => (Math.abs(Number(item) - ratio) < Math.abs(Number(best) - ratio) ? item : best),
72
- LINE_HEIGHTS[0]
73
- );
74
- }
75
-
76
- /** 逐条过滤内联样式 */
77
- function cleanStyleValue(rawStyle, aggressive) {
78
- const kept = [];
79
- String(rawStyle)
80
- .split(';')
81
- .forEach((declaration) => {
82
- const colon = declaration.indexOf(':');
83
- if (colon < 0) return;
84
- const prop = declaration.slice(0, colon).trim().toLowerCase();
85
- let value = declaration.slice(colon + 1).trim();
86
- if (!prop || !value || !KEEP_PROPS.has(prop)) return;
87
-
88
- if (aggressive) {
89
- if (prop === 'font-family') return; // Word 会带入本机字体名,落到文档里只会造成字体混乱
90
- if (prop === 'font-size') value = snapFontSize(value);
91
- if (prop === 'line-height') value = snapLineHeight(value);
92
- if (!value) return;
93
- }
94
-
95
- kept.push(`${prop}: ${value}`);
96
- });
97
- return kept.join('; ');
98
- }
99
-
100
- /** 去掉所有注释节点(Word 的条件注释) */
101
- function stripComments(root) {
102
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
103
- const nodes = [];
104
- while (walker.nextNode()) nodes.push(walker.currentNode);
105
- nodes.forEach((node) => node.remove());
106
- }
107
-
108
- /** 长度声明 → 归一权重(pt / px → px;百分比单独标记);无法解析或非正数返回 null */
109
- function lengthOf(value) {
110
- const matched = String(value || '')
111
- .trim()
112
- .match(/^([\d.]+)\s*(pt|px|%)?$/i);
113
- if (!matched) return null;
114
- const num = Number(matched[1]);
115
- if (!Number.isFinite(num) || num <= 0) return null;
116
- const unit = (matched[2] || 'px').toLowerCase();
117
- if (unit === '%') return { percent: num };
118
- return { px: unit === 'pt' ? num * (4 / 3) : num };
119
- }
120
-
121
- /** 读元素的内联 width 声明(cleanStyleValue 已把样式压成 `prop: value` 序列) */
122
- function declaredWidthOf(el) {
123
- for (const declaration of String(el.getAttribute('style') || '').split(';')) {
124
- const colon = declaration.indexOf(':');
125
- if (colon < 0) continue;
126
- if (declaration.slice(0, colon).trim().toLowerCase() === 'width') return declaration.slice(colon + 1).trim();
127
- }
128
- return '';
129
- }
130
-
131
- /** 元素声明的列宽:优先内联样式,其次 HTML width 属性 */
132
- const widthOf = (el) => lengthOf(declaredWidthOf(el) || el.getAttribute('width') || '');
133
-
134
- /** 剥掉结构元素上的定宽声明:表格外框统一交给 CSS 的 width: 100% */
135
- function stripFixedWidth(el) {
136
- el.removeAttribute('width');
137
- const style = el.getAttribute('style');
138
- if (!style) return;
139
- const kept = [];
140
- for (const declaration of style.split(';')) {
141
- const colon = declaration.indexOf(':');
142
- if (colon < 0) continue;
143
- const prop = declaration.slice(0, colon).trim().toLowerCase();
144
- if (prop === 'width' || prop === 'min-width') continue;
145
- kept.push(declaration.trim());
146
- }
147
- if (kept.length) el.setAttribute('style', kept.join('; '));
148
- else el.removeAttribute('style');
149
- }
150
-
151
- /** 各列宽度 → 归一到合计 100% 的百分比;信息不足返回 null(退化为固定布局等分) */
152
- function percentWidths(widths, tableWidth) {
153
- if (!widths.length || widths.some((item) => !item)) return null;
154
- if (widths.every((item) => item.percent != null)) {
155
- const total = widths.reduce((sum, item) => sum + item.percent, 0);
156
- return total > 0 ? widths.map((item) => (item.percent / total) * 100) : null;
157
- }
158
- const resolved = widths.map((item) => item.px ?? (tableWidth?.px ? (item.percent / 100) * tableWidth.px : null));
159
- if (resolved.some((item) => !item)) return null;
160
- const total = resolved.reduce((sum, item) => sum + item, 0);
161
- return total > 0 ? resolved.map((item) => (item / total) * 100) : null;
162
- }
163
-
164
- /**
165
- * 粘贴表格的宽度收口:Word / 网页表格会把绝对宽度写进 table、colgroup、col、td,
166
- * 直接落进正文会覆盖 `table { width: 100% }` 并撑出纸张(用户看到的「跑到页面外侧」)。
167
- * 这里把列宽换算成 colgroup 百分比、剥掉所有绝对定宽,让表格始终贴合版心;
168
- * 列宽信息缺失时退化成固定布局等分,也不让像素宽度残留。
169
- */
170
- function normalizePastedTable(table) {
171
- const colgroups = Array.from(table.children).filter((el) => el.tagName === 'COLGROUP');
172
- const cols = colgroups.flatMap((group) => Array.from(group.children).filter((el) => el.tagName === 'COL'));
173
- // 找一行没有跨列的格子做列宽来源:标题行整行合并的表格也能从正文行拿到比例
174
- const plainRow = Array.from(table.rows || []).find((row) => Array.from(row.cells).every((cell) => cell.colSpan === 1));
175
- const cells = plainRow ? Array.from(plainRow.cells) : [];
176
- const gridCount = cells.length || cols.length;
177
- const tableWidth = widthOf(table);
178
-
179
- let widths = cols.map(widthOf);
180
- if (cells.length && (cols.length !== cells.length || !widths.some(Boolean))) {
181
- widths = cells.map(widthOf);
182
- } else if (cells.length === cols.length) {
183
- const cellWidths = cells.map(widthOf);
184
- widths = widths.map((item, i) => item || cellWidths[i]);
185
- }
186
-
187
- // 先剥宽再回写,顺序反了会把刚换算好的百分比一起剥掉
188
- stripFixedWidth(table);
189
- cols.forEach(stripFixedWidth);
190
- for (const row of Array.from(table.rows || [])) {
191
- stripFixedWidth(row);
192
- for (const cell of Array.from(row.cells)) stripFixedWidth(cell);
193
- }
194
- for (const child of Array.from(table.children)) {
195
- if (!/^(THEAD|TBODY|TFOOT|COLGROUP)$/.test(child.tagName)) continue;
196
- stripFixedWidth(child);
197
- for (const row of Array.from(child.children)) if (row.tagName === 'TR') stripFixedWidth(row);
198
- }
199
-
200
- const percents = gridCount && widths.length === gridCount ? percentWidths(widths, tableWidth) : null;
201
- if (!percents) return;
202
-
203
- if (cols.length === percents.length) {
204
- cols.forEach((col, i) => {
205
- col.setAttribute('style', `width: ${Math.round(percents[i] * 10) / 10}%`);
206
- });
207
- return;
208
- }
209
- colgroups.forEach((group) => group.remove());
210
- const colgroup = document.createElement('colgroup');
211
- percents.forEach((percent) => {
212
- const col = document.createElement('col');
213
- col.setAttribute('style', `width: ${Math.round(percent * 10) / 10}%`);
214
- colgroup.appendChild(col);
215
- });
216
- table.prepend(colgroup);
217
- }
218
-
219
- /** 从 style 串里抽取 vertical-align 的上下标值(Word / 网页粘贴的上下标就是它,不是 sup/sub 标签) */
220
- const verticalAlignOf = (style) => {
221
- for (const decl of String(style).split(';')) {
222
- const colon = decl.indexOf(':');
223
- if (colon < 0) continue;
224
- if (decl.slice(0, colon).trim().toLowerCase() !== 'vertical-align') continue;
225
- const v = decl.slice(colon + 1).trim().toLowerCase();
226
- if (v === 'super') return 'super';
227
- if (v === 'sub' || v === 'subscript') return 'sub';
228
- }
229
- return '';
230
- };
231
-
232
- /**
233
- * 清洗粘贴进来的 HTML
234
- * @param {string} html 剪贴板中的 text/html
235
- * @returns {string} 清洗后的 HTML(交由内核装载)
236
- */
237
- export function cleanPastedHtml(html) {
238
- if (!html || typeof html !== 'string') return html;
239
- // 无 DOMParser 的环境(服务端渲染 / 单测)原样返回,交给装载侧兜底
240
- if (typeof DOMParser === 'undefined') return html;
241
-
242
- const aggressive = OFFICE_SIGNATURE.test(html);
243
- const parsed = new DOMParser().parseFromString(html, 'text/html');
244
- const body = parsed.body;
245
-
246
- // 静态 NodeList,可安全地边遍历边移除
247
- body.querySelectorAll('*').forEach((el) => {
248
- const tag = el.tagName.toLowerCase();
249
- if (DROP_TAGS.has(tag) || tag.includes(':')) {
250
- el.remove();
251
- return;
252
- }
253
-
254
- el.removeAttribute('class');
255
- el.removeAttribute('id');
256
- el.removeAttribute('dir');
257
- el.removeAttribute('lang');
258
- el.removeAttribute('align');
259
- // 事件属性是脚本入口:粘贴内容一律不允许携带(onclick/onerror/onload…)
260
- for (const attr of Array.from(el.attributes)) {
261
- if (attr.name.toLowerCase().startsWith('on')) el.removeAttribute(attr.name);
262
- }
263
-
264
- if (el.hasAttribute('style')) {
265
- const rawStyle = el.getAttribute('style');
266
- const va = verticalAlignOf(rawStyle);
267
- const cleaned = cleanStyleValue(rawStyle, aggressive);
268
- if (cleaned) el.setAttribute('style', cleaned);
269
- else el.removeAttribute('style');
270
- // 上下标换壳:内核与 docx 写出都只认 sup/sub 标签,vertical-align 声明会在一次编辑重建时被拉平
271
- if (va && tag === 'span') {
272
- const box = document.createElement(va === 'super' ? 'sup' : 'sub');
273
- if (el.hasAttribute('style')) {
274
- el.replaceWith(box);
275
- box.appendChild(el);
276
- } else {
277
- moveChildren(el, box);
278
- el.replaceWith(box);
279
- }
280
- }
281
- }
282
-
283
- // 指向本地文件 / 剪贴板协议的图片粘进来只会是坏图,直接丢掉而不是留个红色占位
284
- if (tag === 'img') {
285
- const src = el.getAttribute('src') || '';
286
- if (!src || !SAFE_IMG.test(src)) el.remove();
287
- }
288
- });
289
-
290
- stripComments(body);
291
- body.querySelectorAll('table').forEach(normalizePastedTable);
292
- return body.innerHTML;
293
- }
1
+ // [文件] web·editor-kernel·pasteClean —— 粘贴内容清洗
2
+ // [设计] 分两档处理,不做一刀切:
3
+ // · Office(Word/Outlook)粘贴:stripping 最凶——要去掉 mso-* 与命名空间标签,把 pt 字号归一成
4
+ // 预设档位(否则工具栏字号下拉回显不出来),行高同理;丢弃 font-family(Word 会带一堆本机字体)。
5
+ // · 其它来源(内部复制、网页):保留字号字体原样,保证编辑器内复制粘贴不失真,只清掉结构性垃圾。
6
+ // 判断依据是 Office 特征串:Word 的 HTML 必然含 <o:p> / mso- 样式 / microsoft-com 命名空间。
7
+
8
+ import { LINE_HEIGHTS } from './constants.js';
9
+ import { moveChildren } from './engine/dom.js';
10
+ import { SAFE_IMG } from '../util/safeValue.js';
11
+ import { FONT_SIZES } from '../textStyles.js';
12
+
13
+ /** 结构性垃圾标签:样式块、脚本、外链声明、可执行/可嵌入内容,以及 Word 的命名空间标签(o:p、w:*、v:*) */
14
+ const DROP_TAGS = new Set([
15
+ 'style', 'script', 'meta', 'link', 'title', 'base', 'xml',
16
+ 'iframe', 'object', 'embed', 'form', 'button', 'select', 'textarea',
17
+ 'svg', 'math'
18
+ ]);
19
+
20
+ /** 允许保留的内联样式;其余(margin/padding/border/background-image/mso-*…)一律丢弃 */
21
+ const KEEP_PROPS = new Set([
22
+ 'text-align',
23
+ 'font-weight',
24
+ 'font-style',
25
+ 'text-decoration',
26
+ 'color',
27
+ 'background-color',
28
+ 'font-size',
29
+ 'font-family',
30
+ 'line-height',
31
+ 'width',
32
+ 'min-width',
33
+ ]);
34
+
35
+ /** Office 粘贴特征 */
36
+ const OFFICE_SIGNATURE = /<o:p|mso-|urn:schemas-microsoft-com|<!--\[if/i;
37
+
38
+ const SAFE_LINE_HEIGHT_MIN = 1;
39
+ const SAFE_LINE_HEIGHT_MAX = 4;
40
+
41
+ /** pt / px → 归档到预设字号;无法安全换算或超出范围的返回 ''(丢弃该声明) */
42
+ function snapFontSize(value) {
43
+ const matched = String(value)
44
+ .trim()
45
+ .match(/^([\d.]+)\s*(pt|px)$/i);
46
+ if (!matched) return '';
47
+ const num = Number(matched[1]);
48
+ if (!Number.isFinite(num)) return '';
49
+ const px = Math.round(matched[2].toLowerCase() === 'pt' ? num * (4 / 3) : num);
50
+ if (px < FONT_SIZES[0] || px > FONT_SIZES[FONT_SIZES.length - 1]) return '';
51
+ return `${FONT_SIZES.reduce((best, size) => (Math.abs(size - px) < Math.abs(best - px) ? size : best), FONT_SIZES[0])}px`;
52
+ }
53
+
54
+ /**
55
+ * 行高 → 归档到预设档位
56
+ * [坑] 必须设下限:Word 里 30% 这种行高换算成倍数就是 0.3,落到预设档会变成 0.25,
57
+ * 直接导致文字互相压叠(这正是踩过的那个坑)。低于 1 倍一律丢弃。
58
+ */
59
+ function snapLineHeight(value) {
60
+ const raw = String(value).trim();
61
+ let ratio = null;
62
+ const percent = raw.match(/^([\d.]+)%$/);
63
+ if (percent) ratio = Number(percent[1]) / 100;
64
+ else {
65
+ const plain = raw.match(/^([\d.]+)$/);
66
+ if (plain) ratio = Number(plain[1]);
67
+ }
68
+ if (!ratio || !Number.isFinite(ratio)) return '';
69
+ if (ratio < SAFE_LINE_HEIGHT_MIN || ratio > SAFE_LINE_HEIGHT_MAX) return '';
70
+ return LINE_HEIGHTS.reduce(
71
+ (best, item) => (Math.abs(Number(item) - ratio) < Math.abs(Number(best) - ratio) ? item : best),
72
+ LINE_HEIGHTS[0]
73
+ );
74
+ }
75
+
76
+ /** 逐条过滤内联样式 */
77
+ function cleanStyleValue(rawStyle, aggressive) {
78
+ const kept = [];
79
+ String(rawStyle)
80
+ .split(';')
81
+ .forEach((declaration) => {
82
+ const colon = declaration.indexOf(':');
83
+ if (colon < 0) return;
84
+ const prop = declaration.slice(0, colon).trim().toLowerCase();
85
+ let value = declaration.slice(colon + 1).trim();
86
+ if (!prop || !value || !KEEP_PROPS.has(prop)) return;
87
+
88
+ if (aggressive) {
89
+ if (prop === 'font-family') return; // Word 会带入本机字体名,落到文档里只会造成字体混乱
90
+ if (prop === 'font-size') value = snapFontSize(value);
91
+ if (prop === 'line-height') value = snapLineHeight(value);
92
+ if (!value) return;
93
+ }
94
+
95
+ kept.push(`${prop}: ${value}`);
96
+ });
97
+ return kept.join('; ');
98
+ }
99
+
100
+ /** 去掉所有注释节点(Word 的条件注释) */
101
+ function stripComments(root) {
102
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
103
+ const nodes = [];
104
+ while (walker.nextNode()) nodes.push(walker.currentNode);
105
+ nodes.forEach((node) => node.remove());
106
+ }
107
+
108
+ /** 长度声明 → 归一权重(pt / px → px;百分比单独标记);无法解析或非正数返回 null */
109
+ function lengthOf(value) {
110
+ const matched = String(value || '')
111
+ .trim()
112
+ .match(/^([\d.]+)\s*(pt|px|%)?$/i);
113
+ if (!matched) return null;
114
+ const num = Number(matched[1]);
115
+ if (!Number.isFinite(num) || num <= 0) return null;
116
+ const unit = (matched[2] || 'px').toLowerCase();
117
+ if (unit === '%') return { percent: num };
118
+ return { px: unit === 'pt' ? num * (4 / 3) : num };
119
+ }
120
+
121
+ /** 读元素的内联 width 声明(cleanStyleValue 已把样式压成 `prop: value` 序列) */
122
+ function declaredWidthOf(el) {
123
+ for (const declaration of String(el.getAttribute('style') || '').split(';')) {
124
+ const colon = declaration.indexOf(':');
125
+ if (colon < 0) continue;
126
+ if (declaration.slice(0, colon).trim().toLowerCase() === 'width') return declaration.slice(colon + 1).trim();
127
+ }
128
+ return '';
129
+ }
130
+
131
+ /** 元素声明的列宽:优先内联样式,其次 HTML width 属性 */
132
+ const widthOf = (el) => lengthOf(declaredWidthOf(el) || el.getAttribute('width') || '');
133
+
134
+ /** 剥掉结构元素上的定宽声明:表格外框统一交给 CSS 的 width: 100% */
135
+ function stripFixedWidth(el) {
136
+ el.removeAttribute('width');
137
+ const style = el.getAttribute('style');
138
+ if (!style) return;
139
+ const kept = [];
140
+ for (const declaration of style.split(';')) {
141
+ const colon = declaration.indexOf(':');
142
+ if (colon < 0) continue;
143
+ const prop = declaration.slice(0, colon).trim().toLowerCase();
144
+ if (prop === 'width' || prop === 'min-width') continue;
145
+ kept.push(declaration.trim());
146
+ }
147
+ if (kept.length) el.setAttribute('style', kept.join('; '));
148
+ else el.removeAttribute('style');
149
+ }
150
+
151
+ /** 各列宽度 → 归一到合计 100% 的百分比;信息不足返回 null(退化为固定布局等分) */
152
+ function percentWidths(widths, tableWidth) {
153
+ if (!widths.length || widths.some((item) => !item)) return null;
154
+ if (widths.every((item) => item.percent != null)) {
155
+ const total = widths.reduce((sum, item) => sum + item.percent, 0);
156
+ return total > 0 ? widths.map((item) => (item.percent / total) * 100) : null;
157
+ }
158
+ const resolved = widths.map((item) => item.px ?? (tableWidth?.px ? (item.percent / 100) * tableWidth.px : null));
159
+ if (resolved.some((item) => !item)) return null;
160
+ const total = resolved.reduce((sum, item) => sum + item, 0);
161
+ return total > 0 ? resolved.map((item) => (item / total) * 100) : null;
162
+ }
163
+
164
+ /**
165
+ * 粘贴表格的宽度收口:Word / 网页表格会把绝对宽度写进 table、colgroup、col、td,
166
+ * 直接落进正文会覆盖 `table { width: 100% }` 并撑出纸张(用户看到的「跑到页面外侧」)。
167
+ * 这里把列宽换算成 colgroup 百分比、剥掉所有绝对定宽,让表格始终贴合版心;
168
+ * 列宽信息缺失时退化成固定布局等分,也不让像素宽度残留。
169
+ */
170
+ function normalizePastedTable(table) {
171
+ const colgroups = Array.from(table.children).filter((el) => el.tagName === 'COLGROUP');
172
+ const cols = colgroups.flatMap((group) => Array.from(group.children).filter((el) => el.tagName === 'COL'));
173
+ // 找一行没有跨列的格子做列宽来源:标题行整行合并的表格也能从正文行拿到比例
174
+ const plainRow = Array.from(table.rows || []).find((row) => Array.from(row.cells).every((cell) => cell.colSpan === 1));
175
+ const cells = plainRow ? Array.from(plainRow.cells) : [];
176
+ const gridCount = cells.length || cols.length;
177
+ const tableWidth = widthOf(table);
178
+
179
+ let widths = cols.map(widthOf);
180
+ if (cells.length && (cols.length !== cells.length || !widths.some(Boolean))) {
181
+ widths = cells.map(widthOf);
182
+ } else if (cells.length === cols.length) {
183
+ const cellWidths = cells.map(widthOf);
184
+ widths = widths.map((item, i) => item || cellWidths[i]);
185
+ }
186
+
187
+ // 先剥宽再回写,顺序反了会把刚换算好的百分比一起剥掉
188
+ stripFixedWidth(table);
189
+ cols.forEach(stripFixedWidth);
190
+ for (const row of Array.from(table.rows || [])) {
191
+ stripFixedWidth(row);
192
+ for (const cell of Array.from(row.cells)) stripFixedWidth(cell);
193
+ }
194
+ for (const child of Array.from(table.children)) {
195
+ if (!/^(THEAD|TBODY|TFOOT|COLGROUP)$/.test(child.tagName)) continue;
196
+ stripFixedWidth(child);
197
+ for (const row of Array.from(child.children)) if (row.tagName === 'TR') stripFixedWidth(row);
198
+ }
199
+
200
+ const percents = gridCount && widths.length === gridCount ? percentWidths(widths, tableWidth) : null;
201
+ if (!percents) return;
202
+
203
+ if (cols.length === percents.length) {
204
+ cols.forEach((col, i) => {
205
+ col.setAttribute('style', `width: ${Math.round(percents[i] * 10) / 10}%`);
206
+ });
207
+ return;
208
+ }
209
+ colgroups.forEach((group) => group.remove());
210
+ const colgroup = document.createElement('colgroup');
211
+ percents.forEach((percent) => {
212
+ const col = document.createElement('col');
213
+ col.setAttribute('style', `width: ${Math.round(percent * 10) / 10}%`);
214
+ colgroup.appendChild(col);
215
+ });
216
+ table.prepend(colgroup);
217
+ }
218
+
219
+ /** 从 style 串里抽取 vertical-align 的上下标值(Word / 网页粘贴的上下标就是它,不是 sup/sub 标签) */
220
+ const verticalAlignOf = (style) => {
221
+ for (const decl of String(style).split(';')) {
222
+ const colon = decl.indexOf(':');
223
+ if (colon < 0) continue;
224
+ if (decl.slice(0, colon).trim().toLowerCase() !== 'vertical-align') continue;
225
+ const v = decl.slice(colon + 1).trim().toLowerCase();
226
+ if (v === 'super') return 'super';
227
+ if (v === 'sub' || v === 'subscript') return 'sub';
228
+ }
229
+ return '';
230
+ };
231
+
232
+ /**
233
+ * 清洗粘贴进来的 HTML
234
+ * @param {string} html 剪贴板中的 text/html
235
+ * @returns {string} 清洗后的 HTML(交由内核装载)
236
+ */
237
+ export function cleanPastedHtml(html) {
238
+ if (!html || typeof html !== 'string') return html;
239
+ // 无 DOMParser 的环境(服务端渲染 / 单测)原样返回,交给装载侧兜底
240
+ if (typeof DOMParser === 'undefined') return html;
241
+
242
+ const aggressive = OFFICE_SIGNATURE.test(html);
243
+ const parsed = new DOMParser().parseFromString(html, 'text/html');
244
+ const body = parsed.body;
245
+
246
+ // 静态 NodeList,可安全地边遍历边移除
247
+ body.querySelectorAll('*').forEach((el) => {
248
+ const tag = el.tagName.toLowerCase();
249
+ if (DROP_TAGS.has(tag) || tag.includes(':')) {
250
+ el.remove();
251
+ return;
252
+ }
253
+
254
+ el.removeAttribute('class');
255
+ el.removeAttribute('id');
256
+ el.removeAttribute('dir');
257
+ el.removeAttribute('lang');
258
+ el.removeAttribute('align');
259
+ // 事件属性是脚本入口:粘贴内容一律不允许携带(onclick/onerror/onload…)
260
+ for (const attr of Array.from(el.attributes)) {
261
+ if (attr.name.toLowerCase().startsWith('on')) el.removeAttribute(attr.name);
262
+ }
263
+
264
+ if (el.hasAttribute('style')) {
265
+ const rawStyle = el.getAttribute('style');
266
+ const va = verticalAlignOf(rawStyle);
267
+ const cleaned = cleanStyleValue(rawStyle, aggressive);
268
+ if (cleaned) el.setAttribute('style', cleaned);
269
+ else el.removeAttribute('style');
270
+ // 上下标换壳:内核与 docx 写出都只认 sup/sub 标签,vertical-align 声明会在一次编辑重建时被拉平
271
+ if (va && tag === 'span') {
272
+ const box = document.createElement(va === 'super' ? 'sup' : 'sub');
273
+ if (el.hasAttribute('style')) {
274
+ el.replaceWith(box);
275
+ box.appendChild(el);
276
+ } else {
277
+ moveChildren(el, box);
278
+ el.replaceWith(box);
279
+ }
280
+ }
281
+ }
282
+
283
+ // 指向本地文件 / 剪贴板协议的图片粘进来只会是坏图,直接丢掉而不是留个红色占位
284
+ if (tag === 'img') {
285
+ const src = el.getAttribute('src') || '';
286
+ if (!src || !SAFE_IMG.test(src)) el.remove();
287
+ }
288
+ });
289
+
290
+ stripComments(body);
291
+ body.querySelectorAll('table').forEach(normalizePastedTable);
292
+ return body.innerHTML;
293
+ }