gbpptx 0.5.2 → 0.6.1

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,1018 +1,1018 @@
1
- // [文件] gbpptx·解析 —— .pptx 部件还原成 Presentation(文本/图片/图形/线条/表格 + 背景 + 备注 + 切换)
2
- // [设计] 一律只按本地名匹配元素:同一演示里 p:/a:/r: 三套前缀混排,写死前缀会在别人的文件上整页解析失败。
3
- // [设计] 占位符(placeholder)常常不在页内写 xfrm,几何要从版式/母版继承;组合形状(grpSp)摊平成页内元素。
4
- // [坑] 页面尺寸按 sldSz 保留长宽比缩放到 960/540 基准,4:3 与自定义画幅不会被强行拉成 16:9。
5
-
6
- import { EMU_PER_PX, REL_NS, emuToPx, encodeDataUrl, normalizeColor, openOpc, parseNode, resolveTarget } from 'gbooxml';
7
- import { DEFAULT_THEME, PRST_TO_KIND, SLIDE_H, SLIDE_W, THEMES_HEX, isPptx, isThemeKey, szToFontSize } from './pptx.js';
8
- import { contrastText, tableStyleColors } from './model.js';
9
- import { PART_MASTER, PART_PRESENTATION, PART_THEME, REL_LAYOUT, REL_MASTER, REL_NOTES, THEME_NAME_PREFIX, slidePath } from './parts.js';
10
- import { parasPlainText, parasToHTML } from './text.js';
11
-
12
- const LINE_STROKE_W = 2;
13
- const SHAPE_STROKE_W = 1;
14
- const DEFAULT_LINE_SPACING = 1.0;
15
-
16
- /**
17
- * 把 .pptx 字节解析成快照(Presentation)
18
- * @param {Uint8Array|ArrayBuffer} data
19
- * @returns {Promise<object>} {version:2, theme, size, slides:[{id,bg,notes,hidden,transition,objects}], warnings}
20
- */
21
- export async function parsePptx(data) {
22
- if (!isPptx(data)) throw new Error('不是有效的 pptx 文件');
23
- let pkg;
24
- try {
25
- pkg = await openOpc(data);
26
- } catch {
27
- throw new Error('不是有效的 pptx 文件');
28
- }
29
- const raw = pkg.part(PART_PRESENTATION);
30
- if (!raw) throw new Error('pptx 缺少 ppt/presentation.xml');
31
- let pres;
32
- try {
33
- pres = parseNode(raw);
34
- } catch (err) {
35
- throw new Error(`无法解析 presentation.xml:${err.message || err}`);
36
- }
37
-
38
- const theme = themeKeyOf(pkg);
39
- const themeHex = THEMES_HEX[theme] || THEMES_HEX[DEFAULT_THEME];
40
- const colors = themeColorsOf(pkg, theme);
41
- const { size, sx, sy } = canvasOf(pres);
42
- const ctx = { size, sx, sy, colors, theme, themeText: `#${themeHex.text}`, themeAccent: `#${themeHex.accent}` };
43
- const warnings = { groups: 0, charts: 0, media: 0, unknown: 0 };
44
-
45
- const entries = slideEntries(pres, pkg);
46
- if (entries.length === 0) throw new Error('pptx 里没有幻灯片');
47
-
48
- const masterTree = readPartTree(pkg, masterPathOf(pkg));
49
- const out = { version: 2, title: '', theme, size, slides: [], warnings };
50
- entries.forEach((entry, i) => {
51
- const rawSlide = pkg.part(entry.path);
52
- if (!rawSlide) return;
53
- let tree;
54
- try {
55
- tree = parseNode(rawSlide);
56
- } catch {
57
- return;
58
- }
59
- const rels = pkg.rels(entry.path);
60
- const layoutTree = readPartTree(pkg, layoutPathOf(rels, entry.path));
61
- const slide = parseSlide(tree, rels, pkg, entry.path, ctx, layoutTree, masterTree, warnings);
62
- slide.id = `s-import${i + 1}`;
63
- slide.hidden = entry.hidden;
64
- slide.notes = notesText(pkg, rels, entry.path);
65
- // 写出时页底色一律显式落 p:bg;回读时把「恰好等于本主题底色」的页判回「随主题」
66
- if (isThemeKey(theme) && String(slide.bg).replace('#', '').toLowerCase() === themeHex.bg.toLowerCase()) {
67
- slide.bg = '';
68
- }
69
- out.slides.push(slide);
70
- });
71
- if (out.slides.length === 0) throw new Error('pptx 里没有可解析的幻灯片');
72
- return out;
73
- }
74
-
75
- /* ---------- 画幅 ---------- */
76
-
77
- /** 源尺寸 → 以 960×540 为基准的等比画幅(宽屏取 960,纵向取 540) */
78
- function canvasOf(pres) {
79
- let srcW = SLIDE_W;
80
- let srcH = SLIDE_H;
81
- const sz = pres.child('sldSz');
82
- if (sz) {
83
- const cx = attrInt64(sz, 'cx');
84
- const cy = attrInt64(sz, 'cy');
85
- srcW = cx > 0 ? emuToPx(cx, 1) : srcW;
86
- srcH = cy > 0 ? emuToPx(cy, 1) : srcH;
87
- }
88
- const ratio = srcW / srcH;
89
- let w;
90
- let h;
91
- if (ratio >= SLIDE_W / SLIDE_H) {
92
- w = SLIDE_W;
93
- h = Math.max(120, Math.round(SLIDE_W / ratio));
94
- } else {
95
- h = SLIDE_H;
96
- w = Math.max(120, Math.round(SLIDE_H * ratio));
97
- }
98
- return { size: { w, h }, sx: w / srcW, sy: h / srcH };
99
- }
100
-
101
- /* ---------- 部件路径 ---------- */
102
-
103
- function readPartTree(pkg, path) {
104
- if (!path) return null;
105
- const raw = pkg.part(path);
106
- if (!raw) return null;
107
- try {
108
- return parseNode(raw);
109
- } catch {
110
- return null;
111
- }
112
- }
113
-
114
- function relPath(rels, fromPart, type) {
115
- for (const rel of rels.values()) {
116
- if (rel.type === type) return resolveTarget(fromPart, rel.target);
117
- }
118
- return '';
119
- }
120
-
121
- const masterPathOf = (pkg) => {
122
- const presRels = pkg.rels(PART_PRESENTATION);
123
- return relPath(presRels, PART_PRESENTATION, REL_MASTER) || PART_MASTER;
124
- };
125
-
126
- const layoutPathOf = (rels, slidePart) => relPath(rels, slidePart, REL_LAYOUT);
127
-
128
- /* ---------- 页序 ---------- */
129
-
130
- /** 页序来自 sldIdLst 的关系(文件名顺序不可靠);关系表缺失时退回按 slide1..N 连续探测 */
131
- function slideEntries(pres, pkg) {
132
- const presRels = pkg.rels(PART_PRESENTATION);
133
- const out = [];
134
- const lst = pres.child('sldIdLst');
135
- if (lst) {
136
- for (const sid of lst.children('sldId')) {
137
- const rel = presRels.get(relAttr(sid, 'id'));
138
- if (rel) out.push({ path: resolveTarget(PART_PRESENTATION, rel.target), hidden: sid.attr('show') === '0' });
139
- }
140
- }
141
- if (out.length > 0) return out;
142
- for (let i = 1; ; i += 1) {
143
- const p = slidePath(i);
144
- if (!pkg.has(p)) break;
145
- out.push({ path: p, hidden: false });
146
- }
147
- return out;
148
- }
149
-
150
- /* ---------- 主题色 ---------- */
151
-
152
- const THEME_SCHEME_KEYS = ['dk1', 'lt1', 'dk2', 'lt2', 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6', 'hlink', 'folHlink'];
153
-
154
- function themeKeyOf(pkg) {
155
- const raw = pkg.part(PART_THEME);
156
- if (!raw) return DEFAULT_THEME;
157
- let tree;
158
- try {
159
- tree = parseNode(raw);
160
- } catch {
161
- return DEFAULT_THEME;
162
- }
163
- const key = tree.attr('name').replace(new RegExp(`^${THEME_NAME_PREFIX}`), '');
164
- return isThemeKey(key) ? key : DEFAULT_THEME;
165
- }
166
-
167
- /** 主题部件里的实际色值(外部文件的 schemeClr 靠它落成具体颜色) */
168
- function themeColorsOf(pkg, themeKey) {
169
- const t = THEMES_HEX[themeKey] || THEMES_HEX[DEFAULT_THEME];
170
- const out = {
171
- tx1: `#${t.text}`, bg1: `#${t.bg}`, tx2: `#${t.text}`, bg2: `#${t.bg}`,
172
- dk1: `#${t.text}`, lt1: `#${t.bg}`, dk2: `#${t.text}`, lt2: `#${t.bg}`,
173
- hlink: '#1d6fd4', folHlink: '#8e44ad',
174
- };
175
- for (let i = 1; i <= 6; i += 1) out[`accent${i}`] = `#${t.accent}`;
176
- const tree = readPartTree(pkg, PART_THEME);
177
- const scheme = tree?.find('themeElements', 'clrScheme');
178
- if (!scheme) return out;
179
- for (const key of THEME_SCHEME_KEYS) {
180
- const node = scheme.child(key);
181
- if (!node || node.kids.length === 0) continue;
182
- const hex = colorNodeToHex(node.kids[0], { colors: out });
183
- if (hex) out[key] = hex;
184
- }
185
- out.tx1 = out.dk1;
186
- out.tx2 = out.dk2;
187
- out.bg1 = out.lt1;
188
- out.bg2 = out.lt2;
189
- return out;
190
- }
191
-
192
- /* ---------- 页面 ---------- */
193
-
194
- function parseSlide(tree, rels, pkg, slidePart, ctx, layoutTree, masterTree, warnings) {
195
- const slide = { id: '', bg: '', notes: '', hidden: false, transition: parseTransition(tree), objects: [] };
196
- // 页底色:页内 → 版式 → 母版 → 主题 bg1(外部幻灯片常不写 p:bg,只靠母版/主题)
197
- slide.bg = backgroundColorOf(tree, ctx)
198
- || backgroundColorOf(layoutTree, ctx)
199
- || backgroundColorOf(masterTree, ctx)
200
- || ctx.colors.bg1
201
- || '';
202
- const spTree = tree.find('cSld', 'spTree');
203
- if (!spTree) return slide;
204
- let z = 1;
205
- const push = (obj) => {
206
- if (!obj) return;
207
- obj.id = `o-import${z}`;
208
- obj.z = z;
209
- z += 1;
210
- slide.objects.push(obj);
211
- };
212
- const structural = new Set(['nvGrpSpPr', 'grpSpPr', 'extLst']);
213
- walkSpTree(spTree, null, (node, transform) => {
214
- const kw = { ctx, rels, pkg, slidePart, layoutTree, masterTree, transform, warnings };
215
- switch (node.name) {
216
- case 'sp': push(parseSp(node, kw)); break;
217
- case 'cxnSp': push(parseCxnSp(node, kw)); break;
218
- case 'pic': push(parsePic(node, kw)); break;
219
- case 'graphicFrame': push(parseGraphicFrame(node, kw)); break;
220
- default: if (!structural.has(node.name)) warnings.unknown += 1; break;
221
- }
222
- }, warnings);
223
- return slide;
224
- }
225
-
226
- /** 遍历 spTree,遇到 grpSp 就合成坐标变换后摊平(不保留组合语义,但内容不丢) */
227
- function walkSpTree(parent, transform, emit, warnings) {
228
- for (const node of parent.kids) {
229
- if (node.name === 'grpSp') {
230
- warnings.groups += 1;
231
- const local = groupTransform(node.find('grpSpPr', 'xfrm'));
232
- walkSpTree(node, composeTransform(transform, local), emit, warnings);
233
- } else {
234
- emit(node, transform);
235
- }
236
- }
237
- }
238
-
239
- function groupTransform(xf) {
240
- if (!xf) return null;
241
- const off = xf.child('off');
242
- const ext = xf.child('ext');
243
- const chOff = xf.child('chOff');
244
- const chExt = xf.child('chExt');
245
- if (!off || !ext || !chOff || !chExt) return null;
246
- const ex = attrInt64(ext, 'cx');
247
- const ey = attrInt64(ext, 'cy');
248
- const cx = attrInt64(chExt, 'cx');
249
- const cy = attrInt64(chExt, 'cy');
250
- const kx = cx > 0 ? ex / cx : 1;
251
- const ky = cy > 0 ? ey / cy : 1;
252
- return {
253
- kx, ky,
254
- tx: attrInt64(off, 'x') - attrInt64(chOff, 'x') * kx,
255
- ty: attrInt64(off, 'y') - attrInt64(chOff, 'y') * ky,
256
- };
257
- }
258
-
259
- function composeTransform(parent, local) {
260
- if (!local) return parent;
261
- if (!parent) return local;
262
- return {
263
- kx: local.kx * parent.kx,
264
- ky: local.ky * parent.ky,
265
- tx: local.tx * parent.kx + parent.tx,
266
- ty: local.ty * parent.ky + parent.ty,
267
- };
268
- }
269
-
270
- /** 位置 / 尺寸 / 旋转 / 翻转(EMU → 逻辑像素;组合变换先生效) */
271
- function parseXfrm(xf, ctx, transform) {
272
- if (!xf) return null;
273
- const off = xf.child('off');
274
- const ext = xf.child('ext');
275
- if (!off || !ext) return null;
276
- let x = attrInt64(off, 'x');
277
- let y = attrInt64(off, 'y');
278
- let w = attrInt64(ext, 'cx');
279
- let h = attrInt64(ext, 'cy');
280
- if (transform) {
281
- x = x * transform.kx + transform.tx;
282
- y = y * transform.ky + transform.ty;
283
- w *= transform.kx;
284
- h *= transform.ky;
285
- }
286
- return {
287
- x: emuToPx(x, 1) * ctx.sx,
288
- y: emuToPx(y, 1) * ctx.sy,
289
- w: emuToPx(w, 1) * ctx.sx,
290
- h: emuToPx(h, 1) * ctx.sy,
291
- rot: attrInt64(xf, 'rot') / 60000,
292
- flipH: xf.attr('flipH') === '1',
293
- flipV: xf.attr('flipV') === '1',
294
- };
295
- }
296
-
297
- /** 占位符的 ph 元素(sp/pic/graphicFrame 通用) */
298
- function placeholderOf(node) {
299
- const paths = [['nvSpPr', 'nvPr', 'ph'], ['nvPicPr', 'nvPr', 'ph'], ['nvGraphicFramePr', 'nvPr', 'ph'], ['nvCxnSpPr', 'nvPr', 'ph']];
300
- for (const p of paths) {
301
- const ph = node.find(...p);
302
- if (ph) return ph;
303
- }
304
- return null;
305
- }
306
-
307
- /** 从版式/母版找同名占位符的 xfrm(idx 优先,其次 type) */
308
- function placeholderXfrm(tree, ph) {
309
- if (!tree || !ph) return null;
310
- const wantIdx = ph.attr('idx');
311
- const wantType = ph.attr('type');
312
- const candidates = [];
313
- const spTree = tree.find('cSld', 'spTree');
314
- if (!spTree) return null;
315
- for (const sp of spTree.children('sp')) {
316
- const p = sp.find('nvSpPr', 'nvPr', 'ph');
317
- if (!p) continue;
318
- const xf = sp.find('spPr', 'xfrm');
319
- if (!xf) continue;
320
- candidates.push({ ph: p, xf });
321
- }
322
- if (candidates.length === 0) return null;
323
- if (wantIdx !== '') {
324
- const hit = candidates.find((c) => c.ph.attr('idx') === wantIdx);
325
- if (hit) return hit.xf;
326
- }
327
- if (wantType !== '') {
328
- const hit = candidates.find((c) => c.ph.attr('type') === wantType);
329
- if (hit) return hit.xf;
330
- }
331
- const fallback = candidates.find((c) => c.ph.attr('idx') === '' && c.ph.attr('type') === '');
332
- return fallback ? fallback.xf : candidates[0].xf;
333
- }
334
-
335
- /** 占位符几何与默认字号(版式/母版都没有时兜底) */
336
- function placeholderLayout(node, layoutTree, masterTree, ctx) {
337
- const ph = placeholderOf(node);
338
- if (!ph) return null;
339
- const type = ph.attr('type');
340
- const xf = placeholderXfrm(layoutTree, ph) || placeholderXfrm(masterTree, ph);
341
- const parsed = xf ? parseXfrm(xf, ctx, null) : null;
342
- return { type, xf: parsed, size: placeholderFontSize(type) };
343
- }
344
-
345
- function placeholderFontSize(type) {
346
- switch (type) {
347
- case 'title': case 'ctrTitle': return 40;
348
- case 'subTitle': return 24;
349
- case 'body': case 'obj': return 20;
350
- default: return 24;
351
- }
352
- }
353
-
354
- function fallbackPlaceholder(type, ctx) {
355
- const { w, h } = ctx.size;
356
- const kind = type || 'obj';
357
- if (kind === 'title' || kind === 'ctrTitle') {
358
- return { x: w * 0.08, y: h * 0.12, w: w * 0.84, h: h * 0.16 };
359
- }
360
- if (kind === 'subTitle') return { x: w * 0.18, y: h * 0.34, w: w * 0.64, h: h * 0.12 };
361
- if (kind === 'ftr' || kind === 'dt' || kind === 'sldNum') return { x: w * 0.06, y: h * 0.9, w: w * 0.88, h: h * 0.07 };
362
- return { x: w * 0.08, y: h * 0.3, w: w * 0.84, h: h * 0.55 };
363
- }
364
-
365
- /** 页/版式/母版的背景色:bgPr 的 solidFill/gradFill,或 bgRef 引用的主题色 */
366
- function backgroundColorOf(tree, ctx) {
367
- if (!tree) return '';
368
- const bgPr = tree.find('cSld', 'bg', 'bgPr');
369
- if (bgPr) {
370
- const color = fillColorOf(bgPr, ctx);
371
- if (color) return color;
372
- }
373
- const ref = tree.find('cSld', 'bg', 'bgRef');
374
- if (ref) {
375
- for (const child of ref.kids) {
376
- const color = colorNodeToHex(child, ctx);
377
- if (color) return color;
378
- }
379
- return ctx.colors.bg1 || '';
380
- }
381
- return '';
382
- }
383
-
384
- /* ---------- 形状 ---------- */
385
-
386
- /** 文本框或预设几何图形:txBox / 占位符优先,其余按填充与预设形状判别 */
387
- function parseSp(node, kw) {
388
- const { ctx, layoutTree, masterTree, transform } = kw;
389
- const spPr = node.child('spPr');
390
- if (!spPr) return null;
391
- const holder = placeholderLayout(node, layoutTree, masterTree, ctx);
392
- let xf = parseXfrm(spPr.child('xfrm'), ctx, transform);
393
- if (!xf && holder?.xf) xf = holder.xf;
394
- if (!xf && holder) {
395
- const fb = fallbackPlaceholder(holder.type, ctx);
396
- xf = { ...fb, rot: 0, flipH: false, flipV: false };
397
- }
398
- if (!xf || xf.w <= 0 || xf.h <= 0) return null;
399
-
400
- const txBody = node.child('txBody');
401
- const paras = parseTxBody(txBody, ctx);
402
- const cNv = node.find('nvSpPr', 'cNvSpPr');
403
- const txBox = cNv?.attr('txBox') === '1';
404
-
405
- const prstNode = spPr.child('prstGeom');
406
- const prst = prstNode ? prstNode.attr('prst') : '';
407
- const kind = PRST_TO_KIND[prst] || '';
408
- const styleFill = shapeStyleFill(node, ctx);
409
- let fill = fillColorOf(spPr, ctx);
410
- if (fill === '' && styleFill) fill = styleFill;
411
- const stroke = parseStroke(spPr.child('ln'), ctx, SHAPE_STROKE_W);
412
- const shadow = hasShadow(spPr);
413
- const body = bodyProps(txBody, ctx);
414
- const textStyle = objectTextStyle(paras, holder?.size || 24);
415
-
416
- // 只有「有视觉的几何」才算形状:矩形 + 无填充无色 + 有文字,是文本框而不是隐形形状
417
- const visual = fill !== '' || stroke.color !== '' || shadow || (prst !== '' && prst !== 'rect');
418
- const asText = txBox || (holder && paras.length > 0) || (!visual && paras.length > 0);
419
- if (asText) {
420
- if (paras.length === 0 && !txBox) return null;
421
- const paraStyle = objectParaStyle(paras);
422
- return {
423
- id: '', type: 'text', x: xf.x, y: xf.y, w: xf.w, h: xf.h, rot: xf.rot, z: 0,
424
- props: {
425
- html: parasToHTML(paras),
426
- font: textStyle.font,
427
- fontSize: textStyle.size,
428
- color: textStyle.color,
429
- align: paraStyle.align,
430
- bold: textStyle.bold,
431
- italic: textStyle.italic,
432
- underline: textStyle.underline,
433
- strike: textStyle.strike,
434
- anchor: body.anchor,
435
- lineSpacing: paraStyle.lineSpacing,
436
- fill,
437
- stroke: stroke.color,
438
- strokeW: stroke.width,
439
- },
440
- };
441
- }
442
- if (!visual) return null;
443
-
444
- return {
445
- id: '', type: 'shape', x: xf.x, y: xf.y, w: xf.w, h: xf.h, rot: xf.rot, z: 0,
446
- props: {
447
- kind: kind || 'rect',
448
- fill: fill || '',
449
- stroke: stroke.color,
450
- strokeW: stroke.width,
451
- dash: stroke.dash,
452
- shadow,
453
- text: parasPlainText(paras),
454
- textColor: textStyle.color || (fill ? contrastText(fill) : ctx.themeText),
455
- font: textStyle.font,
456
- fontSize: textStyle.size,
457
- bold: textStyle.bold,
458
- italic: textStyle.italic,
459
- underline: textStyle.underline,
460
- strike: textStyle.strike,
461
- align: objectParaStyle(paras).align || 'left',
462
- anchor: body.anchor,
463
- lineSpacing: objectParaStyle(paras).lineSpacing,
464
- },
465
- };
466
- }
467
-
468
- /** p:style 里的 fillRef(外部形状没有显式填充时靠它拿到主题强调色) */
469
- function shapeStyleFill(node, ctx) {
470
- const style = node.child('style');
471
- if (!style) return '';
472
- const ref = style.child('fillRef');
473
- if (!ref) return '';
474
- const idx = Number.parseInt(ref.attr('idx'), 10);
475
- if (!(idx > 0)) return '';
476
- for (const child of ref.kids) {
477
- const hex = colorNodeToHex(child, ctx);
478
- if (hex) return hex;
479
- }
480
- return ctx.colors.accent1 || '';
481
- }
482
-
483
- /** 直线连接符:编辑器存起点 + 向量,故用翻转还原方向 */
484
- function parseCxnSp(node, kw) {
485
- const { ctx, transform } = kw;
486
- const spPr = node.child('spPr');
487
- if (!spPr) return null;
488
- const xf = parseXfrm(spPr.child('xfrm'), ctx, transform);
489
- if (!xf) return null;
490
- const stroke = parseStroke(spPr.child('ln'), ctx, LINE_STROKE_W);
491
- let { x, y, w, h } = xf;
492
- if (xf.flipH) { x += w; w = -w; }
493
- if (xf.flipV) { y += h; h = -h; }
494
- return {
495
- id: '', type: 'line', x, y, w, h, rot: 0, z: 0,
496
- props: {
497
- stroke: stroke.color || ctx.themeText,
498
- strokeW: stroke.width,
499
- dash: stroke.dash,
500
- arrowStart: stroke.arrowStart,
501
- arrowEnd: stroke.arrowEnd,
502
- },
503
- };
504
- }
505
-
506
- function parsePic(node, kw) {
507
- const { rels, pkg, slidePart, ctx, transform, warnings } = kw;
508
- const spPr = node.child('spPr');
509
- if (!spPr) return null;
510
- const xf = parseXfrm(spPr.child('xfrm'), ctx, transform);
511
- if (!xf || xf.w <= 0 || xf.h <= 0) return null;
512
- if (node.find('nvPicPr', 'nvPr', 'videoFile') || node.find('nvPicPr', 'nvPr', 'audioFile')) warnings.media += 1;
513
- const blip = node.find('blipFill', 'blip');
514
- if (!blip) return null;
515
- const rid = relAttr(blip, 'embed') || relAttr(blip, 'link');
516
- const rel = rels.get(rid);
517
- if (!rel) return null;
518
- const raw = pkg.part(resolveTarget(slidePart, rel.target));
519
- if (!raw) return null;
520
- const ext = String(rel.target).split('.').pop().toLowerCase();
521
- const cropNode = node.find('blipFill', 'srcRect');
522
- const crop = {
523
- l: cropNode ? Math.round(attrInt64(cropNode, 'l') / 1000) : 0,
524
- t: cropNode ? Math.round(attrInt64(cropNode, 't') / 1000) : 0,
525
- r: cropNode ? Math.round(attrInt64(cropNode, 'r') / 1000) : 0,
526
- b: cropNode ? Math.round(attrInt64(cropNode, 'b') / 1000) : 0,
527
- };
528
- const cNv = node.find('nvPicPr', 'cNvPr');
529
- return {
530
- id: '', type: 'image', x: xf.x, y: xf.y, w: xf.w, h: xf.h, rot: xf.rot, z: 0,
531
- props: {
532
- src: encodeDataUrl(raw, ext),
533
- alt: cNv ? cNv.attr('descr') : '',
534
- crop,
535
- shadow: hasShadow(spPr),
536
- },
537
- };
538
- }
539
-
540
- function parseGraphicFrame(node, kw) {
541
- const { ctx, transform, warnings } = kw;
542
- const xf = parseXfrm(node.child('xfrm'), ctx, transform);
543
- if (!xf || xf.w <= 0 || xf.h <= 0) return null;
544
- const tbl = node.find('graphic', 'graphicData', 'tbl');
545
- if (!tbl) {
546
- if (node.find('graphic', 'graphicData', 'chart')) warnings.charts += 1;
547
- else warnings.unknown += 1;
548
- return null;
549
- }
550
- const tp = tbl.child('tblPr');
551
- const headerRow = tp ? tp.attr('firstRow') === '1' : false;
552
- const bandedRows = tp ? tp.attr('bandRow') === '1' : false;
553
- const body = parseTableBody(tbl, ctx, headerRow);
554
- if (body.rows.length === 0) return null;
555
- const style = inferTableStyle(tbl, body, ctx, headerRow, bandedRows);
556
- return {
557
- id: '', type: 'table', x: xf.x, y: xf.y, w: xf.w, h: xf.h, rot: 0, z: 0,
558
- props: {
559
- rows: body.rows,
560
- headerRow,
561
- bandedRows,
562
- tableStyle: style,
563
- font: body.font,
564
- fontSize: body.size,
565
- color: body.color,
566
- colW: tableColPercents(tbl),
567
- rowH: tableRowPercents(tbl),
568
- },
569
- };
570
- }
571
-
572
- /** 表格正文行 + 首个有效 run 的字号/颜色/字体(正文样式优先取非表头行,避免把表头白字当默认色) */
573
- function parseTableBody(tbl, ctx, headerRow) {
574
- const rows = [];
575
- const styles = [];
576
- for (const tr of tbl.children('tr')) {
577
- const row = [];
578
- const rowStyles = [];
579
- for (const tc of tr.children('tc')) {
580
- const paras = parseTxBody(tc.child('txBody'), ctx);
581
- row.push(parasPlainText(paras));
582
- rowStyles.push(objectTextStyle(paras, 0));
583
- }
584
- if (row.length > 0) {
585
- rows.push(row);
586
- styles.push(rowStyles);
587
- }
588
- }
589
- const pick = (key) => {
590
- const order = headerRow ? [...styles.keys()].slice(1).concat([0]) : [...styles.keys()];
591
- for (const ri of order) {
592
- for (const s of styles[ri] || []) {
593
- if (key === 'size') { if (s.size > 0) return s.size; }
594
- else if (s[key] !== '') return s[key];
595
- }
596
- }
597
- return '';
598
- };
599
- return { rows, size: pick('size') || 16, color: pick('color'), font: pick('font') };
600
- }
601
-
602
- /** 列宽百分比(tblGrid 的 gridCol 比例) */
603
- function tableColPercents(tbl) {
604
- const grid = tbl.child('tblGrid');
605
- if (!grid) return [];
606
- const widths = [];
607
- let sum = 0;
608
- for (const gc of grid.children('gridCol')) {
609
- const v = Number.parseFloat(gc.attr('w'));
610
- if (!Number.isFinite(v) || v <= 0) continue;
611
- widths.push(v);
612
- sum += v;
613
- }
614
- if (widths.length < 2 || sum <= 0) return [];
615
- return widths.map((v) => (v / sum) * 100);
616
- }
617
-
618
- /** 行高百分比(tr@h;缺失时返回空表,让渲染端等分) */
619
- function tableRowPercents(tbl) {
620
- const heights = [];
621
- let sum = 0;
622
- for (const tr of tbl.children('tr')) {
623
- const v = Number.parseFloat(tr.attr('h'));
624
- if (!Number.isFinite(v) || v <= 0) return [];
625
- heights.push(v);
626
- sum += v;
627
- }
628
- if (heights.length < 2 || sum <= 0) return [];
629
- return heights.map((v) => (v / sum) * 100);
630
- }
631
-
632
- /** 从表头/镶边填充反推表格样式(本包写出的文件能原样还原) */
633
- function inferTableStyle(tbl, body, ctx, headerRow, bandedRows) {
634
- const head = headerRow ? cellFill(tbl, 0, 0, ctx) : '';
635
- if (headerRow) {
636
- if (!head) return 'plain';
637
- if (sameColor(head, ctx.themeAccent)) {
638
- for (let ri = 1; ri < (body.rows || []).length; ri += 1) {
639
- const band = cellFill(tbl, ri, 0, ctx);
640
- if (band) return nearestBandStyle(band, ctx);
641
- }
642
- return 'header';
643
- }
644
- return 'plain';
645
- }
646
- // 没有表头行时,扫描所有行找镶边填充
647
- for (let ri = 0; ri < (body.rows || []).length; ri += 1) {
648
- const fill = cellFill(tbl, ri, 0, ctx);
649
- if (fill) return nearestBandStyle(fill, ctx);
650
- }
651
- return 'plain';
652
- }
653
-
654
- /** 深色主题下「镶边」与「深色」都可能偏暗,按与主题推导色的距离判定而不是亮度 */
655
- function nearestBandStyle(fill, ctx) {
656
- const banded = tableStyleColors('banded', ctx.theme).bandFill;
657
- const dark = tableStyleColors('dark', ctx.theme).bandFill;
658
- return colorDistance(fill, banded) <= colorDistance(fill, dark) ? 'banded' : 'dark';
659
- }
660
-
661
- function colorDistance(a, b) {
662
- const x = hexToRgb(a);
663
- const y = hexToRgb(b);
664
- return Math.abs(x.r - y.r) + Math.abs(x.g - y.g) + Math.abs(x.b - y.b);
665
- }
666
-
667
- function cellFill(tbl, rowIndex, colIndex, ctx) {
668
- const tr = tbl.children('tr')[rowIndex];
669
- if (!tr) return '';
670
- const tc = tr.children('tc')[colIndex];
671
- if (!tc) return '';
672
- return fillColorOf(tc.child('tcPr'), ctx);
673
- }
674
-
675
- const sameColor = (a, b) => String(a).toLowerCase() === String(b).toLowerCase();
676
- /* ---------- 切换 ---------- */
677
-
678
- function parseTransition(tree) {
679
- const node = tree.child('transition');
680
- if (!node) return { type: 'none', dir: 'l', speed: 'med' };
681
- const speed = ['slow', 'med', 'fast'].includes(node.attr('spd')) ? node.attr('spd') : 'med';
682
- for (const child of node.kids) {
683
- if (child.name === 'fade') return { type: 'fade', dir: 'l', speed };
684
- if (child.name === 'push') return { type: 'push', dir: child.attr('dir') || 'l', speed };
685
- if (child.name === 'wipe') return { type: 'wipe', dir: child.attr('dir') || 'l', speed };
686
- if (child.name === 'cover') return { type: 'cover', dir: child.attr('dir') || 'l', speed };
687
- if (child.name === 'split') return { type: 'split', dir: 'l', speed };
688
- if (child.name === 'zoom') return { type: 'zoom', dir: 'l', speed };
689
- }
690
- return { type: 'none', dir: 'l', speed: 'med' };
691
- }
692
-
693
- /* ---------- 文本 ---------- */
694
-
695
- /** txBody → 段落序列(<a:br> 视作换行,即另起一段;保留项目符号与行距) */
696
- function parseTxBody(tx, ctx) {
697
- if (!tx) return [];
698
- let paras = [];
699
- for (const p of tx.children('p')) {
700
- const ppr = p.child('pPr');
701
- const align = alignOf(ppr);
702
- const list = listOf(ppr);
703
- const level = ppr ? Math.max(0, Math.min(8, Number.parseInt(ppr.attr('lvl'), 10) || 0)) : 0;
704
- const lineSpacing = lineSpacingOf(ppr);
705
- let para = { align, list, level, lineSpacing, runs: [] };
706
- const flush = () => {
707
- paras.push(para);
708
- para = { align, list, level, lineSpacing, runs: [] };
709
- };
710
- for (const node of p.kids) {
711
- if (node.name === 'br') {
712
- flush();
713
- } else if (node.name === 'r' || node.name === 'fld') {
714
- const t = node.child('t');
715
- if (!t || t.text === '') continue;
716
- const run = { text: t.text, bold: false, italic: false, underline: false, strike: false, color: '', font: '', size: 0 };
717
- const rPr = node.child('rPr');
718
- if (rPr) {
719
- run.bold = rPr.attr('b') === '1';
720
- run.italic = rPr.attr('i') === '1';
721
- const u = rPr.attr('u');
722
- if (u !== '' && u !== 'none') run.underline = true;
723
- const s = rPr.attr('strike');
724
- if (s === 'sngStrike' || s === 'dblStrike') run.strike = true;
725
- const sz = Number.parseFloat(rPr.attr('sz'));
726
- if (Number.isFinite(sz) && sz > 0) run.size = szToFontSize(sz);
727
- run.color = fillColorOf(rPr, ctx);
728
- const lat = rPr.child('latin');
729
- if (lat) run.font = lat.attr('typeface');
730
- }
731
- para.runs.push(run);
732
- }
733
- }
734
- flush();
735
- }
736
- // 末尾全空段是 PowerPoint 默认空段落的产物,不带信息
737
- while (paras.length > 0 && paras[paras.length - 1].runs.length === 0) paras.pop();
738
- return paras;
739
- }
740
-
741
- function alignOf(ppr) {
742
- if (!ppr) return '';
743
- switch (ppr.attr('algn')) {
744
- case 'ctr': return 'center';
745
- case 'r': return 'right';
746
- case 'just': return 'justify';
747
- case 'l': return 'left';
748
- default: return '';
749
- }
750
- }
751
-
752
- function listOf(ppr) {
753
- if (!ppr) return '';
754
- if (ppr.child('buNone')) return '';
755
- const buChar = ppr.child('buChar');
756
- if (buChar && buChar.attr('char') !== '') return 'bullet';
757
- const buAuto = ppr.child('buAutoNum');
758
- if (buAuto) return 'number';
759
- return '';
760
- }
761
-
762
- function lineSpacingOf(ppr) {
763
- const pct = ppr?.find('lnSpc', 'spcPct');
764
- if (pct) {
765
- const v = Number.parseFloat(pct.attr('val'));
766
- if (Number.isFinite(v) && v > 0) return Math.max(0.6, Math.min(4, v / 100000));
767
- }
768
- return DEFAULT_LINE_SPACING;
769
- }
770
-
771
- /** 取首个有内容的 run 的格式作对象级默认值(run 级差异仍留在 HTML 里) */
772
- function objectTextStyle(paras, fallbackSize = 24) {
773
- let size = 0;
774
- let color = '';
775
- let font = '';
776
- let total = 0;
777
- let boldCount = 0;
778
- let italicCount = 0;
779
- let underlineCount = 0;
780
- let strikeCount = 0;
781
- for (const p of paras) {
782
- for (const r of p.runs) {
783
- if (r.text === '') continue;
784
- total += 1;
785
- if (size === 0 && r.size > 0) size = r.size;
786
- if (color === '' && r.color !== '') color = r.color;
787
- if (font === '' && r.font !== '') font = r.font;
788
- if (r.bold) boldCount += 1;
789
- if (r.italic) italicCount += 1;
790
- if (r.underline) underlineCount += 1;
791
- if (r.strike) strikeCount += 1;
792
- }
793
- }
794
- if (size <= 0) size = fallbackSize;
795
- // 对象级布尔只在「整框一致」时成立:混合格式必须留在 run 级 HTML 里,否则会把未加粗的 run 一起加粗
796
- return {
797
- size, color, font,
798
- bold: total > 0 && boldCount === total,
799
- italic: total > 0 && italicCount === total,
800
- underline: total > 0 && underlineCount === total,
801
- strike: total > 0 && strikeCount === total,
802
- };
803
- }
804
-
805
- function objectParaStyle(paras) {
806
- let align = '';
807
- let lineSpacing = DEFAULT_LINE_SPACING;
808
- let first = true;
809
- for (const p of paras) {
810
- if (align === '' && p.align !== '') align = p.align;
811
- if (first) lineSpacing = p.lineSpacing || DEFAULT_LINE_SPACING;
812
- first = false;
813
- }
814
- return { align, lineSpacing };
815
- }
816
-
817
- /** bodyPr 的垂直锚点 */
818
- function bodyProps(tx, ctx) {
819
- const body = tx?.child('bodyPr');
820
- if (!body) return { anchor: 'top' };
821
- const anchor = body.attr('anchor');
822
- if (anchor === 'ctr') return { anchor: 'middle' };
823
- if (anchor === 'b') return { anchor: 'bottom' };
824
- return { anchor: 'top' };
825
- }
826
-
827
- /* ---------- 备注 ---------- */
828
-
829
- /** 取关联备注页的正文:备注文字在 type="notes" 的那个占位形状里 */
830
- function notesText(pkg, rels, slidePart) {
831
- for (const rel of rels.values()) {
832
- if (rel.type !== REL_NOTES) continue;
833
- const raw = pkg.part(resolveTarget(slidePart, rel.target));
834
- if (!raw) continue;
835
- let tree;
836
- try {
837
- tree = parseNode(raw);
838
- } catch {
839
- continue;
840
- }
841
- const spTree = tree.find('cSld', 'spTree');
842
- if (!spTree) continue;
843
- for (const sp of spTree.children('sp')) {
844
- const ph = sp.find('nvSpPr', 'nvPr', 'ph');
845
- if (!ph || ph.attr('type') !== 'notes') continue;
846
- return parasPlainText(parseTxBody(sp.child('txBody'), { colors: {} }));
847
- }
848
- }
849
- return '';
850
- }
851
-
852
- /* ---------- 颜色 ---------- */
853
-
854
- /** 取填充色:既能接 spPr/tcPr/rPr/ln 这类容器,也能直接接 solidFill/gradFill 节点 */
855
- function fillColorOf(node, ctx) {
856
- if (!node) return '';
857
- if (node.name === 'solidFill') return fillNodeColor(node, ctx);
858
- if (node.name === 'gradFill') return gradientColor(node, ctx);
859
- const solid = node.child('solidFill');
860
- if (solid) return fillNodeColor(solid, ctx);
861
- const grad = node.child('gradFill');
862
- if (grad) return gradientColor(grad, ctx);
863
- return '';
864
- }
865
-
866
- function fillNodeColor(fill, ctx) {
867
- for (const child of fill.kids) {
868
- const hex = colorNodeToHex(child, ctx);
869
- if (hex) return hex;
870
- }
871
- return '';
872
- }
873
-
874
- function gradientColor(grad, ctx) {
875
- const stops = grad.find('gsLst', 'gs');
876
- if (!stops) return '';
877
- for (const child of stops.kids) {
878
- const hex = colorNodeToHex(child, ctx);
879
- if (hex) return hex;
880
- }
881
- return '';
882
- }
883
-
884
- /** 颜色元素(srgbClr / schemeClr / sysClr / prstClr)→ #rrggbb,并应用亮度/着色修饰 */
885
- function colorNodeToHex(node, ctx) {
886
- let hex = '';
887
- if (node.name === 'srgbClr') hex = normalizeColor(node.attr('val'));
888
- else if (node.name === 'schemeClr') hex = ctx.colors[node.attr('val')] || '';
889
- else if (node.name === 'sysClr') hex = normalizeColor(node.attr('lastClr'));
890
- else if (node.name === 'prstClr') hex = PRESET_COLORS[node.attr('val')] || '';
891
- if (!hex) return '';
892
- return applyColorMods(hex, node);
893
- }
894
-
895
- const PRESET_COLORS = {
896
- black: '#000000', white: '#ffffff', red: '#ff0000', green: '#008000', blue: '#0000ff',
897
- yellow: '#ffff00', gray: '#808080', grey: '#808080', orange: '#ffa500',
898
- };
899
-
900
- function applyColorMods(hex, node) {
901
- const pct = (name) => {
902
- const c = node.child(name);
903
- if (!c) return null;
904
- const v = Number.parseFloat(c.attr('val'));
905
- return Number.isFinite(v) ? v / 100000 : null;
906
- };
907
- let { r, g, b } = hexToRgb(hex);
908
- const tint = pct('tint');
909
- const shade = pct('shade');
910
- if (tint !== null) {
911
- r += (255 - r) * (1 - tint);
912
- g += (255 - g) * (1 - tint);
913
- b += (255 - b) * (1 - tint);
914
- }
915
- if (shade !== null) {
916
- r *= shade;
917
- g *= shade;
918
- b *= shade;
919
- }
920
- const lumMod = pct('lumMod');
921
- const lumOff = pct('lumOff');
922
- if (lumMod !== null || lumOff !== null) {
923
- let hsl = rgbToHsl(r, g, b);
924
- if (lumMod !== null) hsl.l *= lumMod;
925
- if (lumOff !== null) hsl.l += lumOff;
926
- hsl.l = Math.max(0, Math.min(1, hsl.l));
927
- ({ r, g, b } = hslToRgb(hsl.h, hsl.s, hsl.l));
928
- }
929
- return rgbToHex(r, g, b);
930
- }
931
-
932
- const hexToRgb = (hex) => {
933
- const v = String(hex).replace('#', '');
934
- const n = Number.parseInt(v.length === 3 ? v.split('').map((c) => c + c).join('') : v, 16);
935
- return Number.isFinite(n) ? { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 } : { r: 0, g: 0, b: 0 };
936
- };
937
- const rgbToHex = (r, g, b) => `#${[r, g, b].map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('')}`;
938
-
939
- function rgbToHsl(r, g, b) {
940
- r /= 255; g /= 255; b /= 255;
941
- const max = Math.max(r, g, b);
942
- const min = Math.min(r, g, b);
943
- const l = (max + min) / 2;
944
- if (max === min) return { h: 0, s: 0, l };
945
- const d = max - min;
946
- const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
947
- let h;
948
- if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
949
- else if (max === g) h = (b - r) / d + 2;
950
- else h = (r - g) / d + 4;
951
- return { h: h / 6, s, l };
952
- }
953
-
954
- function hslToRgb(h, s, l) {
955
- if (s === 0) return { r: l * 255, g: l * 255, b: l * 255 };
956
- const hue = (p, q, t) => {
957
- let x = t;
958
- if (x < 0) x += 1;
959
- if (x > 1) x -= 1;
960
- if (x < 1 / 6) return p + (q - p) * 6 * x;
961
- if (x < 1 / 2) return q;
962
- if (x < 2 / 3) return p + (q - p) * (2 / 3 - x) * 6;
963
- return p;
964
- };
965
- const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
966
- const p = 2 * l - q;
967
- return { r: hue(p, q, h + 1 / 3) * 255, g: hue(p, q, h) * 255, b: hue(p, q, h - 1 / 3) * 255 };
968
- }
969
-
970
- /* ---------- 小工具 ---------- */
971
-
972
- /** 取关系属性(r:id / r:embed);在 r: 命名空间里,只按本地名取会撞上同名的页码 id */
973
- function relAttr(n, local) {
974
- const v = n.attrNS(REL_NS, local);
975
- if (v !== '') return v;
976
- for (const a of n.attrs) {
977
- if (a.local === local && String(a.value).startsWith('rId')) return a.value;
978
- }
979
- return '';
980
- }
981
-
982
- /** 描边颜色/宽度/虚线/双端箭头(EMU → px;宽度缺失时取 fallback) */
983
- function parseStroke(ln, ctx, fallbackPx) {
984
- if (!ln) return { color: '', width: 0, dash: 'solid', arrowStart: false, arrowEnd: false };
985
- const dash = normalizeDash(ln.child('prstDash')?.attr('val'));
986
- const head = ln.child('headEnd');
987
- const tail = ln.child('tailEnd');
988
- const arrows = {
989
- arrowStart: !!head && head.attr('type') !== '' && head.attr('type') !== 'none',
990
- arrowEnd: !!tail && tail.attr('type') !== '' && tail.attr('type') !== 'none',
991
- };
992
- // 显式 noFill 是「无线条」:宽度也随之归零,否则回写会把无线条又画出来
993
- if (ln.child('noFill')) return { color: '', width: 0, dash, ...arrows };
994
- let width = 0;
995
- const w = attrInt64(ln, 'w');
996
- if (w > 0) width = w / EMU_PER_PX;
997
- if (width <= 0) width = fallbackPx;
998
- return { color: fillColorOf(ln, ctx), width, dash, ...arrows };
999
- }
1000
-
1001
- function normalizeDash(val) {
1002
- switch (val) {
1003
- case 'dash': case 'lgDash': case 'dot': case 'dashDot': return val;
1004
- case 'sysDash': return 'dash';
1005
- case 'sysDot': case 'sysDashDot': return 'dot';
1006
- default: return 'solid';
1007
- }
1008
- }
1009
-
1010
- function hasShadow(spPr) {
1011
- return !!spPr?.find('effectLst', 'outerShdw');
1012
- }
1013
-
1014
- function attrInt64(n, local) {
1015
- if (!n) return 0;
1016
- const v = Number.parseInt(n.attr(local), 10);
1017
- return Number.isFinite(v) ? v : 0;
1018
- }
1
+ // [文件] gbpptx·解析 —— .pptx 部件还原成 Presentation(文本/图片/图形/线条/表格 + 背景 + 备注 + 切换)
2
+ // [设计] 一律只按本地名匹配元素:同一演示里 p:/a:/r: 三套前缀混排,写死前缀会在别人的文件上整页解析失败。
3
+ // [设计] 占位符(placeholder)常常不在页内写 xfrm,几何要从版式/母版继承;组合形状(grpSp)摊平成页内元素。
4
+ // [坑] 页面尺寸按 sldSz 保留长宽比缩放到 960/540 基准,4:3 与自定义画幅不会被强行拉成 16:9。
5
+
6
+ import { EMU_PER_PX, REL_NS, emuToPx, encodeDataUrl, normalizeColor, openOpc, parseNode, resolveTarget } from 'gbooxml';
7
+ import { DEFAULT_THEME, PRST_TO_KIND, SLIDE_H, SLIDE_W, THEMES_HEX, isPptx, isThemeKey, szToFontSize } from './pptx.js';
8
+ import { contrastText, tableStyleColors } from './model.js';
9
+ import { PART_MASTER, PART_PRESENTATION, PART_THEME, REL_LAYOUT, REL_MASTER, REL_NOTES, THEME_NAME_PREFIX, slidePath } from './parts.js';
10
+ import { parasPlainText, parasToHTML } from './text.js';
11
+
12
+ const LINE_STROKE_W = 2;
13
+ const SHAPE_STROKE_W = 1;
14
+ const DEFAULT_LINE_SPACING = 1.0;
15
+
16
+ /**
17
+ * 把 .pptx 字节解析成快照(Presentation)
18
+ * @param {Uint8Array|ArrayBuffer} data
19
+ * @returns {Promise<object>} {version:2, theme, size, slides:[{id,bg,notes,hidden,transition,objects}], warnings}
20
+ */
21
+ export async function parsePptx(data) {
22
+ if (!isPptx(data)) throw new Error('不是有效的 pptx 文件');
23
+ let pkg;
24
+ try {
25
+ pkg = await openOpc(data);
26
+ } catch {
27
+ throw new Error('不是有效的 pptx 文件');
28
+ }
29
+ const raw = pkg.part(PART_PRESENTATION);
30
+ if (!raw) throw new Error('pptx 缺少 ppt/presentation.xml');
31
+ let pres;
32
+ try {
33
+ pres = parseNode(raw);
34
+ } catch (err) {
35
+ throw new Error(`无法解析 presentation.xml:${err.message || err}`);
36
+ }
37
+
38
+ const theme = themeKeyOf(pkg);
39
+ const themeHex = THEMES_HEX[theme] || THEMES_HEX[DEFAULT_THEME];
40
+ const colors = themeColorsOf(pkg, theme);
41
+ const { size, sx, sy } = canvasOf(pres);
42
+ const ctx = { size, sx, sy, colors, theme, themeText: `#${themeHex.text}`, themeAccent: `#${themeHex.accent}` };
43
+ const warnings = { groups: 0, charts: 0, media: 0, unknown: 0 };
44
+
45
+ const entries = slideEntries(pres, pkg);
46
+ if (entries.length === 0) throw new Error('pptx 里没有幻灯片');
47
+
48
+ const masterTree = readPartTree(pkg, masterPathOf(pkg));
49
+ const out = { version: 2, title: '', theme, size, slides: [], warnings };
50
+ entries.forEach((entry, i) => {
51
+ const rawSlide = pkg.part(entry.path);
52
+ if (!rawSlide) return;
53
+ let tree;
54
+ try {
55
+ tree = parseNode(rawSlide);
56
+ } catch {
57
+ return;
58
+ }
59
+ const rels = pkg.rels(entry.path);
60
+ const layoutTree = readPartTree(pkg, layoutPathOf(rels, entry.path));
61
+ const slide = parseSlide(tree, rels, pkg, entry.path, ctx, layoutTree, masterTree, warnings);
62
+ slide.id = `s-import${i + 1}`;
63
+ slide.hidden = entry.hidden;
64
+ slide.notes = notesText(pkg, rels, entry.path);
65
+ // 写出时页底色一律显式落 p:bg;回读时把「恰好等于本主题底色」的页判回「随主题」
66
+ if (isThemeKey(theme) && String(slide.bg).replace('#', '').toLowerCase() === themeHex.bg.toLowerCase()) {
67
+ slide.bg = '';
68
+ }
69
+ out.slides.push(slide);
70
+ });
71
+ if (out.slides.length === 0) throw new Error('pptx 里没有可解析的幻灯片');
72
+ return out;
73
+ }
74
+
75
+ /* ---------- 画幅 ---------- */
76
+
77
+ /** 源尺寸 → 以 960×540 为基准的等比画幅(宽屏取 960,纵向取 540) */
78
+ function canvasOf(pres) {
79
+ let srcW = SLIDE_W;
80
+ let srcH = SLIDE_H;
81
+ const sz = pres.child('sldSz');
82
+ if (sz) {
83
+ const cx = attrInt64(sz, 'cx');
84
+ const cy = attrInt64(sz, 'cy');
85
+ srcW = cx > 0 ? emuToPx(cx, 1) : srcW;
86
+ srcH = cy > 0 ? emuToPx(cy, 1) : srcH;
87
+ }
88
+ const ratio = srcW / srcH;
89
+ let w;
90
+ let h;
91
+ if (ratio >= SLIDE_W / SLIDE_H) {
92
+ w = SLIDE_W;
93
+ h = Math.max(120, Math.round(SLIDE_W / ratio));
94
+ } else {
95
+ h = SLIDE_H;
96
+ w = Math.max(120, Math.round(SLIDE_H * ratio));
97
+ }
98
+ return { size: { w, h }, sx: w / srcW, sy: h / srcH };
99
+ }
100
+
101
+ /* ---------- 部件路径 ---------- */
102
+
103
+ function readPartTree(pkg, path) {
104
+ if (!path) return null;
105
+ const raw = pkg.part(path);
106
+ if (!raw) return null;
107
+ try {
108
+ return parseNode(raw);
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+
114
+ function relPath(rels, fromPart, type) {
115
+ for (const rel of rels.values()) {
116
+ if (rel.type === type) return resolveTarget(fromPart, rel.target);
117
+ }
118
+ return '';
119
+ }
120
+
121
+ const masterPathOf = (pkg) => {
122
+ const presRels = pkg.rels(PART_PRESENTATION);
123
+ return relPath(presRels, PART_PRESENTATION, REL_MASTER) || PART_MASTER;
124
+ };
125
+
126
+ const layoutPathOf = (rels, slidePart) => relPath(rels, slidePart, REL_LAYOUT);
127
+
128
+ /* ---------- 页序 ---------- */
129
+
130
+ /** 页序来自 sldIdLst 的关系(文件名顺序不可靠);关系表缺失时退回按 slide1..N 连续探测 */
131
+ function slideEntries(pres, pkg) {
132
+ const presRels = pkg.rels(PART_PRESENTATION);
133
+ const out = [];
134
+ const lst = pres.child('sldIdLst');
135
+ if (lst) {
136
+ for (const sid of lst.children('sldId')) {
137
+ const rel = presRels.get(relAttr(sid, 'id'));
138
+ if (rel) out.push({ path: resolveTarget(PART_PRESENTATION, rel.target), hidden: sid.attr('show') === '0' });
139
+ }
140
+ }
141
+ if (out.length > 0) return out;
142
+ for (let i = 1; ; i += 1) {
143
+ const p = slidePath(i);
144
+ if (!pkg.has(p)) break;
145
+ out.push({ path: p, hidden: false });
146
+ }
147
+ return out;
148
+ }
149
+
150
+ /* ---------- 主题色 ---------- */
151
+
152
+ const THEME_SCHEME_KEYS = ['dk1', 'lt1', 'dk2', 'lt2', 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6', 'hlink', 'folHlink'];
153
+
154
+ function themeKeyOf(pkg) {
155
+ const raw = pkg.part(PART_THEME);
156
+ if (!raw) return DEFAULT_THEME;
157
+ let tree;
158
+ try {
159
+ tree = parseNode(raw);
160
+ } catch {
161
+ return DEFAULT_THEME;
162
+ }
163
+ const key = tree.attr('name').replace(new RegExp(`^${THEME_NAME_PREFIX}`), '');
164
+ return isThemeKey(key) ? key : DEFAULT_THEME;
165
+ }
166
+
167
+ /** 主题部件里的实际色值(外部文件的 schemeClr 靠它落成具体颜色) */
168
+ function themeColorsOf(pkg, themeKey) {
169
+ const t = THEMES_HEX[themeKey] || THEMES_HEX[DEFAULT_THEME];
170
+ const out = {
171
+ tx1: `#${t.text}`, bg1: `#${t.bg}`, tx2: `#${t.text}`, bg2: `#${t.bg}`,
172
+ dk1: `#${t.text}`, lt1: `#${t.bg}`, dk2: `#${t.text}`, lt2: `#${t.bg}`,
173
+ hlink: '#1d6fd4', folHlink: '#8e44ad',
174
+ };
175
+ for (let i = 1; i <= 6; i += 1) out[`accent${i}`] = `#${t.accent}`;
176
+ const tree = readPartTree(pkg, PART_THEME);
177
+ const scheme = tree?.find('themeElements', 'clrScheme');
178
+ if (!scheme) return out;
179
+ for (const key of THEME_SCHEME_KEYS) {
180
+ const node = scheme.child(key);
181
+ if (!node || node.kids.length === 0) continue;
182
+ const hex = colorNodeToHex(node.kids[0], { colors: out });
183
+ if (hex) out[key] = hex;
184
+ }
185
+ out.tx1 = out.dk1;
186
+ out.tx2 = out.dk2;
187
+ out.bg1 = out.lt1;
188
+ out.bg2 = out.lt2;
189
+ return out;
190
+ }
191
+
192
+ /* ---------- 页面 ---------- */
193
+
194
+ function parseSlide(tree, rels, pkg, slidePart, ctx, layoutTree, masterTree, warnings) {
195
+ const slide = { id: '', bg: '', notes: '', hidden: false, transition: parseTransition(tree), objects: [] };
196
+ // 页底色:页内 → 版式 → 母版 → 主题 bg1(外部幻灯片常不写 p:bg,只靠母版/主题)
197
+ slide.bg = backgroundColorOf(tree, ctx)
198
+ || backgroundColorOf(layoutTree, ctx)
199
+ || backgroundColorOf(masterTree, ctx)
200
+ || ctx.colors.bg1
201
+ || '';
202
+ const spTree = tree.find('cSld', 'spTree');
203
+ if (!spTree) return slide;
204
+ let z = 1;
205
+ const push = (obj) => {
206
+ if (!obj) return;
207
+ obj.id = `o-import${z}`;
208
+ obj.z = z;
209
+ z += 1;
210
+ slide.objects.push(obj);
211
+ };
212
+ const structural = new Set(['nvGrpSpPr', 'grpSpPr', 'extLst']);
213
+ walkSpTree(spTree, null, (node, transform) => {
214
+ const kw = { ctx, rels, pkg, slidePart, layoutTree, masterTree, transform, warnings };
215
+ switch (node.name) {
216
+ case 'sp': push(parseSp(node, kw)); break;
217
+ case 'cxnSp': push(parseCxnSp(node, kw)); break;
218
+ case 'pic': push(parsePic(node, kw)); break;
219
+ case 'graphicFrame': push(parseGraphicFrame(node, kw)); break;
220
+ default: if (!structural.has(node.name)) warnings.unknown += 1; break;
221
+ }
222
+ }, warnings);
223
+ return slide;
224
+ }
225
+
226
+ /** 遍历 spTree,遇到 grpSp 就合成坐标变换后摊平(不保留组合语义,但内容不丢) */
227
+ function walkSpTree(parent, transform, emit, warnings) {
228
+ for (const node of parent.kids) {
229
+ if (node.name === 'grpSp') {
230
+ warnings.groups += 1;
231
+ const local = groupTransform(node.find('grpSpPr', 'xfrm'));
232
+ walkSpTree(node, composeTransform(transform, local), emit, warnings);
233
+ } else {
234
+ emit(node, transform);
235
+ }
236
+ }
237
+ }
238
+
239
+ function groupTransform(xf) {
240
+ if (!xf) return null;
241
+ const off = xf.child('off');
242
+ const ext = xf.child('ext');
243
+ const chOff = xf.child('chOff');
244
+ const chExt = xf.child('chExt');
245
+ if (!off || !ext || !chOff || !chExt) return null;
246
+ const ex = attrInt64(ext, 'cx');
247
+ const ey = attrInt64(ext, 'cy');
248
+ const cx = attrInt64(chExt, 'cx');
249
+ const cy = attrInt64(chExt, 'cy');
250
+ const kx = cx > 0 ? ex / cx : 1;
251
+ const ky = cy > 0 ? ey / cy : 1;
252
+ return {
253
+ kx, ky,
254
+ tx: attrInt64(off, 'x') - attrInt64(chOff, 'x') * kx,
255
+ ty: attrInt64(off, 'y') - attrInt64(chOff, 'y') * ky,
256
+ };
257
+ }
258
+
259
+ function composeTransform(parent, local) {
260
+ if (!local) return parent;
261
+ if (!parent) return local;
262
+ return {
263
+ kx: local.kx * parent.kx,
264
+ ky: local.ky * parent.ky,
265
+ tx: local.tx * parent.kx + parent.tx,
266
+ ty: local.ty * parent.ky + parent.ty,
267
+ };
268
+ }
269
+
270
+ /** 位置 / 尺寸 / 旋转 / 翻转(EMU → 逻辑像素;组合变换先生效) */
271
+ function parseXfrm(xf, ctx, transform) {
272
+ if (!xf) return null;
273
+ const off = xf.child('off');
274
+ const ext = xf.child('ext');
275
+ if (!off || !ext) return null;
276
+ let x = attrInt64(off, 'x');
277
+ let y = attrInt64(off, 'y');
278
+ let w = attrInt64(ext, 'cx');
279
+ let h = attrInt64(ext, 'cy');
280
+ if (transform) {
281
+ x = x * transform.kx + transform.tx;
282
+ y = y * transform.ky + transform.ty;
283
+ w *= transform.kx;
284
+ h *= transform.ky;
285
+ }
286
+ return {
287
+ x: emuToPx(x, 1) * ctx.sx,
288
+ y: emuToPx(y, 1) * ctx.sy,
289
+ w: emuToPx(w, 1) * ctx.sx,
290
+ h: emuToPx(h, 1) * ctx.sy,
291
+ rot: attrInt64(xf, 'rot') / 60000,
292
+ flipH: xf.attr('flipH') === '1',
293
+ flipV: xf.attr('flipV') === '1',
294
+ };
295
+ }
296
+
297
+ /** 占位符的 ph 元素(sp/pic/graphicFrame 通用) */
298
+ function placeholderOf(node) {
299
+ const paths = [['nvSpPr', 'nvPr', 'ph'], ['nvPicPr', 'nvPr', 'ph'], ['nvGraphicFramePr', 'nvPr', 'ph'], ['nvCxnSpPr', 'nvPr', 'ph']];
300
+ for (const p of paths) {
301
+ const ph = node.find(...p);
302
+ if (ph) return ph;
303
+ }
304
+ return null;
305
+ }
306
+
307
+ /** 从版式/母版找同名占位符的 xfrm(idx 优先,其次 type) */
308
+ function placeholderXfrm(tree, ph) {
309
+ if (!tree || !ph) return null;
310
+ const wantIdx = ph.attr('idx');
311
+ const wantType = ph.attr('type');
312
+ const candidates = [];
313
+ const spTree = tree.find('cSld', 'spTree');
314
+ if (!spTree) return null;
315
+ for (const sp of spTree.children('sp')) {
316
+ const p = sp.find('nvSpPr', 'nvPr', 'ph');
317
+ if (!p) continue;
318
+ const xf = sp.find('spPr', 'xfrm');
319
+ if (!xf) continue;
320
+ candidates.push({ ph: p, xf });
321
+ }
322
+ if (candidates.length === 0) return null;
323
+ if (wantIdx !== '') {
324
+ const hit = candidates.find((c) => c.ph.attr('idx') === wantIdx);
325
+ if (hit) return hit.xf;
326
+ }
327
+ if (wantType !== '') {
328
+ const hit = candidates.find((c) => c.ph.attr('type') === wantType);
329
+ if (hit) return hit.xf;
330
+ }
331
+ const fallback = candidates.find((c) => c.ph.attr('idx') === '' && c.ph.attr('type') === '');
332
+ return fallback ? fallback.xf : candidates[0].xf;
333
+ }
334
+
335
+ /** 占位符几何与默认字号(版式/母版都没有时兜底) */
336
+ function placeholderLayout(node, layoutTree, masterTree, ctx) {
337
+ const ph = placeholderOf(node);
338
+ if (!ph) return null;
339
+ const type = ph.attr('type');
340
+ const xf = placeholderXfrm(layoutTree, ph) || placeholderXfrm(masterTree, ph);
341
+ const parsed = xf ? parseXfrm(xf, ctx, null) : null;
342
+ return { type, xf: parsed, size: placeholderFontSize(type) };
343
+ }
344
+
345
+ function placeholderFontSize(type) {
346
+ switch (type) {
347
+ case 'title': case 'ctrTitle': return 40;
348
+ case 'subTitle': return 24;
349
+ case 'body': case 'obj': return 20;
350
+ default: return 24;
351
+ }
352
+ }
353
+
354
+ function fallbackPlaceholder(type, ctx) {
355
+ const { w, h } = ctx.size;
356
+ const kind = type || 'obj';
357
+ if (kind === 'title' || kind === 'ctrTitle') {
358
+ return { x: w * 0.08, y: h * 0.12, w: w * 0.84, h: h * 0.16 };
359
+ }
360
+ if (kind === 'subTitle') return { x: w * 0.18, y: h * 0.34, w: w * 0.64, h: h * 0.12 };
361
+ if (kind === 'ftr' || kind === 'dt' || kind === 'sldNum') return { x: w * 0.06, y: h * 0.9, w: w * 0.88, h: h * 0.07 };
362
+ return { x: w * 0.08, y: h * 0.3, w: w * 0.84, h: h * 0.55 };
363
+ }
364
+
365
+ /** 页/版式/母版的背景色:bgPr 的 solidFill/gradFill,或 bgRef 引用的主题色 */
366
+ function backgroundColorOf(tree, ctx) {
367
+ if (!tree) return '';
368
+ const bgPr = tree.find('cSld', 'bg', 'bgPr');
369
+ if (bgPr) {
370
+ const color = fillColorOf(bgPr, ctx);
371
+ if (color) return color;
372
+ }
373
+ const ref = tree.find('cSld', 'bg', 'bgRef');
374
+ if (ref) {
375
+ for (const child of ref.kids) {
376
+ const color = colorNodeToHex(child, ctx);
377
+ if (color) return color;
378
+ }
379
+ return ctx.colors.bg1 || '';
380
+ }
381
+ return '';
382
+ }
383
+
384
+ /* ---------- 形状 ---------- */
385
+
386
+ /** 文本框或预设几何图形:txBox / 占位符优先,其余按填充与预设形状判别 */
387
+ function parseSp(node, kw) {
388
+ const { ctx, layoutTree, masterTree, transform } = kw;
389
+ const spPr = node.child('spPr');
390
+ if (!spPr) return null;
391
+ const holder = placeholderLayout(node, layoutTree, masterTree, ctx);
392
+ let xf = parseXfrm(spPr.child('xfrm'), ctx, transform);
393
+ if (!xf && holder?.xf) xf = holder.xf;
394
+ if (!xf && holder) {
395
+ const fb = fallbackPlaceholder(holder.type, ctx);
396
+ xf = { ...fb, rot: 0, flipH: false, flipV: false };
397
+ }
398
+ if (!xf || xf.w <= 0 || xf.h <= 0) return null;
399
+
400
+ const txBody = node.child('txBody');
401
+ const paras = parseTxBody(txBody, ctx);
402
+ const cNv = node.find('nvSpPr', 'cNvSpPr');
403
+ const txBox = cNv?.attr('txBox') === '1';
404
+
405
+ const prstNode = spPr.child('prstGeom');
406
+ const prst = prstNode ? prstNode.attr('prst') : '';
407
+ const kind = PRST_TO_KIND[prst] || '';
408
+ const styleFill = shapeStyleFill(node, ctx);
409
+ let fill = fillColorOf(spPr, ctx);
410
+ if (fill === '' && styleFill) fill = styleFill;
411
+ const stroke = parseStroke(spPr.child('ln'), ctx, SHAPE_STROKE_W);
412
+ const shadow = hasShadow(spPr);
413
+ const body = bodyProps(txBody, ctx);
414
+ const textStyle = objectTextStyle(paras, holder?.size || 24);
415
+
416
+ // 只有「有视觉的几何」才算形状:矩形 + 无填充无色 + 有文字,是文本框而不是隐形形状
417
+ const visual = fill !== '' || stroke.color !== '' || shadow || (prst !== '' && prst !== 'rect');
418
+ const asText = txBox || (holder && paras.length > 0) || (!visual && paras.length > 0);
419
+ if (asText) {
420
+ if (paras.length === 0 && !txBox) return null;
421
+ const paraStyle = objectParaStyle(paras);
422
+ return {
423
+ id: '', type: 'text', x: xf.x, y: xf.y, w: xf.w, h: xf.h, rot: xf.rot, z: 0,
424
+ props: {
425
+ html: parasToHTML(paras),
426
+ font: textStyle.font,
427
+ fontSize: textStyle.size,
428
+ color: textStyle.color,
429
+ align: paraStyle.align,
430
+ bold: textStyle.bold,
431
+ italic: textStyle.italic,
432
+ underline: textStyle.underline,
433
+ strike: textStyle.strike,
434
+ anchor: body.anchor,
435
+ lineSpacing: paraStyle.lineSpacing,
436
+ fill,
437
+ stroke: stroke.color,
438
+ strokeW: stroke.width,
439
+ },
440
+ };
441
+ }
442
+ if (!visual) return null;
443
+
444
+ return {
445
+ id: '', type: 'shape', x: xf.x, y: xf.y, w: xf.w, h: xf.h, rot: xf.rot, z: 0,
446
+ props: {
447
+ kind: kind || 'rect',
448
+ fill: fill || '',
449
+ stroke: stroke.color,
450
+ strokeW: stroke.width,
451
+ dash: stroke.dash,
452
+ shadow,
453
+ text: parasPlainText(paras),
454
+ textColor: textStyle.color || (fill ? contrastText(fill) : ctx.themeText),
455
+ font: textStyle.font,
456
+ fontSize: textStyle.size,
457
+ bold: textStyle.bold,
458
+ italic: textStyle.italic,
459
+ underline: textStyle.underline,
460
+ strike: textStyle.strike,
461
+ align: objectParaStyle(paras).align || 'left',
462
+ anchor: body.anchor,
463
+ lineSpacing: objectParaStyle(paras).lineSpacing,
464
+ },
465
+ };
466
+ }
467
+
468
+ /** p:style 里的 fillRef(外部形状没有显式填充时靠它拿到主题强调色) */
469
+ function shapeStyleFill(node, ctx) {
470
+ const style = node.child('style');
471
+ if (!style) return '';
472
+ const ref = style.child('fillRef');
473
+ if (!ref) return '';
474
+ const idx = Number.parseInt(ref.attr('idx'), 10);
475
+ if (!(idx > 0)) return '';
476
+ for (const child of ref.kids) {
477
+ const hex = colorNodeToHex(child, ctx);
478
+ if (hex) return hex;
479
+ }
480
+ return ctx.colors.accent1 || '';
481
+ }
482
+
483
+ /** 直线连接符:编辑器存起点 + 向量,故用翻转还原方向 */
484
+ function parseCxnSp(node, kw) {
485
+ const { ctx, transform } = kw;
486
+ const spPr = node.child('spPr');
487
+ if (!spPr) return null;
488
+ const xf = parseXfrm(spPr.child('xfrm'), ctx, transform);
489
+ if (!xf) return null;
490
+ const stroke = parseStroke(spPr.child('ln'), ctx, LINE_STROKE_W);
491
+ let { x, y, w, h } = xf;
492
+ if (xf.flipH) { x += w; w = -w; }
493
+ if (xf.flipV) { y += h; h = -h; }
494
+ return {
495
+ id: '', type: 'line', x, y, w, h, rot: 0, z: 0,
496
+ props: {
497
+ stroke: stroke.color || ctx.themeText,
498
+ strokeW: stroke.width,
499
+ dash: stroke.dash,
500
+ arrowStart: stroke.arrowStart,
501
+ arrowEnd: stroke.arrowEnd,
502
+ },
503
+ };
504
+ }
505
+
506
+ function parsePic(node, kw) {
507
+ const { rels, pkg, slidePart, ctx, transform, warnings } = kw;
508
+ const spPr = node.child('spPr');
509
+ if (!spPr) return null;
510
+ const xf = parseXfrm(spPr.child('xfrm'), ctx, transform);
511
+ if (!xf || xf.w <= 0 || xf.h <= 0) return null;
512
+ if (node.find('nvPicPr', 'nvPr', 'videoFile') || node.find('nvPicPr', 'nvPr', 'audioFile')) warnings.media += 1;
513
+ const blip = node.find('blipFill', 'blip');
514
+ if (!blip) return null;
515
+ const rid = relAttr(blip, 'embed') || relAttr(blip, 'link');
516
+ const rel = rels.get(rid);
517
+ if (!rel) return null;
518
+ const raw = pkg.part(resolveTarget(slidePart, rel.target));
519
+ if (!raw) return null;
520
+ const ext = String(rel.target).split('.').pop().toLowerCase();
521
+ const cropNode = node.find('blipFill', 'srcRect');
522
+ const crop = {
523
+ l: cropNode ? Math.round(attrInt64(cropNode, 'l') / 1000) : 0,
524
+ t: cropNode ? Math.round(attrInt64(cropNode, 't') / 1000) : 0,
525
+ r: cropNode ? Math.round(attrInt64(cropNode, 'r') / 1000) : 0,
526
+ b: cropNode ? Math.round(attrInt64(cropNode, 'b') / 1000) : 0,
527
+ };
528
+ const cNv = node.find('nvPicPr', 'cNvPr');
529
+ return {
530
+ id: '', type: 'image', x: xf.x, y: xf.y, w: xf.w, h: xf.h, rot: xf.rot, z: 0,
531
+ props: {
532
+ src: encodeDataUrl(raw, ext),
533
+ alt: cNv ? cNv.attr('descr') : '',
534
+ crop,
535
+ shadow: hasShadow(spPr),
536
+ },
537
+ };
538
+ }
539
+
540
+ function parseGraphicFrame(node, kw) {
541
+ const { ctx, transform, warnings } = kw;
542
+ const xf = parseXfrm(node.child('xfrm'), ctx, transform);
543
+ if (!xf || xf.w <= 0 || xf.h <= 0) return null;
544
+ const tbl = node.find('graphic', 'graphicData', 'tbl');
545
+ if (!tbl) {
546
+ if (node.find('graphic', 'graphicData', 'chart')) warnings.charts += 1;
547
+ else warnings.unknown += 1;
548
+ return null;
549
+ }
550
+ const tp = tbl.child('tblPr');
551
+ const headerRow = tp ? tp.attr('firstRow') === '1' : false;
552
+ const bandedRows = tp ? tp.attr('bandRow') === '1' : false;
553
+ const body = parseTableBody(tbl, ctx, headerRow);
554
+ if (body.rows.length === 0) return null;
555
+ const style = inferTableStyle(tbl, body, ctx, headerRow, bandedRows);
556
+ return {
557
+ id: '', type: 'table', x: xf.x, y: xf.y, w: xf.w, h: xf.h, rot: 0, z: 0,
558
+ props: {
559
+ rows: body.rows,
560
+ headerRow,
561
+ bandedRows,
562
+ tableStyle: style,
563
+ font: body.font,
564
+ fontSize: body.size,
565
+ color: body.color,
566
+ colW: tableColPercents(tbl),
567
+ rowH: tableRowPercents(tbl),
568
+ },
569
+ };
570
+ }
571
+
572
+ /** 表格正文行 + 首个有效 run 的字号/颜色/字体(正文样式优先取非表头行,避免把表头白字当默认色) */
573
+ function parseTableBody(tbl, ctx, headerRow) {
574
+ const rows = [];
575
+ const styles = [];
576
+ for (const tr of tbl.children('tr')) {
577
+ const row = [];
578
+ const rowStyles = [];
579
+ for (const tc of tr.children('tc')) {
580
+ const paras = parseTxBody(tc.child('txBody'), ctx);
581
+ row.push(parasPlainText(paras));
582
+ rowStyles.push(objectTextStyle(paras, 0));
583
+ }
584
+ if (row.length > 0) {
585
+ rows.push(row);
586
+ styles.push(rowStyles);
587
+ }
588
+ }
589
+ const pick = (key) => {
590
+ const order = headerRow ? [...styles.keys()].slice(1).concat([0]) : [...styles.keys()];
591
+ for (const ri of order) {
592
+ for (const s of styles[ri] || []) {
593
+ if (key === 'size') { if (s.size > 0) return s.size; }
594
+ else if (s[key] !== '') return s[key];
595
+ }
596
+ }
597
+ return '';
598
+ };
599
+ return { rows, size: pick('size') || 16, color: pick('color'), font: pick('font') };
600
+ }
601
+
602
+ /** 列宽百分比(tblGrid 的 gridCol 比例) */
603
+ function tableColPercents(tbl) {
604
+ const grid = tbl.child('tblGrid');
605
+ if (!grid) return [];
606
+ const widths = [];
607
+ let sum = 0;
608
+ for (const gc of grid.children('gridCol')) {
609
+ const v = Number.parseFloat(gc.attr('w'));
610
+ if (!Number.isFinite(v) || v <= 0) continue;
611
+ widths.push(v);
612
+ sum += v;
613
+ }
614
+ if (widths.length < 2 || sum <= 0) return [];
615
+ return widths.map((v) => (v / sum) * 100);
616
+ }
617
+
618
+ /** 行高百分比(tr@h;缺失时返回空表,让渲染端等分) */
619
+ function tableRowPercents(tbl) {
620
+ const heights = [];
621
+ let sum = 0;
622
+ for (const tr of tbl.children('tr')) {
623
+ const v = Number.parseFloat(tr.attr('h'));
624
+ if (!Number.isFinite(v) || v <= 0) return [];
625
+ heights.push(v);
626
+ sum += v;
627
+ }
628
+ if (heights.length < 2 || sum <= 0) return [];
629
+ return heights.map((v) => (v / sum) * 100);
630
+ }
631
+
632
+ /** 从表头/镶边填充反推表格样式(本包写出的文件能原样还原) */
633
+ function inferTableStyle(tbl, body, ctx, headerRow, bandedRows) {
634
+ const head = headerRow ? cellFill(tbl, 0, 0, ctx) : '';
635
+ if (headerRow) {
636
+ if (!head) return 'plain';
637
+ if (sameColor(head, ctx.themeAccent)) {
638
+ for (let ri = 1; ri < (body.rows || []).length; ri += 1) {
639
+ const band = cellFill(tbl, ri, 0, ctx);
640
+ if (band) return nearestBandStyle(band, ctx);
641
+ }
642
+ return 'header';
643
+ }
644
+ return 'plain';
645
+ }
646
+ // 没有表头行时,扫描所有行找镶边填充
647
+ for (let ri = 0; ri < (body.rows || []).length; ri += 1) {
648
+ const fill = cellFill(tbl, ri, 0, ctx);
649
+ if (fill) return nearestBandStyle(fill, ctx);
650
+ }
651
+ return 'plain';
652
+ }
653
+
654
+ /** 深色主题下「镶边」与「深色」都可能偏暗,按与主题推导色的距离判定而不是亮度 */
655
+ function nearestBandStyle(fill, ctx) {
656
+ const banded = tableStyleColors('banded', ctx.theme).bandFill;
657
+ const dark = tableStyleColors('dark', ctx.theme).bandFill;
658
+ return colorDistance(fill, banded) <= colorDistance(fill, dark) ? 'banded' : 'dark';
659
+ }
660
+
661
+ function colorDistance(a, b) {
662
+ const x = hexToRgb(a);
663
+ const y = hexToRgb(b);
664
+ return Math.abs(x.r - y.r) + Math.abs(x.g - y.g) + Math.abs(x.b - y.b);
665
+ }
666
+
667
+ function cellFill(tbl, rowIndex, colIndex, ctx) {
668
+ const tr = tbl.children('tr')[rowIndex];
669
+ if (!tr) return '';
670
+ const tc = tr.children('tc')[colIndex];
671
+ if (!tc) return '';
672
+ return fillColorOf(tc.child('tcPr'), ctx);
673
+ }
674
+
675
+ const sameColor = (a, b) => String(a).toLowerCase() === String(b).toLowerCase();
676
+ /* ---------- 切换 ---------- */
677
+
678
+ function parseTransition(tree) {
679
+ const node = tree.child('transition');
680
+ if (!node) return { type: 'none', dir: 'l', speed: 'med' };
681
+ const speed = ['slow', 'med', 'fast'].includes(node.attr('spd')) ? node.attr('spd') : 'med';
682
+ for (const child of node.kids) {
683
+ if (child.name === 'fade') return { type: 'fade', dir: 'l', speed };
684
+ if (child.name === 'push') return { type: 'push', dir: child.attr('dir') || 'l', speed };
685
+ if (child.name === 'wipe') return { type: 'wipe', dir: child.attr('dir') || 'l', speed };
686
+ if (child.name === 'cover') return { type: 'cover', dir: child.attr('dir') || 'l', speed };
687
+ if (child.name === 'split') return { type: 'split', dir: 'l', speed };
688
+ if (child.name === 'zoom') return { type: 'zoom', dir: 'l', speed };
689
+ }
690
+ return { type: 'none', dir: 'l', speed: 'med' };
691
+ }
692
+
693
+ /* ---------- 文本 ---------- */
694
+
695
+ /** txBody → 段落序列(<a:br> 视作换行,即另起一段;保留项目符号与行距) */
696
+ function parseTxBody(tx, ctx) {
697
+ if (!tx) return [];
698
+ let paras = [];
699
+ for (const p of tx.children('p')) {
700
+ const ppr = p.child('pPr');
701
+ const align = alignOf(ppr);
702
+ const list = listOf(ppr);
703
+ const level = ppr ? Math.max(0, Math.min(8, Number.parseInt(ppr.attr('lvl'), 10) || 0)) : 0;
704
+ const lineSpacing = lineSpacingOf(ppr);
705
+ let para = { align, list, level, lineSpacing, runs: [] };
706
+ const flush = () => {
707
+ paras.push(para);
708
+ para = { align, list, level, lineSpacing, runs: [] };
709
+ };
710
+ for (const node of p.kids) {
711
+ if (node.name === 'br') {
712
+ flush();
713
+ } else if (node.name === 'r' || node.name === 'fld') {
714
+ const t = node.child('t');
715
+ if (!t || t.text === '') continue;
716
+ const run = { text: t.text, bold: false, italic: false, underline: false, strike: false, color: '', font: '', size: 0 };
717
+ const rPr = node.child('rPr');
718
+ if (rPr) {
719
+ run.bold = rPr.attr('b') === '1';
720
+ run.italic = rPr.attr('i') === '1';
721
+ const u = rPr.attr('u');
722
+ if (u !== '' && u !== 'none') run.underline = true;
723
+ const s = rPr.attr('strike');
724
+ if (s === 'sngStrike' || s === 'dblStrike') run.strike = true;
725
+ const sz = Number.parseFloat(rPr.attr('sz'));
726
+ if (Number.isFinite(sz) && sz > 0) run.size = szToFontSize(sz);
727
+ run.color = fillColorOf(rPr, ctx);
728
+ const lat = rPr.child('latin');
729
+ if (lat) run.font = lat.attr('typeface');
730
+ }
731
+ para.runs.push(run);
732
+ }
733
+ }
734
+ flush();
735
+ }
736
+ // 末尾全空段是 PowerPoint 默认空段落的产物,不带信息
737
+ while (paras.length > 0 && paras[paras.length - 1].runs.length === 0) paras.pop();
738
+ return paras;
739
+ }
740
+
741
+ function alignOf(ppr) {
742
+ if (!ppr) return '';
743
+ switch (ppr.attr('algn')) {
744
+ case 'ctr': return 'center';
745
+ case 'r': return 'right';
746
+ case 'just': return 'justify';
747
+ case 'l': return 'left';
748
+ default: return '';
749
+ }
750
+ }
751
+
752
+ function listOf(ppr) {
753
+ if (!ppr) return '';
754
+ if (ppr.child('buNone')) return '';
755
+ const buChar = ppr.child('buChar');
756
+ if (buChar && buChar.attr('char') !== '') return 'bullet';
757
+ const buAuto = ppr.child('buAutoNum');
758
+ if (buAuto) return 'number';
759
+ return '';
760
+ }
761
+
762
+ function lineSpacingOf(ppr) {
763
+ const pct = ppr?.find('lnSpc', 'spcPct');
764
+ if (pct) {
765
+ const v = Number.parseFloat(pct.attr('val'));
766
+ if (Number.isFinite(v) && v > 0) return Math.max(0.6, Math.min(4, v / 100000));
767
+ }
768
+ return DEFAULT_LINE_SPACING;
769
+ }
770
+
771
+ /** 取首个有内容的 run 的格式作对象级默认值(run 级差异仍留在 HTML 里) */
772
+ function objectTextStyle(paras, fallbackSize = 24) {
773
+ let size = 0;
774
+ let color = '';
775
+ let font = '';
776
+ let total = 0;
777
+ let boldCount = 0;
778
+ let italicCount = 0;
779
+ let underlineCount = 0;
780
+ let strikeCount = 0;
781
+ for (const p of paras) {
782
+ for (const r of p.runs) {
783
+ if (r.text === '') continue;
784
+ total += 1;
785
+ if (size === 0 && r.size > 0) size = r.size;
786
+ if (color === '' && r.color !== '') color = r.color;
787
+ if (font === '' && r.font !== '') font = r.font;
788
+ if (r.bold) boldCount += 1;
789
+ if (r.italic) italicCount += 1;
790
+ if (r.underline) underlineCount += 1;
791
+ if (r.strike) strikeCount += 1;
792
+ }
793
+ }
794
+ if (size <= 0) size = fallbackSize;
795
+ // 对象级布尔只在「整框一致」时成立:混合格式必须留在 run 级 HTML 里,否则会把未加粗的 run 一起加粗
796
+ return {
797
+ size, color, font,
798
+ bold: total > 0 && boldCount === total,
799
+ italic: total > 0 && italicCount === total,
800
+ underline: total > 0 && underlineCount === total,
801
+ strike: total > 0 && strikeCount === total,
802
+ };
803
+ }
804
+
805
+ function objectParaStyle(paras) {
806
+ let align = '';
807
+ let lineSpacing = DEFAULT_LINE_SPACING;
808
+ let first = true;
809
+ for (const p of paras) {
810
+ if (align === '' && p.align !== '') align = p.align;
811
+ if (first) lineSpacing = p.lineSpacing || DEFAULT_LINE_SPACING;
812
+ first = false;
813
+ }
814
+ return { align, lineSpacing };
815
+ }
816
+
817
+ /** bodyPr 的垂直锚点 */
818
+ function bodyProps(tx, ctx) {
819
+ const body = tx?.child('bodyPr');
820
+ if (!body) return { anchor: 'top' };
821
+ const anchor = body.attr('anchor');
822
+ if (anchor === 'ctr') return { anchor: 'middle' };
823
+ if (anchor === 'b') return { anchor: 'bottom' };
824
+ return { anchor: 'top' };
825
+ }
826
+
827
+ /* ---------- 备注 ---------- */
828
+
829
+ /** 取关联备注页的正文:备注文字在 type="notes" 的那个占位形状里 */
830
+ function notesText(pkg, rels, slidePart) {
831
+ for (const rel of rels.values()) {
832
+ if (rel.type !== REL_NOTES) continue;
833
+ const raw = pkg.part(resolveTarget(slidePart, rel.target));
834
+ if (!raw) continue;
835
+ let tree;
836
+ try {
837
+ tree = parseNode(raw);
838
+ } catch {
839
+ continue;
840
+ }
841
+ const spTree = tree.find('cSld', 'spTree');
842
+ if (!spTree) continue;
843
+ for (const sp of spTree.children('sp')) {
844
+ const ph = sp.find('nvSpPr', 'nvPr', 'ph');
845
+ if (!ph || ph.attr('type') !== 'notes') continue;
846
+ return parasPlainText(parseTxBody(sp.child('txBody'), { colors: {} }));
847
+ }
848
+ }
849
+ return '';
850
+ }
851
+
852
+ /* ---------- 颜色 ---------- */
853
+
854
+ /** 取填充色:既能接 spPr/tcPr/rPr/ln 这类容器,也能直接接 solidFill/gradFill 节点 */
855
+ function fillColorOf(node, ctx) {
856
+ if (!node) return '';
857
+ if (node.name === 'solidFill') return fillNodeColor(node, ctx);
858
+ if (node.name === 'gradFill') return gradientColor(node, ctx);
859
+ const solid = node.child('solidFill');
860
+ if (solid) return fillNodeColor(solid, ctx);
861
+ const grad = node.child('gradFill');
862
+ if (grad) return gradientColor(grad, ctx);
863
+ return '';
864
+ }
865
+
866
+ function fillNodeColor(fill, ctx) {
867
+ for (const child of fill.kids) {
868
+ const hex = colorNodeToHex(child, ctx);
869
+ if (hex) return hex;
870
+ }
871
+ return '';
872
+ }
873
+
874
+ function gradientColor(grad, ctx) {
875
+ const stops = grad.find('gsLst', 'gs');
876
+ if (!stops) return '';
877
+ for (const child of stops.kids) {
878
+ const hex = colorNodeToHex(child, ctx);
879
+ if (hex) return hex;
880
+ }
881
+ return '';
882
+ }
883
+
884
+ /** 颜色元素(srgbClr / schemeClr / sysClr / prstClr)→ #rrggbb,并应用亮度/着色修饰 */
885
+ function colorNodeToHex(node, ctx) {
886
+ let hex = '';
887
+ if (node.name === 'srgbClr') hex = normalizeColor(node.attr('val'));
888
+ else if (node.name === 'schemeClr') hex = ctx.colors[node.attr('val')] || '';
889
+ else if (node.name === 'sysClr') hex = normalizeColor(node.attr('lastClr'));
890
+ else if (node.name === 'prstClr') hex = PRESET_COLORS[node.attr('val')] || '';
891
+ if (!hex) return '';
892
+ return applyColorMods(hex, node);
893
+ }
894
+
895
+ const PRESET_COLORS = {
896
+ black: '#000000', white: '#ffffff', red: '#ff0000', green: '#008000', blue: '#0000ff',
897
+ yellow: '#ffff00', gray: '#808080', grey: '#808080', orange: '#ffa500',
898
+ };
899
+
900
+ function applyColorMods(hex, node) {
901
+ const pct = (name) => {
902
+ const c = node.child(name);
903
+ if (!c) return null;
904
+ const v = Number.parseFloat(c.attr('val'));
905
+ return Number.isFinite(v) ? v / 100000 : null;
906
+ };
907
+ let { r, g, b } = hexToRgb(hex);
908
+ const tint = pct('tint');
909
+ const shade = pct('shade');
910
+ if (tint !== null) {
911
+ r += (255 - r) * (1 - tint);
912
+ g += (255 - g) * (1 - tint);
913
+ b += (255 - b) * (1 - tint);
914
+ }
915
+ if (shade !== null) {
916
+ r *= shade;
917
+ g *= shade;
918
+ b *= shade;
919
+ }
920
+ const lumMod = pct('lumMod');
921
+ const lumOff = pct('lumOff');
922
+ if (lumMod !== null || lumOff !== null) {
923
+ let hsl = rgbToHsl(r, g, b);
924
+ if (lumMod !== null) hsl.l *= lumMod;
925
+ if (lumOff !== null) hsl.l += lumOff;
926
+ hsl.l = Math.max(0, Math.min(1, hsl.l));
927
+ ({ r, g, b } = hslToRgb(hsl.h, hsl.s, hsl.l));
928
+ }
929
+ return rgbToHex(r, g, b);
930
+ }
931
+
932
+ const hexToRgb = (hex) => {
933
+ const v = String(hex).replace('#', '');
934
+ const n = Number.parseInt(v.length === 3 ? v.split('').map((c) => c + c).join('') : v, 16);
935
+ return Number.isFinite(n) ? { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 } : { r: 0, g: 0, b: 0 };
936
+ };
937
+ const rgbToHex = (r, g, b) => `#${[r, g, b].map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('')}`;
938
+
939
+ function rgbToHsl(r, g, b) {
940
+ r /= 255; g /= 255; b /= 255;
941
+ const max = Math.max(r, g, b);
942
+ const min = Math.min(r, g, b);
943
+ const l = (max + min) / 2;
944
+ if (max === min) return { h: 0, s: 0, l };
945
+ const d = max - min;
946
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
947
+ let h;
948
+ if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
949
+ else if (max === g) h = (b - r) / d + 2;
950
+ else h = (r - g) / d + 4;
951
+ return { h: h / 6, s, l };
952
+ }
953
+
954
+ function hslToRgb(h, s, l) {
955
+ if (s === 0) return { r: l * 255, g: l * 255, b: l * 255 };
956
+ const hue = (p, q, t) => {
957
+ let x = t;
958
+ if (x < 0) x += 1;
959
+ if (x > 1) x -= 1;
960
+ if (x < 1 / 6) return p + (q - p) * 6 * x;
961
+ if (x < 1 / 2) return q;
962
+ if (x < 2 / 3) return p + (q - p) * (2 / 3 - x) * 6;
963
+ return p;
964
+ };
965
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
966
+ const p = 2 * l - q;
967
+ return { r: hue(p, q, h + 1 / 3) * 255, g: hue(p, q, h) * 255, b: hue(p, q, h - 1 / 3) * 255 };
968
+ }
969
+
970
+ /* ---------- 小工具 ---------- */
971
+
972
+ /** 取关系属性(r:id / r:embed);在 r: 命名空间里,只按本地名取会撞上同名的页码 id */
973
+ function relAttr(n, local) {
974
+ const v = n.attrNS(REL_NS, local);
975
+ if (v !== '') return v;
976
+ for (const a of n.attrs) {
977
+ if (a.local === local && String(a.value).startsWith('rId')) return a.value;
978
+ }
979
+ return '';
980
+ }
981
+
982
+ /** 描边颜色/宽度/虚线/双端箭头(EMU → px;宽度缺失时取 fallback) */
983
+ function parseStroke(ln, ctx, fallbackPx) {
984
+ if (!ln) return { color: '', width: 0, dash: 'solid', arrowStart: false, arrowEnd: false };
985
+ const dash = normalizeDash(ln.child('prstDash')?.attr('val'));
986
+ const head = ln.child('headEnd');
987
+ const tail = ln.child('tailEnd');
988
+ const arrows = {
989
+ arrowStart: !!head && head.attr('type') !== '' && head.attr('type') !== 'none',
990
+ arrowEnd: !!tail && tail.attr('type') !== '' && tail.attr('type') !== 'none',
991
+ };
992
+ // 显式 noFill 是「无线条」:宽度也随之归零,否则回写会把无线条又画出来
993
+ if (ln.child('noFill')) return { color: '', width: 0, dash, ...arrows };
994
+ let width = 0;
995
+ const w = attrInt64(ln, 'w');
996
+ if (w > 0) width = w / EMU_PER_PX;
997
+ if (width <= 0) width = fallbackPx;
998
+ return { color: fillColorOf(ln, ctx), width, dash, ...arrows };
999
+ }
1000
+
1001
+ function normalizeDash(val) {
1002
+ switch (val) {
1003
+ case 'dash': case 'lgDash': case 'dot': case 'dashDot': return val;
1004
+ case 'sysDash': return 'dash';
1005
+ case 'sysDot': case 'sysDashDot': return 'dot';
1006
+ default: return 'solid';
1007
+ }
1008
+ }
1009
+
1010
+ function hasShadow(spPr) {
1011
+ return !!spPr?.find('effectLst', 'outerShdw');
1012
+ }
1013
+
1014
+ function attrInt64(n, local) {
1015
+ if (!n) return 0;
1016
+ const v = Number.parseInt(n.attr(local), 10);
1017
+ return Number.isFinite(v) ? v : 0;
1018
+ }