@a200888213/gbdocx 0.6.2 → 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.
@@ -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
+ }