gbpptx 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +220 -158
  2. package/package.json +15 -4
  3. package/src/index.js +16 -8
  4. package/src/kernel/model.js +397 -91
  5. package/src/kernel/parts.js +3 -3
  6. package/src/kernel/pptx.js +17 -12
  7. package/src/kernel/read.js +747 -157
  8. package/src/kernel/roundtrip.js +118 -18
  9. package/src/kernel/text.js +133 -28
  10. package/src/kernel/write.js +160 -49
  11. package/web/app/main.js +8 -8
  12. package/web/app/slides/arrange.js +101 -0
  13. package/web/app/slides/clipboard.js +93 -0
  14. package/web/app/slides/file.js +243 -0
  15. package/web/app/slides/find.js +199 -0
  16. package/web/app/slides/history.js +100 -0
  17. package/web/app/slides/keys.js +174 -0
  18. package/web/app/slides/menus.js +105 -0
  19. package/web/app/slides/objects.js +254 -0
  20. package/web/app/slides/render.js +183 -0
  21. package/web/app/slides/shared.js +85 -0
  22. package/web/app/slides/slides.js +103 -0
  23. package/web/app/slides/table.js +102 -0
  24. package/web/app/slides/text.js +418 -0
  25. package/web/app/slides/view.js +130 -0
  26. package/web/app/slides-app.js +285 -844
  27. package/web/app/ui/backstage.js +255 -0
  28. package/web/app/ui/canvas.js +762 -277
  29. package/web/app/ui/color-panel.js +58 -58
  30. package/web/app/ui/dialogs.js +120 -120
  31. package/web/app/ui/file-io.js +116 -89
  32. package/web/app/ui/format-pane.js +427 -0
  33. package/web/app/ui/icons.js +129 -0
  34. package/web/app/ui/menu.js +75 -105
  35. package/web/app/ui/notify.js +45 -45
  36. package/web/app/ui/page-view.js +221 -150
  37. package/web/app/ui/popup.js +80 -80
  38. package/web/app/ui/present.js +292 -100
  39. package/web/app/ui/ribbon.js +878 -0
  40. package/web/app/ui/slide-pane.js +189 -0
  41. package/web/app/ui/statusbar.js +93 -0
  42. package/web/app/ui/text-styles.js +84 -84
  43. package/web/app/ui/titlebar.js +208 -0
  44. package/web/app/ui/transition.js +30 -0
  45. package/web/index.html +23 -21
  46. package/web/serve.mjs +20 -67
  47. package/web/styles/office.css +642 -0
  48. package/web/styles/slides.css +210 -212
  49. package/web/styles/tokens.css +154 -155
  50. package/src/kernel/menus.js +0 -123
  51. package/src/kernel/util/escape.js +0 -21
  52. package/src/kernel/util/id.js +0 -13
  53. package/web/app/ui/inspector.js +0 -209
  54. package/web/app/ui/slides-bar.js +0 -63
  55. package/web/app/ui/toolbar.js +0 -200
@@ -1,39 +1,134 @@
1
- // [文件] gbpptx·保存自检 —— 写出的字节当场读回与模型比对,不一致即拒存(移植 Go 侧无、前端 roundtrip 口径)
1
+ // [文件] gbpptx·保存自检 —— 写出的字节当场读回与模型比对,不一致即拒存
2
2
 
3
3
  import { buildPptx } from './write.js';
4
4
  import { parsePptx } from './read.js';
5
-
6
- /** 正文 HTML 的纯文本摘要(模型侧与读回侧共用,禁各写一份) */
7
- const stripTags = (html) => String(html || '').replace(/<br\s*\/?>/gi, '\n').replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
5
+ import { htmlToParas } from './text.js';
6
+ import { sizeOf, tableStyleColors, transitionOf } from './model.js';
8
7
 
9
8
  const r1 = (v) => Math.round((Number(v) || 0) * 10) / 10;
9
+ const hex = (v) => String(v || '').toLowerCase();
10
10
 
11
11
  // 写出端 xfrm 把 cx/cy 钳到最小 1px(轴向线 h/w=0 存成 1),摘要必须同口径,否则自检永远不过
12
12
  const edge = (v) => r1(Math.max(1, Number(v) || 0));
13
13
 
14
- /** 一个对象的比对摘要(类型白名单内取「能往返」的字段,不比对列宽/行高百分比这类派生值)
14
+ /** 正文的段落摘要:有效对齐 + 列表身份/级别 + 文字(列表必须仍是列表,而不是「• 」字面量) */
15
+ function textDigest(html, fallbackAlign = '') {
16
+ return htmlToParas(html).map((p) => ({
17
+ align: p.align || fallbackAlign || 'left',
18
+ list: p.list || '',
19
+ level: p.level || 0,
20
+ text: p.runs.map((r) => r.text).join(''),
21
+ }));
22
+ }
23
+
24
+ const trimText = (v) => String(v ?? '').replace(/\r/g, '');
25
+
26
+ /** 文本对象实际生效的字号集合(run 内联优先,缺省回落对象字号) */
27
+ function textSizes(html, fallback) {
28
+ const set = new Set();
29
+ for (const p of htmlToParas(html)) {
30
+ for (const r of p.runs) {
31
+ if (r.text === '') continue;
32
+ set.add(r1(r.size > 0 ? r.size : fallback));
33
+ }
34
+ }
35
+ return [...set].sort((a, b) => a - b);
36
+ }
37
+
38
+ /** 一个对象的比对摘要(类型白名单内取「能往返」的字段,不比对列宽/行高这类派生值)
15
39
  * [设计] 文字颜色不参与比对:模型里 color 为空表示「跟随主题」,写出端会落成主题具体色(PowerPoint 必须显式给色),
16
40
  * 回读即得到该具体色——这是主题口径的正常物化,不是内容丢失,故不算自检失败。
17
- * 同理两处白名单:空文本形状不会生成 run,字号无处存放(回读落在默认 24);轴向线的零宽/高被 xfrm 钳成 1px。 */
18
- function objectDigest(o) {
41
+ * 同理:空文本形状不会生成 run,字号无处存放;轴向线的零宽/高被 xfrm 钳成 1px。 */
42
+ function objectDigest(o, theme) {
19
43
  const base = { type: o.type, x: r1(o.x), y: r1(o.y), w: edge(o.w), h: edge(o.h), rot: r1(o.rot) };
20
44
  const p = o.props || {};
21
- if (o.type === 'text') return { ...base, text: stripTags(p.html), size: r1(p.fontSize) };
22
- if (o.type === 'shape') return { ...base, kind: p.kind, fill: (p.fill || '').toLowerCase(), text: String(p.text || '').trim(), size: String(p.text || '').trim() ? r1(p.fontSize) : 0 };
23
- if (o.type === 'line') return { ...base, dash: !!p.dash, arrowEnd: !!p.arrowEnd, strokeW: r1(p.strokeW) };
24
- if (o.type === 'image') return { ...base, src: String(p.src || '').slice(0, 40) };
25
- if (o.type === 'table') return { ...base, rows: (p.rows || []).map((row) => row.map((c) => String(c || '').trim())) };
45
+ if (o.type === 'text') {
46
+ const hasText = textDigest(p.html, p.align).length > 0;
47
+ return {
48
+ ...base,
49
+ paras: textDigest(p.html, p.align),
50
+ sizes: hasText ? textSizes(p.html, p.fontSize) : [],
51
+ anchor: p.anchor || 'top',
52
+ lineSpacing: r1(p.lineSpacing || 1.0),
53
+ fill: hex(p.fill),
54
+ stroke: hex(p.stroke),
55
+ strokeW: r1(p.strokeW),
56
+ };
57
+ }
58
+ if (o.type === 'shape') {
59
+ const text = trimText(p.text);
60
+ return {
61
+ ...base,
62
+ kind: p.kind,
63
+ fill: hex(p.fill),
64
+ stroke: hex(p.stroke),
65
+ strokeW: r1(p.strokeW),
66
+ dash: p.dash || 'solid',
67
+ shadow: !!p.shadow,
68
+ text,
69
+ textColor: text ? hex(p.textColor || '#ffffff') : '',
70
+ size: text ? r1(p.fontSize) : 0,
71
+ align: text ? (p.align || 'center') : '',
72
+ anchor: p.anchor || 'middle',
73
+ lineSpacing: text ? r1(p.lineSpacing || 1) : 0,
74
+ bold: text ? !!p.bold : false,
75
+ italic: text ? !!p.italic : false,
76
+ underline: text ? !!p.underline : false,
77
+ strike: text ? !!p.strike : false,
78
+ };
79
+ }
80
+ if (o.type === 'line') {
81
+ return {
82
+ ...base,
83
+ stroke: hex(p.stroke),
84
+ strokeW: r1(p.strokeW),
85
+ dash: p.dash || 'solid',
86
+ arrowStart: !!p.arrowStart,
87
+ arrowEnd: !!p.arrowEnd,
88
+ };
89
+ }
90
+ if (o.type === 'image') {
91
+ return {
92
+ ...base,
93
+ src: String(p.src || '').slice(0, 40),
94
+ alt: String(p.alt || ''),
95
+ crop: {
96
+ l: Math.round(p.crop?.l || 0), t: Math.round(p.crop?.t || 0),
97
+ r: Math.round(p.crop?.r || 0), b: Math.round(p.crop?.b || 0),
98
+ },
99
+ shadow: !!p.shadow,
100
+ };
101
+ }
102
+ if (o.type === 'table') {
103
+ const style = tableStyleColors(p.tableStyle, theme);
104
+ return {
105
+ ...base,
106
+ rows: (p.rows || []).map((row) => row.map((c) => String(c || '').trim())),
107
+ headerRow: !!p.headerRow,
108
+ bandedRows: !!p.bandedRows,
109
+ tableStyle: p.tableStyle || 'plain',
110
+ size: r1(p.fontSize),
111
+ // 表头/镶边填充由主题推导,比对它们能抓住样式丢失
112
+ styleFill: hex(style.headerFill) + hex(style.bandFill),
113
+ };
114
+ }
26
115
  return base;
27
116
  }
28
117
 
29
118
  /** 整份快照的比对摘要 */
30
119
  const snapshotDigest = (snap) => ({
120
+ size: sizeOf(snap),
31
121
  theme: snap.theme || 'clean',
32
- slides: (snap.slides || []).map((s) => ({
33
- bg: String(s.bg || '').toLowerCase(),
34
- notes: String(s.notes || '').trim(),
35
- objects: (s.objects || []).map(objectDigest),
36
- })),
122
+ slides: (snap.slides || []).map((s) => {
123
+ const tr = transitionOf(s);
124
+ return {
125
+ bg: hex(s.bg),
126
+ notes: String(s.notes || '').trim(),
127
+ hidden: !!s.hidden,
128
+ transition: `${tr.type}/${tr.dir}/${tr.speed}`,
129
+ objects: (s.objects || []).map((o) => objectDigest(o, snap.theme || 'clean')),
130
+ };
131
+ }),
37
132
  });
38
133
 
39
134
  /**
@@ -51,6 +146,9 @@ export async function buildPptxVerified(snapshot) {
51
146
  }
52
147
  const want = snapshotDigest(snapshot);
53
148
  const got = snapshotDigest(back);
149
+ if (want.size.w !== got.size.w || want.size.h !== got.size.h) {
150
+ throw new Error(`保存自检未通过:画幅不一致(应有 ${want.size.w}×${want.size.h},实得 ${got.size.w}×${got.size.h})`);
151
+ }
54
152
  if (want.slides.length !== got.slides.length) {
55
153
  throw new Error(`保存自检未通过:页数不一致(应有 ${want.slides.length},实得 ${got.slides.length})`);
56
154
  }
@@ -59,6 +157,8 @@ export async function buildPptxVerified(snapshot) {
59
157
  const b = got.slides[i];
60
158
  if (a.bg !== b.bg) throw new Error(`保存自检未通过:第 ${i + 1} 页背景色不一致(应有 ${a.bg || '空'},实得 ${b.bg || '空'})`);
61
159
  if (a.notes !== b.notes) throw new Error(`保存自检未通过:第 ${i + 1} 页备注不一致`);
160
+ if (a.hidden !== b.hidden) throw new Error(`保存自检未通过:第 ${i + 1} 页隐藏状态不一致`);
161
+ if (a.transition !== b.transition) throw new Error(`保存自检未通过:第 ${i + 1} 页切换不一致(${a.transition} / ${b.transition})`);
62
162
  if (a.objects.length !== b.objects.length) {
63
163
  throw new Error(`保存自检未通过:第 ${i + 1} 页对象数不一致(应有 ${a.objects.length},实得 ${b.objects.length})`);
64
164
  }
@@ -66,7 +166,7 @@ export async function buildPptxVerified(snapshot) {
66
166
  const setA = new Set(a.objects.map(key));
67
167
  for (const obj of b.objects) {
68
168
  if (!setA.has(key(obj))) {
69
- throw new Error(`保存自检未通过:第 ${i + 1} 页有对象往返后不一致(${JSON.stringify(obj).slice(0, 120)})`);
169
+ throw new Error(`保存自检未通过:第 ${i + 1} 页有对象往返后不一致(${JSON.stringify(obj).slice(0, 160)})`);
70
170
  }
71
171
  }
72
172
  }
@@ -1,6 +1,7 @@
1
- // [文件] gbpptx·正文转换 —— 文本框 HTML 子集 ⇄ 段落/run(块级摊平成段落,列表写成带标记的行;移植 Go text.go)
1
+ // [文件] gbpptx·正文转换 —— 文本框 HTML 子集 ⇄ 段落/run(块级摊平成段落,列表保留符号语义)
2
2
  // [设计] HTML 只认 contenteditable 会产出的那一小撮标签(div/p/br/b/i/u/s/span/font/ul/ol/li):
3
- // 块级一律摊平成段落、行内标记落到 run 上;列表不还原成项目符号,而把「• 」「1. 」写进文字。
3
+ // 块级摊平成段落,行内标记落到 run,列表落到段落的 list/level 上,写出端再变回真正的
4
+ // <a:buChar>/<a:buAutoNum>,而不是把「• 」写进文字——这样 PowerPoint 往返仍是可编辑列表。
4
5
 
5
6
  import { htmlAttr, htmlStyleProp, normalizeColor, xmlEscape } from 'gbooxml';
6
7
 
@@ -11,7 +12,7 @@ const BLOCK_TAGS = new Set(['DIV', 'P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'BLO
11
12
  class ParaCollector {
12
13
  constructor() {
13
14
  this.paras = [];
14
- this.cur = { align: '', runs: [] };
15
+ this.cur = newPara();
15
16
  this.run = null;
16
17
  }
17
18
 
@@ -30,15 +31,16 @@ class ParaCollector {
30
31
  closePara(force) {
31
32
  this.closeRun();
32
33
  if (this.cur.runs.length > 0 || force) this.paras.push(this.cur);
33
- this.cur = { align: this.cur.align, runs: [] };
34
+ this.cur = newPara(this.cur);
34
35
  }
35
36
 
36
- startBlock(align) {
37
+ startBlock(align, list = '', level = 0) {
37
38
  this.closePara(false);
38
- this.cur = { align, runs: [] };
39
+ this.cur = { align, list, level, runs: [] };
39
40
  }
40
41
 
41
- walk(node, f) {
42
+ /** 遍历一个容器;listCtx 用于列表项内部(换行/段落继承列表身份) */
43
+ walk(node, f, listCtx = null) {
42
44
  for (const child of Array.from(node.childNodes)) {
43
45
  if (child.nodeType === Node.TEXT_NODE) {
44
46
  // 元素内的换行是排版空白,真换行由 <br> 表达
@@ -49,38 +51,56 @@ class ParaCollector {
49
51
  const tag = child.tagName;
50
52
  if (tag === 'BR') {
51
53
  this.closePara(true);
54
+ if (listCtx) this.cur = newPara(this.cur, listCtx.list, listCtx.level);
52
55
  } else if (BLOCK_TAGS.has(tag)) {
53
- this.startBlock(blockAlign(child));
54
- this.walk(child, f);
56
+ this.startBlock(blockAlign(child), listCtx?.list || '', listCtx?.level || 0);
57
+ this.walk(child, f, listCtx);
55
58
  this.closePara(false);
59
+ if (listCtx) this.startBlock(blockAlign(child), listCtx.list, listCtx.level);
56
60
  } else if (tag === 'UL' || tag === 'OL') {
57
- this.walkList(child, f, tag === 'OL');
61
+ this.closePara(false);
62
+ this.walkList(child, f, tag === 'OL', (listCtx?.level || -1) + 1);
63
+ if (listCtx) this.startBlock('', listCtx.list, listCtx.level);
58
64
  } else if (tag === 'IMG') {
59
65
  // 图片是独立对象,正文里的 <img> 不进 pptx
60
66
  } else {
61
- this.walk(child, inlineFormat(child, f));
67
+ this.walk(child, inlineFormat(child, f), listCtx);
62
68
  }
63
69
  }
64
70
  }
65
71
 
66
- /** 列表摊平成带标记的行(有序号按 li 顺序编号) */
67
- walkList(list, f, ordered) {
68
- let index = 0;
72
+ /** 列表项 → 带 list/level 的段落;嵌套列表递归到下一级 */
73
+ walkList(list, f, ordered, level) {
69
74
  for (const li of Array.from(list.children)) {
70
75
  if (li.tagName !== 'LI') continue;
71
- index += 1;
72
- this.startBlock(blockAlign(li));
73
- this.addText(f, ordered ? `${index}. ` : '• ');
74
- this.walk(li, f);
76
+ const lvl = listLevel(li, level);
77
+ this.startBlock(blockAlign(li), ordered ? 'number' : 'bullet', lvl);
78
+ this.walk(li, f, { list: ordered ? 'number' : 'bullet', level: lvl });
75
79
  this.closePara(false);
76
80
  }
77
81
  }
78
82
  }
79
83
 
84
+ const newPara = (prev, list = '', level = 0) => ({ align: prev?.align || '', list, level, runs: [] });
85
+
80
86
  const sameFormat = (a, b) =>
81
87
  a.bold === b.bold && a.italic === b.italic && a.underline === b.underline &&
82
88
  a.strike === b.strike && a.color === b.color && a.font === b.font && a.size === b.size;
83
89
 
90
+ /** 列表层级:嵌套层级优先,其次读 parasToHTML 写出的 margin-left */
91
+ function listLevel(li, fallback) {
92
+ const ml = htmlStyleProp(htmlAttr(li, 'style'), 'margin-left');
93
+ if (ml.endsWith('em')) {
94
+ const v = Number.parseFloat(ml);
95
+ if (Number.isFinite(v)) return Math.max(0, Math.min(8, Math.round(v / 1.2)));
96
+ }
97
+ if (ml.endsWith('px')) {
98
+ const v = Number.parseFloat(ml);
99
+ if (Number.isFinite(v)) return Math.max(0, Math.min(8, Math.round(v / 24)));
100
+ }
101
+ return fallback;
102
+ }
103
+
84
104
  /** 块级元素的对齐(contenteditable 写 style,也可能直接给 align 属性) */
85
105
  function blockAlign(el) {
86
106
  const attr = htmlAttr(el, 'align');
@@ -107,7 +127,12 @@ function inlineFormat(el, f) {
107
127
  if (style) {
108
128
  const c = normalizeColor(htmlStyleProp(style, 'color'));
109
129
  if (c !== '') out.color = c;
110
- if (htmlStyleProp(style, 'text-decoration').includes('underline')) out.underline = true;
130
+ const deco = htmlStyleProp(style, 'text-decoration');
131
+ if (deco.includes('underline')) out.underline = true;
132
+ if (deco.includes('line-through')) out.strike = true;
133
+ const weight = htmlStyleProp(style, 'font-weight');
134
+ if (weight === 'bold' || Number(weight) >= 600) out.bold = true;
135
+ if (/italic|oblique/.test(htmlStyleProp(style, 'font-style'))) out.italic = true;
111
136
  const fam = htmlStyleProp(style, 'font-family');
112
137
  if (fam !== '') out.font = fam.split(',')[0].trim().replace(/^['"]|['"]$/g, '');
113
138
  const size = htmlStyleProp(style, 'font-size');
@@ -118,6 +143,8 @@ function inlineFormat(el, f) {
118
143
  }
119
144
  const colorAttr = normalizeColor(htmlAttr(el, 'color'));
120
145
  if (colorAttr !== '') out.color = colorAttr;
146
+ const face = htmlAttr(el, 'face');
147
+ if (face) out.font = face;
121
148
  return out;
122
149
  }
123
150
 
@@ -129,20 +156,37 @@ export function htmlToParas(src) {
129
156
  const c = new ParaCollector();
130
157
  c.walk(box, { bold: false, italic: false, underline: false, strike: false, color: '', font: '', size: 0 });
131
158
  c.closePara(false);
132
- // 末尾空段是 contenteditable 收尾标签的产物,不带信息
159
+ // 末尾空段是 contenteditable / PowerPoint 默认空段落的产物,不带信息
133
160
  while (c.paras.length > 0 && c.paras[c.paras.length - 1].runs.length === 0) c.paras.pop();
134
161
  return c.paras;
135
162
  }
136
163
 
137
- /** 段落序列 → 文本框 HTML(每段一个 div) */
164
+ /** 段落序列 → 文本框 HTML(列表写成 ul/ol,普通段落写成 div) */
138
165
  export function parasToHTML(paras) {
139
166
  let out = '';
167
+ let openList = '';
168
+ const closeList = () => {
169
+ if (openList) out += `</${openList}>`;
170
+ openList = '';
171
+ };
140
172
  for (const p of paras) {
141
- const style = p.align && p.align !== 'left' ? ` style="text-align:${p.align}"` : '';
142
- out += `<div${style}>`;
143
- for (const r of p.runs) out += runToHTML(r);
144
- out += '</div>';
173
+ const list = p.list === 'bullet' ? 'ul' : p.list === 'number' ? 'ol' : '';
174
+ if (list !== openList) {
175
+ closeList();
176
+ if (list) {
177
+ out += `<${list}>`;
178
+ openList = list;
179
+ }
180
+ }
181
+ const align = p.align && p.align !== 'left' ? `text-align:${p.align}` : '';
182
+ const indent = p.level > 0 ? `margin-left:${(p.level * 1.2).toFixed(1)}em` : '';
183
+ const style = [align, indent].filter(Boolean).join(';');
184
+ const styleAttr = style ? ` style="${style}"` : '';
185
+ const body = p.runs.length ? p.runs.map((r) => runToHTML(r)).join('') : '<br>';
186
+ if (list) out += `<li${styleAttr}>${body}</li>`;
187
+ else out += `<div${styleAttr}>${body}</div>`;
145
188
  }
189
+ closeList();
146
190
  return out;
147
191
  }
148
192
 
@@ -162,12 +206,73 @@ export function runToHTML(r) {
162
206
  return text;
163
207
  }
164
208
 
165
- /** 段落 → 纯文本行(表格单元格与图形内文字用) */
166
- export const parasPlainLines = (paras) => paras.map((p) => p.runs.map((r) => r.text).join(''));
209
+ /** 段落 → 纯文本行(表格单元格与图形内文字用;列表带标记、按级别缩进) */
210
+ export function parasPlainLines(paras) {
211
+ let number = 0;
212
+ return paras.map((p) => {
213
+ if (p.list === 'number') number += 1;
214
+ else if (!p.list) number = 0;
215
+ const prefix = p.list === 'bullet' ? '• ' : p.list === 'number' ? `${number}. ` : '';
216
+ return `${' '.repeat(p.level || 0)}${prefix}${p.runs.map((r) => r.text).join('')}`;
217
+ });
218
+ }
167
219
 
168
220
  /** 段落 → 多行纯文本 */
169
221
  export const parasPlainText = (paras) => parasPlainLines(paras).join('\n');
170
222
 
171
223
  /** 纯文本 → 段落(每行一段,图形内文字与表格单元格共用) */
172
224
  export const parasOfPlain = (text) =>
173
- String(text ?? '').split('\n').map((line) => ({ align: '', runs: [{ text: line, bold: false, italic: false, underline: false, strike: false, color: '', font: '', size: 0 }] }));
225
+ String(text ?? '').split('\n').map((line) => ({
226
+ align: '', list: '', level: 0,
227
+ runs: [{ text: line, bold: false, italic: false, underline: false, strike: false, color: '', font: '', size: 0 }],
228
+ }));
229
+
230
+ /** 纯文本行数(字数统计与占位符判断共用) */
231
+ export const countPlainChars = (paras) => paras.reduce((n, p) => n + p.runs.reduce((m, r) => m + r.text.length, 0), 0);
232
+
233
+ const SAFE_TAGS = new Set(['DIV', 'P', 'BR', 'B', 'STRONG', 'I', 'EM', 'U', 'S', 'STRIKE', 'DEL', 'SPAN', 'FONT', 'UL', 'OL', 'LI']);
234
+ const SAFE_STYLES = new Set([
235
+ 'color', 'font-size', 'font-family', 'font-weight', 'font-style',
236
+ 'text-decoration', 'text-align', 'line-height', 'margin-left',
237
+ ]);
238
+ const DROP_TAGS = new Set(['SCRIPT', 'STYLE', 'IFRAME', 'OBJECT', 'EMBED', 'LINK', 'META', 'IMG', 'SVG', 'MATH']);
239
+
240
+ /**
241
+ * 清洗就地编辑器产出的 HTML:只留段落/列表/行内格式白名单,去掉事件属性与可执行样式。
242
+ * 渲染与提交共用同一份,避免粘贴进来的 HTML 在画布里执行脚本。
243
+ */
244
+ export function sanitizeTextHtml(html) {
245
+ if (!html) return '';
246
+ const doc = new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html');
247
+ const clean = (parent) => {
248
+ for (const child of [...parent.childNodes]) {
249
+ if (child.nodeType === Node.TEXT_NODE) continue;
250
+ if (child.nodeType !== Node.ELEMENT_NODE) { child.remove(); continue; }
251
+ if (!SAFE_TAGS.has(child.tagName)) {
252
+ if (DROP_TAGS.has(child.tagName)) {
253
+ child.remove();
254
+ } else {
255
+ while (child.firstChild) parent.insertBefore(child.firstChild, child);
256
+ child.remove();
257
+ }
258
+ continue;
259
+ }
260
+ if (child.hasAttribute('style')) {
261
+ const kept = [];
262
+ for (let i = 0; i < child.style.length; i += 1) {
263
+ const prop = child.style[i];
264
+ if (SAFE_STYLES.has(prop)) kept.push(`${prop}:${child.style.getPropertyValue(prop)}`);
265
+ }
266
+ if (kept.length) child.setAttribute('style', kept.join(';'));
267
+ else child.removeAttribute('style');
268
+ }
269
+ for (const attr of [...child.attributes]) {
270
+ const name = attr.name.toLowerCase();
271
+ if (!['style', 'color', 'face', 'size', 'align'].includes(name)) child.removeAttribute(attr.name);
272
+ }
273
+ clean(child);
274
+ }
275
+ };
276
+ clean(doc.body);
277
+ return doc.body.innerHTML;
278
+ }