@microlee666/dom-to-pptx 1.1.4

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.
@@ -0,0 +1,2735 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var PptxGenJSImport = require('pptxgenjs');
6
+ var html2canvas = require('html2canvas');
7
+ var opentype = require('opentype.js');
8
+ var fonteditorCore = require('fonteditor-core');
9
+ var pako = require('pako');
10
+ var JSZip = require('jszip');
11
+
12
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
13
+
14
+ function _interopNamespace(e) {
15
+ if (e && e.__esModule) return e;
16
+ var n = Object.create(null);
17
+ if (e) {
18
+ Object.keys(e).forEach(function (k) {
19
+ if (k !== 'default') {
20
+ var d = Object.getOwnPropertyDescriptor(e, k);
21
+ Object.defineProperty(n, k, d.get ? d : {
22
+ enumerable: true,
23
+ get: function () { return e[k]; }
24
+ });
25
+ }
26
+ });
27
+ }
28
+ n["default"] = e;
29
+ return Object.freeze(n);
30
+ }
31
+
32
+ var PptxGenJSImport__namespace = /*#__PURE__*/_interopNamespace(PptxGenJSImport);
33
+ var html2canvas__default = /*#__PURE__*/_interopDefaultLegacy(html2canvas);
34
+ var opentype__default = /*#__PURE__*/_interopDefaultLegacy(opentype);
35
+ var pako__default = /*#__PURE__*/_interopDefaultLegacy(pako);
36
+ var JSZip__default = /*#__PURE__*/_interopDefaultLegacy(JSZip);
37
+
38
+ // src/font-utils.js
39
+
40
+ /**
41
+ * Converts various font formats to EOT (Embedded OpenType),
42
+ * which is highly compatible with PowerPoint embedding.
43
+ * @param {string} type - 'ttf', 'woff', or 'otf'
44
+ * @param {ArrayBuffer} fontBuffer - The raw font data
45
+ */
46
+ async function fontToEot(type, fontBuffer) {
47
+ const options = {
48
+ type,
49
+ hinting: true,
50
+ // inflate is required for WOFF decoding
51
+ inflate: type === 'woff' ? pako__default["default"].inflate : undefined,
52
+ };
53
+
54
+ const font = fonteditorCore.Font.create(fontBuffer, options);
55
+
56
+ const eotBuffer = font.write({
57
+ type: 'eot',
58
+ toBuffer: true,
59
+ });
60
+
61
+ if (eotBuffer instanceof ArrayBuffer) {
62
+ return eotBuffer;
63
+ }
64
+
65
+ // Ensure we return an ArrayBuffer
66
+ return eotBuffer.buffer.slice(eotBuffer.byteOffset, eotBuffer.byteOffset + eotBuffer.byteLength);
67
+ }
68
+
69
+ // src/font-embedder.js
70
+
71
+ const START_RID = 201314;
72
+
73
+ class PPTXEmbedFonts {
74
+ constructor() {
75
+ this.zip = null;
76
+ this.rId = START_RID;
77
+ this.fonts = []; // { name, data, rid }
78
+ }
79
+
80
+ async loadZip(zip) {
81
+ this.zip = zip;
82
+ }
83
+
84
+ /**
85
+ * Reads the font name from the buffer using opentype.js
86
+ */
87
+ getFontInfo(fontBuffer) {
88
+ try {
89
+ const font = opentype__default["default"].parse(fontBuffer);
90
+ const names = font.names;
91
+ // Prefer English name, fallback to others
92
+ const fontFamily = names.fontFamily.en || Object.values(names.fontFamily)[0];
93
+ return { name: fontFamily };
94
+ } catch (e) {
95
+ console.warn('Could not parse font info', e);
96
+ return { name: 'Unknown' };
97
+ }
98
+ }
99
+
100
+ async addFont(fontFace, fontBuffer, type) {
101
+ // Convert to EOT/fntdata for PPTX compatibility
102
+ const eotData = await fontToEot(type, fontBuffer);
103
+ const rid = this.rId++;
104
+ this.fonts.push({ name: fontFace, data: eotData, rid });
105
+ }
106
+
107
+ async updateFiles() {
108
+ await this.updateContentTypesXML();
109
+ await this.updatePresentationXML();
110
+ await this.updateRelsPresentationXML();
111
+ this.updateFontFiles();
112
+ }
113
+
114
+ async generateBlob() {
115
+ if (!this.zip) throw new Error('Zip not loaded');
116
+ return this.zip.generateAsync({
117
+ type: 'blob',
118
+ compression: 'DEFLATE',
119
+ compressionOptions: { level: 6 },
120
+ });
121
+ }
122
+
123
+ // --- XML Manipulation Methods ---
124
+
125
+ async updateContentTypesXML() {
126
+ const file = this.zip.file('[Content_Types].xml');
127
+ if (!file) throw new Error('[Content_Types].xml not found');
128
+
129
+ const xmlStr = await file.async('string');
130
+ const parser = new DOMParser();
131
+ const doc = parser.parseFromString(xmlStr, 'text/xml');
132
+
133
+ const types = doc.getElementsByTagName('Types')[0];
134
+ const defaults = Array.from(doc.getElementsByTagName('Default'));
135
+
136
+ const hasFntData = defaults.some((el) => el.getAttribute('Extension') === 'fntdata');
137
+
138
+ if (!hasFntData) {
139
+ const el = doc.createElement('Default');
140
+ el.setAttribute('Extension', 'fntdata');
141
+ el.setAttribute('ContentType', 'application/x-fontdata');
142
+ types.insertBefore(el, types.firstChild);
143
+ }
144
+
145
+ this.zip.file('[Content_Types].xml', new XMLSerializer().serializeToString(doc));
146
+ }
147
+
148
+ async updatePresentationXML() {
149
+ const file = this.zip.file('ppt/presentation.xml');
150
+ if (!file) throw new Error('ppt/presentation.xml not found');
151
+
152
+ const xmlStr = await file.async('string');
153
+ const parser = new DOMParser();
154
+ const doc = parser.parseFromString(xmlStr, 'text/xml');
155
+ const presentation = doc.getElementsByTagName('p:presentation')[0];
156
+
157
+ // Enable embedding flags
158
+ presentation.setAttribute('saveSubsetFonts', 'true');
159
+ presentation.setAttribute('embedTrueTypeFonts', 'true');
160
+
161
+ // Find or create embeddedFontLst
162
+ let embeddedFontLst = presentation.getElementsByTagName('p:embeddedFontLst')[0];
163
+
164
+ if (!embeddedFontLst) {
165
+ embeddedFontLst = doc.createElement('p:embeddedFontLst');
166
+
167
+ // Insert before defaultTextStyle or at end
168
+ const defaultTextStyle = presentation.getElementsByTagName('p:defaultTextStyle')[0];
169
+ if (defaultTextStyle) {
170
+ presentation.insertBefore(embeddedFontLst, defaultTextStyle);
171
+ } else {
172
+ presentation.appendChild(embeddedFontLst);
173
+ }
174
+ }
175
+
176
+ // Add font references
177
+ this.fonts.forEach((font) => {
178
+ // Check if already exists
179
+ const existing = Array.from(embeddedFontLst.getElementsByTagName('p:font')).find(
180
+ (node) => node.getAttribute('typeface') === font.name
181
+ );
182
+
183
+ if (!existing) {
184
+ const embedFont = doc.createElement('p:embeddedFont');
185
+
186
+ const fontNode = doc.createElement('p:font');
187
+ fontNode.setAttribute('typeface', font.name);
188
+ embedFont.appendChild(fontNode);
189
+
190
+ const regular = doc.createElement('p:regular');
191
+ regular.setAttribute('r:id', `rId${font.rid}`);
192
+ embedFont.appendChild(regular);
193
+
194
+ embeddedFontLst.appendChild(embedFont);
195
+ }
196
+ });
197
+
198
+ this.zip.file('ppt/presentation.xml', new XMLSerializer().serializeToString(doc));
199
+ }
200
+
201
+ async updateRelsPresentationXML() {
202
+ const file = this.zip.file('ppt/_rels/presentation.xml.rels');
203
+ if (!file) throw new Error('presentation.xml.rels not found');
204
+
205
+ const xmlStr = await file.async('string');
206
+ const parser = new DOMParser();
207
+ const doc = parser.parseFromString(xmlStr, 'text/xml');
208
+ const relationships = doc.getElementsByTagName('Relationships')[0];
209
+
210
+ this.fonts.forEach((font) => {
211
+ const rel = doc.createElement('Relationship');
212
+ rel.setAttribute('Id', `rId${font.rid}`);
213
+ rel.setAttribute('Target', `fonts/${font.rid}.fntdata`);
214
+ rel.setAttribute(
215
+ 'Type',
216
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/font'
217
+ );
218
+ relationships.appendChild(rel);
219
+ });
220
+
221
+ this.zip.file('ppt/_rels/presentation.xml.rels', new XMLSerializer().serializeToString(doc));
222
+ }
223
+
224
+ updateFontFiles() {
225
+ this.fonts.forEach((font) => {
226
+ this.zip.file(`ppt/fonts/${font.rid}.fntdata`, font.data);
227
+ });
228
+ }
229
+ }
230
+
231
+ // src/utils.js
232
+
233
+ // canvas context for color normalization
234
+ let _ctx;
235
+ function getCtx() {
236
+ if (!_ctx) _ctx = document.createElement('canvas').getContext('2d', { willReadFrequently: true });
237
+ return _ctx;
238
+ }
239
+
240
+ function getTableBorder(style, side, scale) {
241
+ const widthStr = style[`border${side}Width`];
242
+ const styleStr = style[`border${side}Style`];
243
+ const colorStr = style[`border${side}Color`];
244
+
245
+ const width = parseFloat(widthStr) || 0;
246
+ if (width === 0 || styleStr === 'none' || styleStr === 'hidden') {
247
+ return null;
248
+ }
249
+
250
+ const color = parseColor(colorStr);
251
+ if (!color.hex || color.opacity === 0) return null;
252
+
253
+ let dash = 'solid';
254
+ if (styleStr === 'dashed') dash = 'dash';
255
+ if (styleStr === 'dotted') dash = 'dot';
256
+
257
+ return {
258
+ pt: width * 0.75 * scale, // Convert px to pt
259
+ color: color.hex,
260
+ style: dash,
261
+ };
262
+ }
263
+
264
+ /**
265
+ * Extracts native table data for PptxGenJS.
266
+ */
267
+ function extractTableData(node, scale, options = {}) {
268
+ const rows = [];
269
+ const colWidths = [];
270
+ const root = options.root || null;
271
+
272
+ // 1. Calculate Column Widths based on the first row of cells
273
+ // We look at the first <tr>'s children to determine visual column widths.
274
+ // Note: This assumes a fixed grid. Complex colspan/rowspan on the first row
275
+ // might skew widths, but getBoundingClientRect captures the rendered result.
276
+ const firstRow = node.querySelector('tr');
277
+ if (firstRow) {
278
+ const cells = Array.from(firstRow.children);
279
+ cells.forEach((cell) => {
280
+ const rect = cell.getBoundingClientRect();
281
+ const wIn = rect.width * (1 / 96) * scale;
282
+ colWidths.push(wIn);
283
+ });
284
+ }
285
+
286
+ // 2. Iterate Rows
287
+ const trList = node.querySelectorAll('tr');
288
+ trList.forEach((tr) => {
289
+ const rowData = [];
290
+ const cellList = Array.from(tr.children).filter((c) =>
291
+ ['TD', 'TH'].includes(c.tagName)
292
+ );
293
+
294
+ cellList.forEach((cell) => {
295
+ const style = window.getComputedStyle(cell);
296
+ const cellText = cell.innerText.replace(/[\n\r\t]+/g, ' ').trim();
297
+
298
+ // A. Text Style
299
+ const textStyle = getTextStyle(style, scale, cellText, options);
300
+
301
+ // B. Cell Background
302
+ const fill = computeTableCellFill(style, cell, root, options);
303
+
304
+ // C. Alignment
305
+ let align = 'left';
306
+ if (style.textAlign === 'center') align = 'center';
307
+ if (style.textAlign === 'right' || style.textAlign === 'end') align = 'right';
308
+
309
+ let valign = 'top';
310
+ if (style.verticalAlign === 'middle') valign = 'middle';
311
+ if (style.verticalAlign === 'bottom') valign = 'bottom';
312
+
313
+ // D. Padding (Margins in PPTX)
314
+ // CSS Padding px -> PPTX Margin pt
315
+ const padding = getPadding(style, scale);
316
+ // getPadding returns [top, right, bottom, left] in inches relative to scale
317
+ // PptxGenJS expects points (pt) for margin: [t, r, b, l]
318
+ // or discrete properties. Let's use discrete for clarity.
319
+ const margin = [
320
+ padding[0] * 72, // top
321
+ padding[1] * 72, // right
322
+ padding[2] * 72, // bottom
323
+ padding[3] * 72 // left
324
+ ];
325
+
326
+ // E. Borders
327
+ const borderTop = getTableBorder(style, 'Top', scale);
328
+ const borderRight = getTableBorder(style, 'Right', scale);
329
+ const borderBottom = getTableBorder(style, 'Bottom', scale);
330
+ const borderLeft = getTableBorder(style, 'Left', scale);
331
+
332
+ // F. Construct Cell Object
333
+ rowData.push({
334
+ text: cellText,
335
+ options: {
336
+ color: textStyle.color,
337
+ fontFace: textStyle.fontFace,
338
+ fontSize: textStyle.fontSize,
339
+ bold: textStyle.bold,
340
+ italic: textStyle.italic,
341
+ underline: textStyle.underline,
342
+
343
+ fill: fill,
344
+ align: align,
345
+ valign: valign,
346
+ margin: margin,
347
+
348
+ rowspan: parseInt(cell.getAttribute('rowspan')) || null,
349
+ colspan: parseInt(cell.getAttribute('colspan')) || null,
350
+
351
+ border: {
352
+ pt: null, // trigger explicit object structure
353
+ top: borderTop,
354
+ right: borderRight,
355
+ bottom: borderBottom,
356
+ left: borderLeft
357
+ }
358
+ },
359
+ });
360
+ });
361
+
362
+ if (rowData.length > 0) {
363
+ rows.push(rowData);
364
+ }
365
+ });
366
+
367
+ return { rows, colWidths };
368
+ }
369
+
370
+ // Checks if any parent element has overflow: hidden which would clip this element
371
+ function isClippedByParent(node) {
372
+ let parent = node.parentElement;
373
+ while (parent && parent !== document.body) {
374
+ const style = window.getComputedStyle(parent);
375
+ const overflow = style.overflow;
376
+ if (overflow === 'hidden' || overflow === 'clip') {
377
+ return true;
378
+ }
379
+ parent = parent.parentElement;
380
+ }
381
+ return false;
382
+ }
383
+
384
+ // Helper to save gradient text
385
+ // Helper to save gradient text: extracts the first color from a gradient string
386
+ function getGradientFallbackColor(bgImage) {
387
+ if (!bgImage || bgImage === 'none') return null;
388
+
389
+ // 1. Extract content inside function(...)
390
+ // Handles linear-gradient(...), radial-gradient(...), repeating-linear-gradient(...)
391
+ const match = bgImage.match(/gradient\((.*)\)/);
392
+ if (!match) return null;
393
+
394
+ const content = match[1];
395
+
396
+ // 2. Split by comma, respecting parentheses (to avoid splitting inside rgb(), oklch(), etc.)
397
+ const parts = [];
398
+ let current = '';
399
+ let parenDepth = 0;
400
+
401
+ for (const char of content) {
402
+ if (char === '(') parenDepth++;
403
+ if (char === ')') parenDepth--;
404
+ if (char === ',' && parenDepth === 0) {
405
+ parts.push(current.trim());
406
+ current = '';
407
+ } else {
408
+ current += char;
409
+ }
410
+ }
411
+ if (current) parts.push(current.trim());
412
+
413
+ // 3. Find first part that is a color (skip angle/direction)
414
+ for (const part of parts) {
415
+ // Ignore directions (to right) or angles (90deg, 0.5turn)
416
+ if (/^(to\s|[\d\.]+(deg|rad|turn|grad))/.test(part)) continue;
417
+
418
+ // Extract color: Remove trailing position (e.g. "red 50%" -> "red")
419
+ // Regex matches whitespace + number + unit at end of string
420
+ const colorPart = part.replace(/\s+(-?[\d\.]+(%|px|em|rem|ch|vh|vw)?)$/, '');
421
+
422
+ // Check if it's not just a number (some gradients might have bare numbers? unlikely in standard syntax)
423
+ if (colorPart) return colorPart;
424
+ }
425
+
426
+ return null;
427
+ }
428
+
429
+ function mapDashType(style) {
430
+ if (style === 'dashed') return 'dash';
431
+ if (style === 'dotted') return 'dot';
432
+ return 'solid';
433
+ }
434
+
435
+ function hexToRgb(hex) {
436
+ const clean = (hex || '').replace('#', '').trim();
437
+ if (clean.length !== 6) return null;
438
+ const num = parseInt(clean, 16);
439
+ if (Number.isNaN(num)) return null;
440
+ return {
441
+ r: (num >> 16) & 255,
442
+ g: (num >> 8) & 255,
443
+ b: num & 255,
444
+ };
445
+ }
446
+
447
+ function rgbToHex(rgb) {
448
+ const toHex = (v) => v.toString(16).padStart(2, '0').toUpperCase();
449
+ return `${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}`;
450
+ }
451
+
452
+ function blendHex(baseHex, overlayHex, alpha) {
453
+ const base = hexToRgb(baseHex);
454
+ const over = hexToRgb(overlayHex);
455
+ if (!base || !over) return overlayHex;
456
+ const a = Math.max(0, Math.min(1, alpha));
457
+ const r = Math.round(base.r * (1 - a) + over.r * a);
458
+ const g = Math.round(base.g * (1 - a) + over.g * a);
459
+ const b = Math.round(base.b * (1 - a) + over.b * a);
460
+ return rgbToHex({ r, g, b });
461
+ }
462
+
463
+ function resolveTableBaseColor(node, root) {
464
+ // Start from parent to avoid picking the cell's own semi-transparent fill
465
+ let el = node?.parentElement || null;
466
+ while (el && el !== document.body) {
467
+ const style = window.getComputedStyle(el);
468
+ const bg = parseColor(style.backgroundColor);
469
+ if (bg.hex && bg.opacity > 0) return bg.hex;
470
+
471
+ const bgClip = style.webkitBackgroundClip || style.backgroundClip;
472
+ const bgImage = style.backgroundImage;
473
+ if (bgClip !== 'text' && bgImage && bgImage.includes('gradient')) {
474
+ const fallback = getGradientFallbackColor(bgImage);
475
+ if (fallback) {
476
+ const parsed = parseColor(fallback);
477
+ if (parsed.hex) return parsed.hex;
478
+ }
479
+ }
480
+
481
+ if (el === root) break;
482
+ el = el.parentElement;
483
+ }
484
+ return null;
485
+ }
486
+
487
+ function computeTableCellFill(style, cell, root, options = {}) {
488
+ const bg = parseColor(style.backgroundColor);
489
+ if (!bg.hex || bg.opacity <= 0) return null;
490
+
491
+ const flatten = options.tableConfig?.flattenTransparentFill !== false;
492
+ if (bg.opacity < 1 && flatten) {
493
+ const baseHex = resolveTableBaseColor(cell, root) || 'FFFFFF';
494
+ const blended = blendHex(baseHex, bg.hex, bg.opacity);
495
+ return { color: blended };
496
+ }
497
+
498
+ const transparency = Math.max(0, Math.min(100, (1 - bg.opacity) * 100));
499
+ return transparency > 0 ? { color: bg.hex, transparency } : { color: bg.hex };
500
+ }
501
+
502
+ /**
503
+ * Analyzes computed border styles and determines the rendering strategy.
504
+ */
505
+ function getBorderInfo(style, scale) {
506
+ const top = {
507
+ width: parseFloat(style.borderTopWidth) || 0,
508
+ style: style.borderTopStyle,
509
+ color: parseColor(style.borderTopColor).hex,
510
+ };
511
+ const right = {
512
+ width: parseFloat(style.borderRightWidth) || 0,
513
+ style: style.borderRightStyle,
514
+ color: parseColor(style.borderRightColor).hex,
515
+ };
516
+ const bottom = {
517
+ width: parseFloat(style.borderBottomWidth) || 0,
518
+ style: style.borderBottomStyle,
519
+ color: parseColor(style.borderBottomColor).hex,
520
+ };
521
+ const left = {
522
+ width: parseFloat(style.borderLeftWidth) || 0,
523
+ style: style.borderLeftStyle,
524
+ color: parseColor(style.borderLeftColor).hex,
525
+ };
526
+
527
+ const hasAnyBorder = top.width > 0 || right.width > 0 || bottom.width > 0 || left.width > 0;
528
+ if (!hasAnyBorder) return { type: 'none' };
529
+
530
+ // Check if all sides are uniform
531
+ const isUniform =
532
+ top.width === right.width &&
533
+ top.width === bottom.width &&
534
+ top.width === left.width &&
535
+ top.style === right.style &&
536
+ top.style === bottom.style &&
537
+ top.style === left.style &&
538
+ top.color === right.color &&
539
+ top.color === bottom.color &&
540
+ top.color === left.color;
541
+
542
+ if (isUniform) {
543
+ return {
544
+ type: 'uniform',
545
+ options: {
546
+ width: top.width * 0.75 * scale,
547
+ color: top.color,
548
+ transparency: (1 - parseColor(style.borderTopColor).opacity) * 100,
549
+ dashType: mapDashType(top.style),
550
+ },
551
+ };
552
+ } else {
553
+ return {
554
+ type: 'composite',
555
+ sides: { top, right, bottom, left },
556
+ };
557
+ }
558
+ }
559
+
560
+ /**
561
+ * Generates an SVG image for composite borders that respects border-radius.
562
+ */
563
+ function generateCompositeBorderSVG(w, h, radius, sides) {
564
+ radius = radius / 2; // Adjust for SVG rendering
565
+ const clipId = 'clip_' + Math.random().toString(36).substr(2, 9);
566
+ let borderRects = '';
567
+
568
+ if (sides.top.width > 0 && sides.top.color) {
569
+ borderRects += `<rect x="0" y="0" width="${w}" height="${sides.top.width}" fill="#${sides.top.color}" />`;
570
+ }
571
+ if (sides.right.width > 0 && sides.right.color) {
572
+ borderRects += `<rect x="${w - sides.right.width}" y="0" width="${sides.right.width}" height="${h}" fill="#${sides.right.color}" />`;
573
+ }
574
+ if (sides.bottom.width > 0 && sides.bottom.color) {
575
+ borderRects += `<rect x="0" y="${h - sides.bottom.width}" width="${w}" height="${sides.bottom.width}" fill="#${sides.bottom.color}" />`;
576
+ }
577
+ if (sides.left.width > 0 && sides.left.color) {
578
+ borderRects += `<rect x="0" y="0" width="${sides.left.width}" height="${h}" fill="#${sides.left.color}" />`;
579
+ }
580
+
581
+ const svg = `
582
+ <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
583
+ <defs>
584
+ <clipPath id="${clipId}">
585
+ <rect x="0" y="0" width="${w}" height="${h}" rx="${radius}" ry="${radius}" />
586
+ </clipPath>
587
+ </defs>
588
+ <g clip-path="url(#${clipId})">
589
+ ${borderRects}
590
+ </g>
591
+ </svg>`;
592
+
593
+ return 'data:image/svg+xml;base64,' + btoa(svg);
594
+ }
595
+
596
+ /**
597
+ * Generates an SVG data URL for a solid shape with non-uniform corner radii.
598
+ */
599
+ function generateCustomShapeSVG(w, h, color, opacity, radii) {
600
+ let { tl, tr, br, bl } = radii;
601
+
602
+ // Clamp radii using CSS spec logic (avoid overlap)
603
+ const factor = Math.min(
604
+ w / (tl + tr) || Infinity,
605
+ h / (tr + br) || Infinity,
606
+ w / (br + bl) || Infinity,
607
+ h / (bl + tl) || Infinity
608
+ );
609
+
610
+ if (factor < 1) {
611
+ tl *= factor;
612
+ tr *= factor;
613
+ br *= factor;
614
+ bl *= factor;
615
+ }
616
+
617
+ const path = `
618
+ M ${tl} 0
619
+ L ${w - tr} 0
620
+ A ${tr} ${tr} 0 0 1 ${w} ${tr}
621
+ L ${w} ${h - br}
622
+ A ${br} ${br} 0 0 1 ${w - br} ${h}
623
+ L ${bl} ${h}
624
+ A ${bl} ${bl} 0 0 1 0 ${h - bl}
625
+ L 0 ${tl}
626
+ A ${tl} ${tl} 0 0 1 ${tl} 0
627
+ Z
628
+ `;
629
+
630
+ const svg = `
631
+ <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
632
+ <path d="${path}" fill="#${color}" fill-opacity="${opacity}" />
633
+ </svg>`;
634
+
635
+ return 'data:image/svg+xml;base64,' + btoa(svg);
636
+ }
637
+
638
+ // --- REPLACE THE EXISTING parseColor FUNCTION ---
639
+ function parseColor(str) {
640
+ if (!str || str === 'transparent' || str.trim() === 'rgba(0, 0, 0, 0)') {
641
+ return { hex: null, opacity: 0 };
642
+ }
643
+
644
+ const ctx = getCtx();
645
+ ctx.fillStyle = str;
646
+ const computed = ctx.fillStyle;
647
+
648
+ // 1. Handle Hex Output (e.g. #ff0000) - Fast Path
649
+ if (computed.startsWith('#')) {
650
+ let hex = computed.slice(1);
651
+ let opacity = 1;
652
+ if (hex.length === 3) hex = hex.split('').map(c => c + c).join('');
653
+ if (hex.length === 4) hex = hex.split('').map(c => c + c).join('');
654
+ if (hex.length === 8) {
655
+ opacity = parseInt(hex.slice(6), 16) / 255;
656
+ hex = hex.slice(0, 6);
657
+ }
658
+ return { hex: hex.toUpperCase(), opacity };
659
+ }
660
+
661
+ // 2. Handle RGB/RGBA Output (standard) - Fast Path
662
+ if (computed.startsWith('rgb')) {
663
+ const match = computed.match(/[\d.]+/g);
664
+ if (match && match.length >= 3) {
665
+ const r = parseInt(match[0]);
666
+ const g = parseInt(match[1]);
667
+ const b = parseInt(match[2]);
668
+ const a = match.length > 3 ? parseFloat(match[3]) : 1;
669
+ const hex = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase();
670
+ return { hex, opacity: a };
671
+ }
672
+ }
673
+
674
+ // 3. Fallback: Browser returned a format we don't parse (oklch, lab, color(srgb...), etc.)
675
+ // Use Canvas API to convert to sRGB
676
+ ctx.clearRect(0, 0, 1, 1);
677
+ ctx.fillRect(0, 0, 1, 1);
678
+ const data = ctx.getImageData(0, 0, 1, 1).data;
679
+ // data = [r, g, b, a]
680
+ const r = data[0];
681
+ const g = data[1];
682
+ const b = data[2];
683
+ const a = data[3] / 255;
684
+
685
+ if (a === 0) return { hex: null, opacity: 0 };
686
+
687
+ const hex = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase();
688
+ return { hex, opacity: a };
689
+ }
690
+
691
+ function getPadding(style, scale) {
692
+ const pxToInch = 1 / 96;
693
+ return [
694
+ (parseFloat(style.paddingTop) || 0) * pxToInch * scale,
695
+ (parseFloat(style.paddingRight) || 0) * pxToInch * scale,
696
+ (parseFloat(style.paddingBottom) || 0) * pxToInch * scale,
697
+ (parseFloat(style.paddingLeft) || 0) * pxToInch * scale,
698
+ ];
699
+ }
700
+
701
+ function getSoftEdges(filterStr, scale) {
702
+ if (!filterStr || filterStr === 'none') return null;
703
+ const match = filterStr.match(/blur\(([\d.]+)px\)/);
704
+ if (match) return parseFloat(match[1]) * 0.75 * scale;
705
+ return null;
706
+ }
707
+
708
+ const DEFAULT_CJK_FONTS = [
709
+ 'PingFang SC',
710
+ 'Hiragino Sans GB',
711
+ 'Microsoft YaHei',
712
+ 'Noto Sans CJK SC',
713
+ 'Source Han Sans SC',
714
+ 'WenQuanYi Micro Hei',
715
+ 'SimHei',
716
+ 'SimSun',
717
+ 'STHeiti'
718
+ ];
719
+
720
+ function normalizeFontList(fontFamily) {
721
+ if (!fontFamily || typeof fontFamily !== 'string') return [];
722
+ return fontFamily
723
+ .split(',')
724
+ .map((f) => f.trim().replace(/['"]/g, ''))
725
+ .filter(Boolean);
726
+ }
727
+
728
+ function containsCjk(text) {
729
+ if (!text) return false;
730
+ return /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/.test(text);
731
+ }
732
+
733
+ function normalizeCjkFallbacks(options) {
734
+ if (!options) return [];
735
+ const raw =
736
+ options.fontFallbacks?.cjk ??
737
+ options.cjkFonts ??
738
+ options.cjkFont ??
739
+ [];
740
+ const list = Array.isArray(raw) ? raw : [raw];
741
+ return list
742
+ .map((f) => (typeof f === 'string' ? f.trim() : String(f)))
743
+ .filter(Boolean);
744
+ }
745
+
746
+ function pickFontFace(fontFamily, text, options) {
747
+ const fontList = normalizeFontList(fontFamily);
748
+ const primary = fontList[0] || 'Arial';
749
+
750
+ if (!containsCjk(text)) return primary;
751
+
752
+ const lowered = fontList.map((f) => f.toLowerCase());
753
+ const configured = normalizeCjkFallbacks(options);
754
+ if (configured.length > 0) {
755
+ const match = configured.find((f) => lowered.includes(f.toLowerCase()));
756
+ return match || configured[0];
757
+ }
758
+
759
+ const autoMatch = DEFAULT_CJK_FONTS.find((f) => lowered.includes(f.toLowerCase()));
760
+ return autoMatch || primary;
761
+ }
762
+
763
+ function getTextStyle(style, scale, text = '', options = {}) {
764
+ let colorObj = parseColor(style.color);
765
+
766
+ const bgClip = style.webkitBackgroundClip || style.backgroundClip;
767
+ if (colorObj.opacity === 0 && bgClip === 'text') {
768
+ const fallback = getGradientFallbackColor(style.backgroundImage);
769
+ if (fallback) colorObj = parseColor(fallback);
770
+ }
771
+
772
+ let lineSpacing = null;
773
+ const fontSizePx = parseFloat(style.fontSize);
774
+ const lhStr = style.lineHeight;
775
+
776
+ if (lhStr && lhStr !== 'normal') {
777
+ let lhPx = parseFloat(lhStr);
778
+
779
+ // Edge Case: If browser returns a raw multiplier (e.g. "1.5")
780
+ // we must multiply by font size to get the height in pixels.
781
+ // (Note: getComputedStyle usually returns 'px', but inline styles might differ)
782
+ if (/^[0-9.]+$/.test(lhStr)) {
783
+ lhPx = lhPx * fontSizePx;
784
+ }
785
+
786
+ if (!isNaN(lhPx) && lhPx > 0) {
787
+ // Convert Pixel Height to Point Height (1px = 0.75pt)
788
+ // And apply the global layout scale.
789
+ lineSpacing = lhPx * 0.75 * scale;
790
+ }
791
+ }
792
+
793
+ // --- Spacing (Margins) ---
794
+ // Convert CSS margins (px) to PPTX Paragraph Spacing (pt).
795
+ let paraSpaceBefore = 0;
796
+ let paraSpaceAfter = 0;
797
+
798
+ const mt = parseFloat(style.marginTop) || 0;
799
+ const mb = parseFloat(style.marginBottom) || 0;
800
+
801
+ if (mt > 0) paraSpaceBefore = mt * 0.75 * scale;
802
+ if (mb > 0) paraSpaceAfter = mb * 0.75 * scale;
803
+
804
+ const fontFace = pickFontFace(style.fontFamily, text, options);
805
+
806
+ return {
807
+ color: colorObj.hex || '000000',
808
+ fontFace: fontFace,
809
+ fontSize: Math.floor(fontSizePx * 0.75 * scale),
810
+ bold: parseInt(style.fontWeight) >= 600,
811
+ italic: style.fontStyle === 'italic',
812
+ underline: style.textDecoration.includes('underline'),
813
+ // Only add if we have a valid value
814
+ ...(lineSpacing && { lineSpacing }),
815
+ ...(paraSpaceBefore > 0 && { paraSpaceBefore }),
816
+ ...(paraSpaceAfter > 0 && { paraSpaceAfter }),
817
+ // Map background color to highlight if present
818
+ ...(parseColor(style.backgroundColor).hex ? { highlight: parseColor(style.backgroundColor).hex } : {}),
819
+ };
820
+ }
821
+
822
+ /**
823
+ * Determines if a given DOM node is primarily a text container.
824
+ * Updated to correctly reject Icon elements so they are rendered as images.
825
+ */
826
+ function isTextContainer(node) {
827
+ const hasText = node.textContent.trim().length > 0;
828
+ if (!hasText) return false;
829
+
830
+ const children = Array.from(node.children);
831
+ if (children.length === 0) return true;
832
+
833
+ const isSafeInline = (el) => {
834
+ // 1. Reject Web Components / Custom Elements
835
+ if (el.tagName.includes('-')) return false;
836
+ // 2. Reject Explicit Images/SVGs
837
+ if (el.tagName === 'IMG' || el.tagName === 'SVG') return false;
838
+
839
+ // 3. Reject Class-based Icons (FontAwesome, Material, Bootstrap, etc.)
840
+ // If an <i> or <span> has icon classes, it is a visual object, not text.
841
+ if (el.tagName === 'I' || el.tagName === 'SPAN') {
842
+ const cls = el.getAttribute('class') || '';
843
+ if (
844
+ cls.includes('fa-') ||
845
+ cls.includes('fas') ||
846
+ cls.includes('far') ||
847
+ cls.includes('fab') ||
848
+ cls.includes('material-icons') ||
849
+ cls.includes('bi-') ||
850
+ cls.includes('icon')
851
+ ) {
852
+ return false;
853
+ }
854
+ }
855
+
856
+ const style = window.getComputedStyle(el);
857
+ const display = style.display;
858
+
859
+ // 4. Standard Inline Tag Check
860
+ const isInlineTag = ['SPAN', 'B', 'STRONG', 'EM', 'I', 'A', 'SMALL', 'MARK'].includes(
861
+ el.tagName
862
+ );
863
+ const isInlineDisplay = display.includes('inline');
864
+
865
+ if (!isInlineTag && !isInlineDisplay) return false;
866
+
867
+ // 5. Structural Styling Check
868
+ // If a child has a background or border, it's a layout block, not a simple text span.
869
+ const bgColor = parseColor(style.backgroundColor);
870
+ const hasVisibleBg = bgColor.hex && bgColor.opacity > 0;
871
+ const hasBorder =
872
+ parseFloat(style.borderWidth) > 0 && parseColor(style.borderColor).opacity > 0;
873
+
874
+ // 4. Check for empty shapes (visual objects without text, like dots)
875
+ const hasContent = el.textContent.trim().length > 0;
876
+ if (!hasContent && (hasVisibleBg || hasBorder)) {
877
+ return false;
878
+ }
879
+
880
+ // If element has background/border and is not inline, treat as layout block
881
+ if ((hasVisibleBg || hasBorder) && !isInlineDisplay) {
882
+ return false;
883
+ }
884
+
885
+ return true;
886
+ };
887
+
888
+ return children.every(isSafeInline);
889
+ }
890
+
891
+ function getRotation(transformStr) {
892
+ if (!transformStr || transformStr === 'none') return 0;
893
+ const values = transformStr.split('(')[1].split(')')[0].split(',');
894
+ if (values.length < 4) return 0;
895
+ const a = parseFloat(values[0]);
896
+ const b = parseFloat(values[1]);
897
+ return Math.round(Math.atan2(b, a) * (180 / Math.PI));
898
+ }
899
+
900
+ function svgToPng(node) {
901
+ return new Promise((resolve) => {
902
+ const clone = node.cloneNode(true);
903
+ const rect = node.getBoundingClientRect();
904
+ const width = rect.width || 300;
905
+ const height = rect.height || 150;
906
+
907
+ function inlineStyles(source, target) {
908
+ const computed = window.getComputedStyle(source);
909
+ const properties = [
910
+ 'fill',
911
+ 'stroke',
912
+ 'stroke-width',
913
+ 'stroke-linecap',
914
+ 'stroke-linejoin',
915
+ 'opacity',
916
+ 'font-family',
917
+ 'font-size',
918
+ 'font-weight',
919
+ ];
920
+
921
+ if (computed.fill === 'none') target.setAttribute('fill', 'none');
922
+ else if (computed.fill) target.style.fill = computed.fill;
923
+
924
+ if (computed.stroke === 'none') target.setAttribute('stroke', 'none');
925
+ else if (computed.stroke) target.style.stroke = computed.stroke;
926
+
927
+ properties.forEach((prop) => {
928
+ if (prop !== 'fill' && prop !== 'stroke') {
929
+ const val = computed[prop];
930
+ if (val && val !== 'auto') target.style[prop] = val;
931
+ }
932
+ });
933
+
934
+ for (let i = 0; i < source.children.length; i++) {
935
+ if (target.children[i]) inlineStyles(source.children[i], target.children[i]);
936
+ }
937
+ }
938
+
939
+ inlineStyles(node, clone);
940
+ clone.setAttribute('width', width);
941
+ clone.setAttribute('height', height);
942
+ clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
943
+
944
+ const xml = new XMLSerializer().serializeToString(clone);
945
+ const svgUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(xml)}`;
946
+ const img = new Image();
947
+ img.crossOrigin = 'Anonymous';
948
+ img.onload = () => {
949
+ const canvas = document.createElement('canvas');
950
+ const scale = 3;
951
+ canvas.width = width * scale;
952
+ canvas.height = height * scale;
953
+ const ctx = canvas.getContext('2d');
954
+ ctx.scale(scale, scale);
955
+ ctx.drawImage(img, 0, 0, width, height);
956
+ resolve(canvas.toDataURL('image/png'));
957
+ };
958
+ img.onerror = () => resolve(null);
959
+ img.src = svgUrl;
960
+ });
961
+ }
962
+
963
+ function getVisibleShadow(shadowStr, scale) {
964
+ if (!shadowStr || shadowStr === 'none') return null;
965
+ const shadows = shadowStr.split(/,(?![^()]*\))/);
966
+ for (let s of shadows) {
967
+ s = s.trim();
968
+ if (s.startsWith('rgba(0, 0, 0, 0)')) continue;
969
+ const match = s.match(
970
+ /(rgba?\([^)]+\)|#[0-9a-fA-F]+)\s+(-?[\d.]+)px\s+(-?[\d.]+)px\s+([\d.]+)px/
971
+ );
972
+ if (match) {
973
+ const colorStr = match[1];
974
+ const x = parseFloat(match[2]);
975
+ const y = parseFloat(match[3]);
976
+ const blur = parseFloat(match[4]);
977
+ const distance = Math.sqrt(x * x + y * y);
978
+ let angle = Math.atan2(y, x) * (180 / Math.PI);
979
+ if (angle < 0) angle += 360;
980
+ const colorObj = parseColor(colorStr);
981
+ return {
982
+ type: 'outer',
983
+ angle: angle,
984
+ blur: blur * 0.75 * scale,
985
+ offset: distance * 0.75 * scale,
986
+ color: colorObj.hex || '000000',
987
+ opacity: colorObj.opacity,
988
+ };
989
+ }
990
+ }
991
+ return null;
992
+ }
993
+
994
+ /**
995
+ * Generates an SVG image for gradients, supporting degrees and keywords.
996
+ */
997
+ function generateGradientSVG(w, h, bgString, radius, border) {
998
+ try {
999
+ const match = bgString.match(/linear-gradient\((.*)\)/);
1000
+ if (!match) return null;
1001
+ const content = match[1];
1002
+
1003
+ // Split by comma, ignoring commas inside parentheses (e.g. rgba())
1004
+ const parts = content.split(/,(?![^()]*\))/).map((p) => p.trim());
1005
+ if (parts.length < 2) return null;
1006
+
1007
+ let x1 = '0%',
1008
+ y1 = '0%',
1009
+ x2 = '0%',
1010
+ y2 = '100%';
1011
+ let stopsStartIndex = 0;
1012
+ const firstPart = parts[0].toLowerCase();
1013
+
1014
+ // 1. Check for Keywords (to right, etc.)
1015
+ if (firstPart.startsWith('to ')) {
1016
+ stopsStartIndex = 1;
1017
+ const direction = firstPart.replace('to ', '').trim();
1018
+ switch (direction) {
1019
+ case 'top':
1020
+ y1 = '100%';
1021
+ y2 = '0%';
1022
+ break;
1023
+ case 'bottom':
1024
+ y1 = '0%';
1025
+ y2 = '100%';
1026
+ break;
1027
+ case 'left':
1028
+ x1 = '100%';
1029
+ x2 = '0%';
1030
+ break;
1031
+ case 'right':
1032
+ x2 = '100%';
1033
+ break;
1034
+ case 'top right':
1035
+ x1 = '0%';
1036
+ y1 = '100%';
1037
+ x2 = '100%';
1038
+ y2 = '0%';
1039
+ break;
1040
+ case 'top left':
1041
+ x1 = '100%';
1042
+ y1 = '100%';
1043
+ x2 = '0%';
1044
+ y2 = '0%';
1045
+ break;
1046
+ case 'bottom right':
1047
+ x2 = '100%';
1048
+ y2 = '100%';
1049
+ break;
1050
+ case 'bottom left':
1051
+ x1 = '100%';
1052
+ y2 = '100%';
1053
+ break;
1054
+ }
1055
+ }
1056
+ // 2. Check for Degrees (45deg, 90deg, etc.)
1057
+ else if (firstPart.match(/^-?[\d.]+(deg|rad|turn|grad)$/)) {
1058
+ stopsStartIndex = 1;
1059
+ const val = parseFloat(firstPart);
1060
+ // CSS 0deg is Top (North), 90deg is Right (East), 180deg is Bottom (South)
1061
+ // We convert this to SVG coordinates on a unit square (0-100%).
1062
+ // Formula: Map angle to perimeter coordinates.
1063
+ if (!isNaN(val)) {
1064
+ const deg = firstPart.includes('rad') ? val * (180 / Math.PI) : val;
1065
+ const cssRad = ((deg - 90) * Math.PI) / 180; // Correct CSS angle offset
1066
+
1067
+ // Calculate standard vector for rectangle center (50, 50)
1068
+ const scale = 50; // Distance from center to edge (approx)
1069
+ const cos = Math.cos(cssRad); // Y component (reversed in SVG)
1070
+ const sin = Math.sin(cssRad); // X component
1071
+
1072
+ // Invert Y for SVG coordinate system
1073
+ x1 = (50 - sin * scale).toFixed(1) + '%';
1074
+ y1 = (50 + cos * scale).toFixed(1) + '%';
1075
+ x2 = (50 + sin * scale).toFixed(1) + '%';
1076
+ y2 = (50 - cos * scale).toFixed(1) + '%';
1077
+ }
1078
+ }
1079
+
1080
+ // 3. Process Color Stops
1081
+ let stopsXML = '';
1082
+ const stopParts = parts.slice(stopsStartIndex);
1083
+
1084
+ stopParts.forEach((part, idx) => {
1085
+ // Parse "Color Position" (e.g., "red 50%")
1086
+ // Regex looks for optional space + number + unit at the end of the string
1087
+ let color = part;
1088
+ let offset = Math.round((idx / (stopParts.length - 1)) * 100) + '%';
1089
+
1090
+ const posMatch = part.match(/^(.*?)\s+(-?[\d.]+(?:%|px)?)$/);
1091
+ if (posMatch) {
1092
+ color = posMatch[1];
1093
+ offset = posMatch[2];
1094
+ }
1095
+
1096
+ // Handle RGBA/RGB for SVG compatibility
1097
+ let opacity = 1;
1098
+ if (color.includes('rgba')) {
1099
+ const rgbaMatch = color.match(/[\d.]+/g);
1100
+ if (rgbaMatch && rgbaMatch.length >= 4) {
1101
+ opacity = rgbaMatch[3];
1102
+ color = `rgb(${rgbaMatch[0]},${rgbaMatch[1]},${rgbaMatch[2]})`;
1103
+ }
1104
+ }
1105
+
1106
+ stopsXML += `<stop offset="${offset}" stop-color="${color.trim()}" stop-opacity="${opacity}"/>`;
1107
+ });
1108
+
1109
+ let strokeAttr = '';
1110
+ if (border) {
1111
+ strokeAttr = `stroke="#${border.color}" stroke-width="${border.width}"`;
1112
+ }
1113
+
1114
+ const svg = `
1115
+ <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
1116
+ <defs>
1117
+ <linearGradient id="grad" x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}">
1118
+ ${stopsXML}
1119
+ </linearGradient>
1120
+ </defs>
1121
+ <rect x="0" y="0" width="${w}" height="${h}" rx="${radius}" ry="${radius}" fill="url(#grad)" ${strokeAttr} />
1122
+ </svg>`;
1123
+
1124
+ return 'data:image/svg+xml;base64,' + btoa(svg);
1125
+ } catch (e) {
1126
+ console.warn('Gradient generation failed:', e);
1127
+ return null;
1128
+ }
1129
+ }
1130
+
1131
+ function generateBlurredSVG(w, h, color, radius, blurPx) {
1132
+ const padding = blurPx * 3;
1133
+ const fullW = w + padding * 2;
1134
+ const fullH = h + padding * 2;
1135
+ const x = padding;
1136
+ const y = padding;
1137
+ let shapeTag = '';
1138
+ const isCircle = radius >= Math.min(w, h) / 2 - 1 && Math.abs(w - h) < 2;
1139
+
1140
+ if (isCircle) {
1141
+ const cx = x + w / 2;
1142
+ const cy = y + h / 2;
1143
+ const rx = w / 2;
1144
+ const ry = h / 2;
1145
+ shapeTag = `<ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" fill="#${color}" filter="url(#f1)" />`;
1146
+ } else {
1147
+ shapeTag = `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${radius}" ry="${radius}" fill="#${color}" filter="url(#f1)" />`;
1148
+ }
1149
+
1150
+ const svg = `
1151
+ <svg xmlns="http://www.w3.org/2000/svg" width="${fullW}" height="${fullH}" viewBox="0 0 ${fullW} ${fullH}">
1152
+ <defs>
1153
+ <filter id="f1" x="-50%" y="-50%" width="200%" height="200%">
1154
+ <feGaussianBlur in="SourceGraphic" stdDeviation="${blurPx}" />
1155
+ </filter>
1156
+ </defs>
1157
+ ${shapeTag}
1158
+ </svg>`;
1159
+
1160
+ return {
1161
+ data: 'data:image/svg+xml;base64,' + btoa(svg),
1162
+ padding: padding,
1163
+ };
1164
+ }
1165
+
1166
+ // src/utils.js
1167
+
1168
+ // ... (keep all existing exports) ...
1169
+
1170
+ /**
1171
+ * Traverses the target DOM and collects all unique font-family names used.
1172
+ */
1173
+ function getUsedFontFamilies(root) {
1174
+ const families = new Set();
1175
+
1176
+ function scan(node) {
1177
+ if (node.nodeType === 1) {
1178
+ // Element
1179
+ const style = window.getComputedStyle(node);
1180
+ const fontList = normalizeFontList(style.fontFamily);
1181
+ fontList.forEach((f) => families.add(f));
1182
+ }
1183
+ for (const child of node.childNodes) {
1184
+ scan(child);
1185
+ }
1186
+ }
1187
+
1188
+ // Handle array of roots or single root
1189
+ const elements = Array.isArray(root) ? root : [root];
1190
+ elements.forEach((el) => {
1191
+ const node = typeof el === 'string' ? document.querySelector(el) : el;
1192
+ if (node) scan(node);
1193
+ });
1194
+
1195
+ return families;
1196
+ }
1197
+
1198
+ /**
1199
+ * Scans document.styleSheets to find @font-face URLs for the requested families.
1200
+ * Returns an array of { name, url } objects.
1201
+ */
1202
+ async function getAutoDetectedFonts(usedFamilies) {
1203
+ const foundFonts = [];
1204
+ const processedUrls = new Set();
1205
+
1206
+ // Helper to extract clean URL from CSS src string
1207
+ const extractUrl = (srcStr) => {
1208
+ // Look for url("...") or url('...') or url(...)
1209
+ // Prioritize woff, ttf, otf. Avoid woff2 if possible as handling is harder,
1210
+ // but if it's the only one, take it (convert logic handles it best effort).
1211
+ const matches = srcStr.match(/url\((['"]?)(.*?)\1\)/g);
1212
+ if (!matches) return null;
1213
+
1214
+ // Filter for preferred formats
1215
+ let chosenUrl = null;
1216
+ for (const match of matches) {
1217
+ const urlRaw = match.replace(/url\((['"]?)(.*?)\1\)/, '$2');
1218
+ // Skip data URIs for now (unless you want to support base64 embedding)
1219
+ if (urlRaw.startsWith('data:')) continue;
1220
+
1221
+ if (urlRaw.includes('.ttf') || urlRaw.includes('.otf') || urlRaw.includes('.woff')) {
1222
+ chosenUrl = urlRaw;
1223
+ break; // Found a good one
1224
+ }
1225
+ // Fallback
1226
+ if (!chosenUrl) chosenUrl = urlRaw;
1227
+ }
1228
+ return chosenUrl;
1229
+ };
1230
+
1231
+ for (const sheet of Array.from(document.styleSheets)) {
1232
+ try {
1233
+ // Accessing cssRules on cross-origin sheets (like Google Fonts) might fail
1234
+ // if CORS headers aren't set. We wrap in try/catch.
1235
+ const rules = sheet.cssRules || sheet.rules;
1236
+ if (!rules) continue;
1237
+
1238
+ for (const rule of Array.from(rules)) {
1239
+ if (rule.constructor.name === 'CSSFontFaceRule' || rule.type === 5) {
1240
+ const familyName = rule.style.getPropertyValue('font-family').replace(/['"]/g, '').trim();
1241
+
1242
+ if (usedFamilies.has(familyName)) {
1243
+ const src = rule.style.getPropertyValue('src');
1244
+ const url = extractUrl(src);
1245
+
1246
+ if (url && !processedUrls.has(url)) {
1247
+ processedUrls.add(url);
1248
+ foundFonts.push({ name: familyName, url: url });
1249
+ }
1250
+ }
1251
+ }
1252
+ }
1253
+ } catch (e) {
1254
+ // SecurityError is common for external stylesheets (CORS).
1255
+ // We cannot scan those automatically via CSSOM.
1256
+ console.warn('error:', e);
1257
+ console.warn('Cannot scan stylesheet for fonts (CORS restriction):', sheet.href);
1258
+ }
1259
+ }
1260
+
1261
+ return foundFonts;
1262
+ }
1263
+
1264
+ // src/image-processor.js
1265
+
1266
+ async function getProcessedImage(
1267
+ src,
1268
+ targetW,
1269
+ targetH,
1270
+ radius,
1271
+ objectFit = 'fill',
1272
+ objectPosition = '50% 50%'
1273
+ ) {
1274
+ return new Promise((resolve) => {
1275
+ const img = new Image();
1276
+ img.crossOrigin = 'Anonymous';
1277
+
1278
+ img.onload = () => {
1279
+ const canvas = document.createElement('canvas');
1280
+ const scale = 2; // Double resolution
1281
+ canvas.width = targetW * scale;
1282
+ canvas.height = targetH * scale;
1283
+ const ctx = canvas.getContext('2d');
1284
+ ctx.scale(scale, scale);
1285
+
1286
+ // Normalize radius
1287
+ let r = { tl: 0, tr: 0, br: 0, bl: 0 };
1288
+ if (typeof radius === 'number') {
1289
+ r = { tl: radius, tr: radius, br: radius, bl: radius };
1290
+ } else if (typeof radius === 'object' && radius !== null) {
1291
+ r = { ...r, ...radius };
1292
+ }
1293
+
1294
+ // 1. Draw Mask
1295
+ ctx.beginPath();
1296
+ // ... (radius clamping logic remains the same) ...
1297
+ const factor = Math.min(
1298
+ targetW / (r.tl + r.tr) || Infinity,
1299
+ targetH / (r.tr + r.br) || Infinity,
1300
+ targetW / (r.br + r.bl) || Infinity,
1301
+ targetH / (r.bl + r.tl) || Infinity
1302
+ );
1303
+
1304
+ if (factor < 1) {
1305
+ r.tl *= factor;
1306
+ r.tr *= factor;
1307
+ r.br *= factor;
1308
+ r.bl *= factor;
1309
+ }
1310
+
1311
+ ctx.moveTo(r.tl, 0);
1312
+ ctx.lineTo(targetW - r.tr, 0);
1313
+ ctx.arcTo(targetW, 0, targetW, r.tr, r.tr);
1314
+ ctx.lineTo(targetW, targetH - r.br);
1315
+ ctx.arcTo(targetW, targetH, targetW - r.br, targetH, r.br);
1316
+ ctx.lineTo(r.bl, targetH);
1317
+ ctx.arcTo(0, targetH, 0, targetH - r.bl, r.bl);
1318
+ ctx.lineTo(0, r.tl);
1319
+ ctx.arcTo(0, 0, r.tl, 0, r.tl);
1320
+ ctx.closePath();
1321
+ ctx.fillStyle = '#000';
1322
+ ctx.fill();
1323
+
1324
+ // 2. Composite Source-In
1325
+ ctx.globalCompositeOperation = 'source-in';
1326
+
1327
+ // 3. Draw Image with Object Fit logic
1328
+ const wRatio = targetW / img.width;
1329
+ const hRatio = targetH / img.height;
1330
+ let renderW, renderH;
1331
+
1332
+ if (objectFit === 'contain') {
1333
+ const fitScale = Math.min(wRatio, hRatio);
1334
+ renderW = img.width * fitScale;
1335
+ renderH = img.height * fitScale;
1336
+ } else if (objectFit === 'cover') {
1337
+ const coverScale = Math.max(wRatio, hRatio);
1338
+ renderW = img.width * coverScale;
1339
+ renderH = img.height * coverScale;
1340
+ } else if (objectFit === 'none') {
1341
+ renderW = img.width;
1342
+ renderH = img.height;
1343
+ } else if (objectFit === 'scale-down') {
1344
+ const scaleDown = Math.min(1, Math.min(wRatio, hRatio));
1345
+ renderW = img.width * scaleDown;
1346
+ renderH = img.height * scaleDown;
1347
+ } else {
1348
+ // 'fill' (default)
1349
+ renderW = targetW;
1350
+ renderH = targetH;
1351
+ }
1352
+
1353
+ // Handle Object Position (simplified parsing for "x% y%" or keywords)
1354
+ let posX = 0.5; // Default center
1355
+ let posY = 0.5;
1356
+
1357
+ const posParts = objectPosition.split(' ');
1358
+ if (posParts.length > 0) {
1359
+ const parsePos = (val) => {
1360
+ if (val === 'left' || val === 'top') return 0;
1361
+ if (val === 'center') return 0.5;
1362
+ if (val === 'right' || val === 'bottom') return 1;
1363
+ if (val.includes('%')) return parseFloat(val) / 100;
1364
+ return 0.5; // fallback
1365
+ };
1366
+ posX = parsePos(posParts[0]);
1367
+ posY = posParts.length > 1 ? parsePos(posParts[1]) : 0.5;
1368
+ }
1369
+
1370
+ const renderX = (targetW - renderW) * posX;
1371
+ const renderY = (targetH - renderH) * posY;
1372
+
1373
+ ctx.drawImage(img, renderX, renderY, renderW, renderH);
1374
+
1375
+ resolve(canvas.toDataURL('image/png'));
1376
+ };
1377
+
1378
+ img.onerror = () => resolve(null);
1379
+ img.src = src;
1380
+ });
1381
+ }
1382
+
1383
+ // src/index.js
1384
+
1385
+ // Normalize import
1386
+ const PptxGenJS = PptxGenJSImport__namespace?.default ?? PptxGenJSImport__namespace;
1387
+
1388
+ const PPI = 96;
1389
+ const PX_TO_INCH = 1 / PPI;
1390
+
1391
+ /**
1392
+ * Main export function.
1393
+ * @param {HTMLElement | string | Array<HTMLElement | string>} target
1394
+ * @param {Object} options
1395
+ * @param {string} [options.fileName]
1396
+ * @param {boolean} [options.skipDownload=false] - If true, prevents automatic download
1397
+ * @param {Object} [options.listConfig] - Config for bullets
1398
+ * @returns {Promise<Blob>} - Returns the generated PPTX Blob
1399
+ */
1400
+ async function exportToPptx(target, options = {}) {
1401
+ const resolvePptxConstructor = (pkg) => {
1402
+ if (!pkg) return null;
1403
+ if (typeof pkg === 'function') return pkg;
1404
+ if (pkg && typeof pkg.default === 'function') return pkg.default;
1405
+ if (pkg && typeof pkg.PptxGenJS === 'function') return pkg.PptxGenJS;
1406
+ if (pkg && pkg.PptxGenJS && typeof pkg.PptxGenJS.default === 'function')
1407
+ return pkg.PptxGenJS.default;
1408
+ return null;
1409
+ };
1410
+
1411
+ const PptxConstructor = resolvePptxConstructor(PptxGenJS);
1412
+ if (!PptxConstructor) throw new Error('PptxGenJS constructor not found.');
1413
+ const pptx = new PptxConstructor();
1414
+ pptx.layout = 'LAYOUT_16x9';
1415
+
1416
+ const elements = Array.isArray(target) ? target : [target];
1417
+
1418
+ for (const el of elements) {
1419
+ const root = typeof el === 'string' ? document.querySelector(el) : el;
1420
+ if (!root) {
1421
+ console.warn('Element not found, skipping slide:', el);
1422
+ continue;
1423
+ }
1424
+ const slide = pptx.addSlide();
1425
+ await processSlide(root, slide, pptx, options);
1426
+ }
1427
+
1428
+ // 3. Font Embedding Logic
1429
+ let finalBlob;
1430
+ let fontsToEmbed = options.fonts || [];
1431
+
1432
+ if (options.autoEmbedFonts) {
1433
+ // A. Scan DOM for used font families
1434
+ const usedFamilies = getUsedFontFamilies(elements);
1435
+
1436
+ // B. Scan CSS for URLs matches
1437
+ const detectedFonts = await getAutoDetectedFonts(usedFamilies);
1438
+
1439
+ // C. Merge (Avoid duplicates)
1440
+ const explicitNames = new Set(fontsToEmbed.map((f) => f.name));
1441
+ for (const autoFont of detectedFonts) {
1442
+ if (!explicitNames.has(autoFont.name)) {
1443
+ fontsToEmbed.push(autoFont);
1444
+ }
1445
+ }
1446
+
1447
+ if (detectedFonts.length > 0) {
1448
+ console.log(
1449
+ 'Auto-detected fonts:',
1450
+ detectedFonts.map((f) => f.name)
1451
+ );
1452
+ }
1453
+ }
1454
+
1455
+ if (fontsToEmbed.length > 0) {
1456
+ // Generate initial PPTX
1457
+ const initialBlob = await pptx.write({ outputType: 'blob' });
1458
+
1459
+ // Load into Embedder
1460
+ const zip = await JSZip__default["default"].loadAsync(initialBlob);
1461
+ const embedder = new PPTXEmbedFonts();
1462
+ await embedder.loadZip(zip);
1463
+
1464
+ // Fetch and Embed
1465
+ for (const fontCfg of fontsToEmbed) {
1466
+ try {
1467
+ const response = await fetch(fontCfg.url);
1468
+ if (!response.ok) throw new Error(`Failed to fetch ${fontCfg.url}`);
1469
+ const buffer = await response.arrayBuffer();
1470
+
1471
+ // Infer type
1472
+ const ext = fontCfg.url.split('.').pop().split(/[?#]/)[0].toLowerCase();
1473
+ let type = 'ttf';
1474
+ if (['woff', 'otf'].includes(ext)) type = ext;
1475
+
1476
+ await embedder.addFont(fontCfg.name, buffer, type);
1477
+ } catch (e) {
1478
+ console.warn(`Failed to embed font: ${fontCfg.name} (${fontCfg.url})`, e);
1479
+ }
1480
+ }
1481
+
1482
+ await embedder.updateFiles();
1483
+ finalBlob = await embedder.generateBlob();
1484
+ } else {
1485
+ // No fonts to embed
1486
+ finalBlob = await pptx.write({ outputType: 'blob' });
1487
+ }
1488
+
1489
+ // 4. Output Handling
1490
+ // If skipDownload is NOT true, proceed with browser download
1491
+ if (!options.skipDownload) {
1492
+ const fileName = options.fileName || 'export.pptx';
1493
+ const url = URL.createObjectURL(finalBlob);
1494
+ const a = document.createElement('a');
1495
+ a.href = url;
1496
+ a.download = fileName;
1497
+ document.body.appendChild(a);
1498
+ a.click();
1499
+ document.body.removeChild(a);
1500
+ URL.revokeObjectURL(url);
1501
+ }
1502
+
1503
+ // Always return the blob so the caller can use it (e.g. upload to server)
1504
+ return finalBlob;
1505
+ }
1506
+
1507
+ /**
1508
+ * Worker function to process a single DOM element into a single PPTX slide.
1509
+ * @param {HTMLElement} root - The root element for this slide.
1510
+ * @param {PptxGenJS.Slide} slide - The PPTX slide object to add content to.
1511
+ * @param {PptxGenJS} pptx - The main PPTX instance.
1512
+ */
1513
+ async function processSlide(root, slide, pptx, globalOptions = {}) {
1514
+ const rootRect = root.getBoundingClientRect();
1515
+ const PPTX_WIDTH_IN = 10;
1516
+ const PPTX_HEIGHT_IN = 5.625;
1517
+
1518
+ const contentWidthIn = rootRect.width * PX_TO_INCH;
1519
+ const contentHeightIn = rootRect.height * PX_TO_INCH;
1520
+ const scale = Math.min(PPTX_WIDTH_IN / contentWidthIn, PPTX_HEIGHT_IN / contentHeightIn);
1521
+
1522
+ const layoutConfig = {
1523
+ rootX: rootRect.x,
1524
+ rootY: rootRect.y,
1525
+ scale: scale,
1526
+ offX: (PPTX_WIDTH_IN - contentWidthIn * scale) / 2,
1527
+ offY: (PPTX_HEIGHT_IN - contentHeightIn * scale) / 2,
1528
+ };
1529
+
1530
+ const renderQueue = [];
1531
+ const asyncTasks = []; // Queue for heavy operations (Images, Canvas)
1532
+ let domOrderCounter = 0;
1533
+
1534
+ // Sync Traversal Function
1535
+ function collect(node, parentZIndex) {
1536
+ const order = domOrderCounter++;
1537
+
1538
+ let currentZ = parentZIndex;
1539
+ let nodeStyle = null;
1540
+ const nodeType = node.nodeType;
1541
+
1542
+ if (nodeType === 1) {
1543
+ nodeStyle = window.getComputedStyle(node);
1544
+ // Optimization: Skip completely hidden elements immediately
1545
+ if (
1546
+ nodeStyle.display === 'none' ||
1547
+ nodeStyle.visibility === 'hidden' ||
1548
+ nodeStyle.opacity === '0'
1549
+ ) {
1550
+ return;
1551
+ }
1552
+ if (nodeStyle.zIndex !== 'auto') {
1553
+ currentZ = parseInt(nodeStyle.zIndex);
1554
+ }
1555
+ }
1556
+
1557
+ // Prepare the item. If it needs async work, it returns a 'job'
1558
+ const result = prepareRenderItem(
1559
+ node,
1560
+ { ...layoutConfig, root },
1561
+ order,
1562
+ pptx,
1563
+ currentZ,
1564
+ nodeStyle,
1565
+ globalOptions
1566
+ );
1567
+
1568
+ if (result) {
1569
+ if (result.items) {
1570
+ // Push items immediately to queue (data might be missing but filled later)
1571
+ renderQueue.push(...result.items);
1572
+ }
1573
+ if (result.job) {
1574
+ // Push the promise-returning function to the task list
1575
+ asyncTasks.push(result.job);
1576
+ }
1577
+ if (result.stopRecursion) return;
1578
+ }
1579
+
1580
+ // Recurse children synchronously
1581
+ const childNodes = node.childNodes;
1582
+ for (let i = 0; i < childNodes.length; i++) {
1583
+ collect(childNodes[i], currentZ);
1584
+ }
1585
+ }
1586
+
1587
+ // 1. Traverse and build the structure (Fast)
1588
+ collect(root, 0);
1589
+
1590
+ // 2. Execute all heavy tasks in parallel (Fast)
1591
+ if (asyncTasks.length > 0) {
1592
+ await Promise.all(asyncTasks.map((task) => task()));
1593
+ }
1594
+
1595
+ // 3. Cleanup and Sort
1596
+ // Remove items that failed to generate data (marked with skip)
1597
+ const finalQueue = renderQueue.filter(
1598
+ (item) => !item.skip && (item.type !== 'image' || item.options.data)
1599
+ );
1600
+
1601
+ finalQueue.sort((a, b) => {
1602
+ if (a.zIndex !== b.zIndex) return a.zIndex - b.zIndex;
1603
+ return a.domOrder - b.domOrder;
1604
+ });
1605
+
1606
+ // 4. Add to Slide
1607
+ for (const item of finalQueue) {
1608
+ if (item.type === 'shape') slide.addShape(item.shapeType, item.options);
1609
+ if (item.type === 'image') slide.addImage(item.options);
1610
+ if (item.type === 'text') slide.addText(item.textParts, item.options);
1611
+ if (item.type === 'table') {
1612
+ slide.addTable(item.tableData.rows, {
1613
+ x: item.options.x,
1614
+ y: item.options.y,
1615
+ w: item.options.w,
1616
+ colW: item.tableData.colWidths, // Essential for correct layout
1617
+ autoPage: false,
1618
+ // Remove default table styles so our extracted CSS applies cleanly
1619
+ border: { type: "none" },
1620
+ fill: { color: "FFFFFF", transparency: 100 }
1621
+ });
1622
+ }
1623
+ }
1624
+ }
1625
+
1626
+ /**
1627
+ * Optimized html2canvas wrapper
1628
+ * Includes fix for cropped icons by adjusting styles in the cloned document.
1629
+ */
1630
+ async function elementToCanvasImage(node, widthPx, heightPx) {
1631
+ return new Promise((resolve) => {
1632
+ // 1. Assign a temp ID to locate the node inside the cloned document
1633
+ const originalId = node.id;
1634
+ const tempId = 'pptx-capture-' + Math.random().toString(36).substr(2, 9);
1635
+ node.id = tempId;
1636
+
1637
+ const width = Math.max(Math.ceil(widthPx), 1);
1638
+ const height = Math.max(Math.ceil(heightPx), 1);
1639
+ const style = window.getComputedStyle(node);
1640
+
1641
+ html2canvas__default["default"](node, {
1642
+ backgroundColor: null,
1643
+ logging: false,
1644
+ scale: 3, // Higher scale for sharper icons
1645
+ useCORS: true, // critical for external fonts/images
1646
+ onclone: (clonedDoc) => {
1647
+ const clonedNode = clonedDoc.getElementById(tempId);
1648
+ if (clonedNode) {
1649
+ // --- FIX: PREVENT ICON CLIPPING ---
1650
+ // 1. Force overflow visible so glyphs bleeding out aren't cut
1651
+ clonedNode.style.overflow = 'visible';
1652
+
1653
+ // 2. Adjust alignment for Icons to prevent baseline clipping
1654
+ // (Applies to <i>, <span>, or standard icon classes)
1655
+ const tag = clonedNode.tagName;
1656
+ if (tag === 'I' || tag === 'SPAN' || clonedNode.className.includes('fa-')) {
1657
+ // Flex center helps align the glyph exactly in the middle of the box
1658
+ // preventing top/bottom cropping due to line-height mismatches.
1659
+ clonedNode.style.display = 'inline-flex';
1660
+ clonedNode.style.justifyContent = 'center';
1661
+ clonedNode.style.alignItems = 'center';
1662
+
1663
+ // Remove margins that might offset the capture
1664
+ clonedNode.style.margin = '0';
1665
+
1666
+ // Ensure the font fits
1667
+ clonedNode.style.lineHeight = '1';
1668
+ clonedNode.style.verticalAlign = 'middle';
1669
+ }
1670
+ }
1671
+ },
1672
+ })
1673
+ .then((canvas) => {
1674
+ // Restore the original ID
1675
+ if (originalId) node.id = originalId;
1676
+ else node.removeAttribute('id');
1677
+
1678
+ const destCanvas = document.createElement('canvas');
1679
+ destCanvas.width = width;
1680
+ destCanvas.height = height;
1681
+ const ctx = destCanvas.getContext('2d');
1682
+
1683
+ // Draw captured canvas.
1684
+ // We simply draw it to fill the box. Since we centered it in 'onclone',
1685
+ // the glyph should now be visible within the bounds.
1686
+ ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, width, height);
1687
+
1688
+ // --- Border Radius Clipping (Existing Logic) ---
1689
+ let tl = parseFloat(style.borderTopLeftRadius) || 0;
1690
+ let tr = parseFloat(style.borderTopRightRadius) || 0;
1691
+ let br = parseFloat(style.borderBottomRightRadius) || 0;
1692
+ let bl = parseFloat(style.borderBottomLeftRadius) || 0;
1693
+
1694
+ const f = Math.min(
1695
+ width / (tl + tr) || Infinity,
1696
+ height / (tr + br) || Infinity,
1697
+ width / (br + bl) || Infinity,
1698
+ height / (bl + tl) || Infinity
1699
+ );
1700
+
1701
+ if (f < 1) {
1702
+ tl *= f;
1703
+ tr *= f;
1704
+ br *= f;
1705
+ bl *= f;
1706
+ }
1707
+
1708
+ if (tl + tr + br + bl > 0) {
1709
+ ctx.globalCompositeOperation = 'destination-in';
1710
+ ctx.beginPath();
1711
+ ctx.moveTo(tl, 0);
1712
+ ctx.lineTo(width - tr, 0);
1713
+ ctx.arcTo(width, 0, width, tr, tr);
1714
+ ctx.lineTo(width, height - br);
1715
+ ctx.arcTo(width, height, width - br, height, br);
1716
+ ctx.lineTo(bl, height);
1717
+ ctx.arcTo(0, height, 0, height - bl, bl);
1718
+ ctx.lineTo(0, tl);
1719
+ ctx.arcTo(0, 0, tl, 0, tl);
1720
+ ctx.closePath();
1721
+ ctx.fill();
1722
+ }
1723
+
1724
+ resolve(destCanvas.toDataURL('image/png'));
1725
+ })
1726
+ .catch((e) => {
1727
+ if (originalId) node.id = originalId;
1728
+ else node.removeAttribute('id');
1729
+ console.warn('Canvas capture failed for node', node, e);
1730
+ resolve(null);
1731
+ });
1732
+ });
1733
+ }
1734
+
1735
+ /**
1736
+ * Helper to identify elements that should be rendered as icons (Images).
1737
+ * Detects Custom Elements AND generic tags (<i>, <span>) with icon classes/pseudo-elements.
1738
+ */
1739
+ function isIconElement(node) {
1740
+ // 1. Custom Elements (hyphenated tags) or Explicit Library Tags
1741
+ const tag = node.tagName.toUpperCase();
1742
+ if (
1743
+ tag.includes('-') ||
1744
+ [
1745
+ 'MATERIAL-ICON',
1746
+ 'ICONIFY-ICON',
1747
+ 'REMIX-ICON',
1748
+ 'ION-ICON',
1749
+ 'EVA-ICON',
1750
+ 'BOX-ICON',
1751
+ 'FA-ICON',
1752
+ ].includes(tag)
1753
+ ) {
1754
+ return true;
1755
+ }
1756
+
1757
+ // 2. Class-based Icons (FontAwesome, Bootstrap, Material symbols) on <i> or <span>
1758
+ if (tag === 'I' || tag === 'SPAN') {
1759
+ const cls = node.getAttribute('class') || '';
1760
+ if (
1761
+ typeof cls === 'string' &&
1762
+ (cls.includes('fa-') ||
1763
+ cls.includes('fas') ||
1764
+ cls.includes('far') ||
1765
+ cls.includes('fab') ||
1766
+ cls.includes('bi-') ||
1767
+ cls.includes('material-icons') ||
1768
+ cls.includes('icon'))
1769
+ ) {
1770
+ // Double-check: Must have pseudo-element content to be a CSS icon
1771
+ const before = window.getComputedStyle(node, '::before').content;
1772
+ const after = window.getComputedStyle(node, '::after').content;
1773
+ const hasContent = (c) => c && c !== 'none' && c !== 'normal' && c !== '""';
1774
+
1775
+ if (hasContent(before) || hasContent(after)) return true;
1776
+ }
1777
+ }
1778
+
1779
+ return false;
1780
+ }
1781
+
1782
+ /**
1783
+ * Replaces createRenderItem.
1784
+ * Returns { items: [], job: () => Promise, stopRecursion: boolean }
1785
+ */
1786
+ function prepareRenderItem(
1787
+ node,
1788
+ config,
1789
+ domOrder,
1790
+ pptx,
1791
+ effectiveZIndex,
1792
+ computedStyle,
1793
+ globalOptions = {}
1794
+ ) {
1795
+ // 1. Text Node Handling
1796
+ if (node.nodeType === 3) {
1797
+ const textContent = node.nodeValue.trim();
1798
+ if (!textContent) return null;
1799
+
1800
+ const parent = node.parentElement;
1801
+ if (!parent) return null;
1802
+
1803
+ if (isTextContainer(parent)) return null; // Parent handles it
1804
+
1805
+ const range = document.createRange();
1806
+ range.selectNode(node);
1807
+ const rect = range.getBoundingClientRect();
1808
+ range.detach();
1809
+
1810
+ const style = window.getComputedStyle(parent);
1811
+ const widthPx = rect.width;
1812
+ const heightPx = rect.height;
1813
+ const unrotatedW = widthPx * PX_TO_INCH * config.scale;
1814
+ const unrotatedH = heightPx * PX_TO_INCH * config.scale;
1815
+
1816
+ const x = config.offX + (rect.left - config.rootX) * PX_TO_INCH * config.scale;
1817
+ const y = config.offY + (rect.top - config.rootY) * PX_TO_INCH * config.scale;
1818
+
1819
+ return {
1820
+ items: [
1821
+ {
1822
+ type: 'text',
1823
+ zIndex: effectiveZIndex,
1824
+ domOrder,
1825
+ textParts: [
1826
+ {
1827
+ text: textContent,
1828
+ options: (() => {
1829
+ const opts = getTextStyle(style, config.scale, textContent, globalOptions);
1830
+ const bg = parseColor(style.backgroundColor);
1831
+ if (opts.highlight && bg.hex && bg.opacity > 0 && !isTextContainer(parent)) {
1832
+ delete opts.highlight;
1833
+ }
1834
+ return opts;
1835
+ })(),
1836
+ },
1837
+ ],
1838
+ options: { x, y, w: unrotatedW, h: unrotatedH, margin: 0, autoFit: false },
1839
+ },
1840
+ ],
1841
+ stopRecursion: false,
1842
+ };
1843
+ }
1844
+
1845
+ if (node.nodeType !== 1) return null;
1846
+ const style = computedStyle; // Use pre-computed style
1847
+
1848
+ const rect = node.getBoundingClientRect();
1849
+ if (rect.width < 0.5 || rect.height < 0.5) return null;
1850
+
1851
+ const zIndex = effectiveZIndex;
1852
+ const rotation = getRotation(style.transform);
1853
+ const elementOpacity = parseFloat(style.opacity);
1854
+ const safeOpacity = isNaN(elementOpacity) ? 1 : elementOpacity;
1855
+
1856
+ const widthPx = node.offsetWidth || rect.width;
1857
+ const heightPx = node.offsetHeight || rect.height;
1858
+ const unrotatedW = widthPx * PX_TO_INCH * config.scale;
1859
+ const unrotatedH = heightPx * PX_TO_INCH * config.scale;
1860
+ const centerX = rect.left + rect.width / 2;
1861
+ const centerY = rect.top + rect.height / 2;
1862
+
1863
+ let x = config.offX + (centerX - config.rootX) * PX_TO_INCH * config.scale - unrotatedW / 2;
1864
+ let y = config.offY + (centerY - config.rootY) * PX_TO_INCH * config.scale - unrotatedH / 2;
1865
+ let w = unrotatedW;
1866
+ let h = unrotatedH;
1867
+
1868
+ const items = [];
1869
+
1870
+ if (node.tagName === 'TABLE') {
1871
+ const tableData = extractTableData(node, config.scale, { ...globalOptions, root: config.root });
1872
+ const cellBgItems = [];
1873
+ const renderCellBg = globalOptions.tableConfig?.renderCellBackgrounds !== false;
1874
+
1875
+ if (renderCellBg) {
1876
+ const trList = node.querySelectorAll('tr');
1877
+ trList.forEach((tr) => {
1878
+ const cellList = Array.from(tr.children).filter((c) => ['TD', 'TH'].includes(c.tagName));
1879
+ cellList.forEach((cell) => {
1880
+ const style = window.getComputedStyle(cell);
1881
+ const fill = computeTableCellFill(style, cell, config.root, globalOptions);
1882
+ if (!fill) return;
1883
+
1884
+ const rect = cell.getBoundingClientRect();
1885
+ const wIn = rect.width * PX_TO_INCH * config.scale;
1886
+ const hIn = rect.height * PX_TO_INCH * config.scale;
1887
+ const xIn = config.offX + (rect.left - config.rootX) * PX_TO_INCH * config.scale;
1888
+ const yIn = config.offY + (rect.top - config.rootY) * PX_TO_INCH * config.scale;
1889
+
1890
+ cellBgItems.push({
1891
+ type: 'shape',
1892
+ zIndex: effectiveZIndex - 0.5,
1893
+ domOrder,
1894
+ shapeType: 'rect',
1895
+ options: { x: xIn, y: yIn, w: wIn, h: hIn, fill: fill, line: { color: 'FFFFFF', transparency: 100 } }
1896
+ });
1897
+ });
1898
+ });
1899
+ }
1900
+
1901
+ // Calculate total table width to ensure X position is correct
1902
+ // (Though x calculation above usually handles it, tables can be finicky)
1903
+ return {
1904
+ items: [
1905
+ ...cellBgItems,
1906
+ {
1907
+ type: 'table',
1908
+ zIndex: effectiveZIndex,
1909
+ domOrder,
1910
+ tableData: tableData,
1911
+ options: { x, y, w: unrotatedW, h: unrotatedH }
1912
+ }
1913
+ ],
1914
+ stopRecursion: true // Important: Don't process TR/TD as separate shapes
1915
+ };
1916
+ }
1917
+
1918
+ if ((node.tagName === 'UL' || node.tagName === 'OL') && !isComplexHierarchy(node)) {
1919
+ const listItems = [];
1920
+ const liChildren = Array.from(node.children).filter((c) => c.tagName === 'LI');
1921
+
1922
+ liChildren.forEach((child, index) => {
1923
+ const liStyle = window.getComputedStyle(child);
1924
+ const liRect = child.getBoundingClientRect();
1925
+ const parentRect = node.getBoundingClientRect(); // node is UL/OL
1926
+
1927
+ // 1. Determine Bullet Config
1928
+ let bullet = { type: 'bullet' };
1929
+ const listStyleType = liStyle.listStyleType || 'disc';
1930
+
1931
+ if (node.tagName === 'OL' || listStyleType === 'decimal') {
1932
+ bullet = { type: 'number' };
1933
+ } else if (listStyleType === 'none') {
1934
+ bullet = false;
1935
+ } else {
1936
+ let code = '2022'; // disc
1937
+ if (listStyleType === 'circle') code = '25CB';
1938
+ if (listStyleType === 'square') code = '25A0';
1939
+
1940
+ // --- CHANGE: Color & Size Logic (Option > ::marker > CSS color) ---
1941
+ let finalHex = '000000';
1942
+ let markerFontSize = null;
1943
+
1944
+ // A. Check Global Option override
1945
+ if (globalOptions?.listConfig?.color) {
1946
+ finalHex = parseColor(globalOptions.listConfig.color).hex || '000000';
1947
+ }
1948
+ // B. Check ::marker pseudo element (supported in modern browsers)
1949
+ else {
1950
+ const markerStyle = window.getComputedStyle(child, '::marker');
1951
+ const markerColor = parseColor(markerStyle.color);
1952
+ if (markerColor.hex) {
1953
+ finalHex = markerColor.hex;
1954
+ } else {
1955
+ // C. Fallback to LI text color
1956
+ const colorObj = parseColor(liStyle.color);
1957
+ if (colorObj.hex) finalHex = colorObj.hex;
1958
+ }
1959
+
1960
+ // Check ::marker font-size
1961
+ const markerFs = parseFloat(markerStyle.fontSize);
1962
+ if (!isNaN(markerFs) && markerFs > 0) {
1963
+ // Convert px->pt for PPTX
1964
+ markerFontSize = markerFs * 0.75 * config.scale;
1965
+ }
1966
+ }
1967
+
1968
+ bullet = { code, color: finalHex };
1969
+ if (markerFontSize) {
1970
+ bullet.fontSize = markerFontSize;
1971
+ }
1972
+ }
1973
+
1974
+ // 2. Calculate Dynamic Indent (Respects padding-left)
1975
+ // Visual Indent = Distance from UL left edge to LI Content left edge.
1976
+ // PptxGenJS 'indent' = Space between bullet and text?
1977
+ // Actually PptxGenJS 'indent' allows setting the hanging indent.
1978
+ // We calculate the TOTAL visual offset from the parent container.
1979
+ // 1 px = 0.75 pt (approx, standard DTP).
1980
+ // We must scale it by config.scale.
1981
+ const visualIndentPx = liRect.left - parentRect.left;
1982
+ /*
1983
+ Standard indent in PPT is ~27pt.
1984
+ If visualIndentPx is small (e.g. 10px padding), we want small indent.
1985
+ If visualIndentPx is large (40px padding), we want large indent.
1986
+ We treat 'indent' as the value to pass to PptxGenJS.
1987
+ */
1988
+ const computedIndentPt = visualIndentPx * 0.75 * config.scale;
1989
+
1990
+ if (bullet && computedIndentPt > 0) {
1991
+ bullet.indent = computedIndentPt;
1992
+ // Also support custom margin between bullet and text if provided in listConfig?
1993
+ // For now, computedIndentPt covers the visual placement.
1994
+ }
1995
+
1996
+ // 3. Extract Text Parts
1997
+ const parts = collectListParts(child, liStyle, config.scale, globalOptions);
1998
+
1999
+ if (parts.length > 0) {
2000
+ parts.forEach((p) => {
2001
+ if (!p.options) p.options = {};
2002
+ });
2003
+
2004
+ // A. Apply Bullet
2005
+ // Workaround: pptxgenjs bullets inherit the style of the text run they are attached to.
2006
+ // To support ::marker styles (color, size) that differ from the text, we create
2007
+ // a "dummy" text run at the start of the list item that carries the bullet configuration.
2008
+ if (bullet) {
2009
+ const firstPartInfo = parts[0].options;
2010
+
2011
+ // Create a dummy run. We use a Zero Width Space to ensure it's rendered but invisible.
2012
+ // This "run" will hold the bullet and its specific color/size.
2013
+ const bulletRun = {
2014
+ text: '\u200B',
2015
+ options: {
2016
+ ...firstPartInfo, // Inherit base props (fontFace, etc.)
2017
+ color: bullet.color || firstPartInfo.color,
2018
+ fontSize: bullet.fontSize || firstPartInfo.fontSize,
2019
+ bullet: bullet
2020
+ }
2021
+ };
2022
+
2023
+ // Don't duplicate transparent or empty color from firstPart if bullet has one
2024
+ if (bullet.color) bulletRun.options.color = bullet.color;
2025
+ if (bullet.fontSize) bulletRun.options.fontSize = bullet.fontSize;
2026
+
2027
+ // Prepend
2028
+ parts.unshift(bulletRun);
2029
+ }
2030
+
2031
+ // B. Apply Spacing
2032
+ let ptBefore = 0;
2033
+ let ptAfter = 0;
2034
+
2035
+ // A. Check Global Options (Expected in Points)
2036
+ if (globalOptions.listConfig?.spacing) {
2037
+ if (typeof globalOptions.listConfig.spacing.before === 'number') {
2038
+ ptBefore = globalOptions.listConfig.spacing.before;
2039
+ }
2040
+ if (typeof globalOptions.listConfig.spacing.after === 'number') {
2041
+ ptAfter = globalOptions.listConfig.spacing.after;
2042
+ }
2043
+ }
2044
+ // B. Fallback to CSS Margins (Convert px -> pt)
2045
+ else {
2046
+ const mt = parseFloat(liStyle.marginTop) || 0;
2047
+ const mb = parseFloat(liStyle.marginBottom) || 0;
2048
+ if (mt > 0) ptBefore = mt * 0.75 * config.scale;
2049
+ if (mb > 0) ptAfter = mb * 0.75 * config.scale;
2050
+ }
2051
+
2052
+ if (ptBefore > 0) parts[0].options.paraSpaceBefore = ptBefore;
2053
+ if (ptAfter > 0) parts[0].options.paraSpaceAfter = ptAfter;
2054
+
2055
+ if (index < liChildren.length - 1) {
2056
+ parts[parts.length - 1].options.breakLine = true;
2057
+ }
2058
+
2059
+ listItems.push(...parts);
2060
+ }
2061
+ });
2062
+
2063
+ if (listItems.length > 0) {
2064
+ // Add background if exists
2065
+ const bgColorObj = parseColor(style.backgroundColor);
2066
+ if (bgColorObj.hex && bgColorObj.opacity > 0) {
2067
+ items.push({
2068
+ type: 'shape',
2069
+ zIndex,
2070
+ domOrder,
2071
+ shapeType: 'rect',
2072
+ options: { x, y, w, h, fill: { color: bgColorObj.hex } },
2073
+ });
2074
+ }
2075
+
2076
+ items.push({
2077
+ type: 'text',
2078
+ zIndex: zIndex + 1,
2079
+ domOrder,
2080
+ textParts: listItems,
2081
+ options: {
2082
+ x,
2083
+ y,
2084
+ w,
2085
+ h,
2086
+ align: 'left',
2087
+ valign: 'top',
2088
+ margin: 0,
2089
+ autoFit: false,
2090
+ wrap: true,
2091
+ },
2092
+ });
2093
+
2094
+ return { items, stopRecursion: true };
2095
+ }
2096
+ }
2097
+
2098
+ if (node.tagName === 'CANVAS') {
2099
+ const item = {
2100
+ type: 'image',
2101
+ zIndex,
2102
+ domOrder,
2103
+ options: { x, y, w, h, rotate: rotation, data: null }
2104
+ };
2105
+
2106
+ const job = async () => {
2107
+ try {
2108
+ // Direct data extraction from the canvas element
2109
+ // This preserves the exact current state of the chart
2110
+ const dataUrl = node.toDataURL('image/png');
2111
+
2112
+ // Basic validation
2113
+ if (dataUrl && dataUrl.length > 10) {
2114
+ item.options.data = dataUrl;
2115
+ } else {
2116
+ item.skip = true;
2117
+ }
2118
+ } catch (e) {
2119
+ // Tainted canvas (CORS issues) will throw here
2120
+ console.warn('Failed to capture canvas content:', e);
2121
+ item.skip = true;
2122
+ }
2123
+ };
2124
+
2125
+ return { items: [item], job, stopRecursion: true };
2126
+ }
2127
+
2128
+ // --- ASYNC JOB: SVG Tags ---
2129
+ if (node.nodeName.toUpperCase() === 'SVG') {
2130
+ const item = {
2131
+ type: 'image',
2132
+ zIndex,
2133
+ domOrder,
2134
+ options: { data: null, x, y, w, h, rotate: rotation },
2135
+ };
2136
+
2137
+ const job = async () => {
2138
+ const processed = await svgToPng(node);
2139
+ if (processed) item.options.data = processed;
2140
+ else item.skip = true;
2141
+ };
2142
+
2143
+ return { items: [item], job, stopRecursion: true };
2144
+ }
2145
+
2146
+ // --- ASYNC JOB: IMG Tags ---
2147
+ if (node.tagName === 'IMG') {
2148
+ let radii = {
2149
+ tl: parseFloat(style.borderTopLeftRadius) || 0,
2150
+ tr: parseFloat(style.borderTopRightRadius) || 0,
2151
+ br: parseFloat(style.borderBottomRightRadius) || 0,
2152
+ bl: parseFloat(style.borderBottomLeftRadius) || 0,
2153
+ };
2154
+
2155
+ const hasAnyRadius = radii.tl > 0 || radii.tr > 0 || radii.br > 0 || radii.bl > 0;
2156
+ if (!hasAnyRadius) {
2157
+ const parent = node.parentElement;
2158
+ const parentStyle = window.getComputedStyle(parent);
2159
+ if (parentStyle.overflow !== 'visible') {
2160
+ const pRadii = {
2161
+ tl: parseFloat(parentStyle.borderTopLeftRadius) || 0,
2162
+ tr: parseFloat(parentStyle.borderTopRightRadius) || 0,
2163
+ br: parseFloat(parentStyle.borderBottomRightRadius) || 0,
2164
+ bl: parseFloat(parentStyle.borderBottomLeftRadius) || 0,
2165
+ };
2166
+ const pRect = parent.getBoundingClientRect();
2167
+ if (Math.abs(pRect.width - rect.width) < 5 && Math.abs(pRect.height - rect.height) < 5) {
2168
+ radii = pRadii;
2169
+ }
2170
+ }
2171
+ }
2172
+
2173
+ const objectFit = style.objectFit || 'fill'; // default CSS behavior is fill
2174
+ const objectPosition = style.objectPosition || '50% 50%';
2175
+
2176
+ const item = {
2177
+ type: 'image',
2178
+ zIndex,
2179
+ domOrder,
2180
+ options: { x, y, w, h, rotate: rotation, data: null },
2181
+ };
2182
+
2183
+ const job = async () => {
2184
+ const processed = await getProcessedImage(
2185
+ node.src,
2186
+ widthPx,
2187
+ heightPx,
2188
+ radii,
2189
+ objectFit,
2190
+ objectPosition
2191
+ );
2192
+ if (processed) item.options.data = processed;
2193
+ else item.skip = true;
2194
+ };
2195
+
2196
+ return { items: [item], job, stopRecursion: true };
2197
+ }
2198
+
2199
+ // --- ASYNC JOB: Icons and Other Elements ---
2200
+ if (isIconElement(node)) {
2201
+ const item = {
2202
+ type: 'image',
2203
+ zIndex,
2204
+ domOrder,
2205
+ options: { x, y, w, h, rotate: rotation, data: null },
2206
+ };
2207
+ const job = async () => {
2208
+ const pngData = await elementToCanvasImage(node, widthPx, heightPx);
2209
+ if (pngData) item.options.data = pngData;
2210
+ else item.skip = true;
2211
+ };
2212
+ return { items: [item], job, stopRecursion: true };
2213
+ }
2214
+
2215
+ // Radii logic
2216
+ const borderRadiusValue = parseFloat(style.borderRadius) || 0;
2217
+ const borderBottomLeftRadius = parseFloat(style.borderBottomLeftRadius) || 0;
2218
+ const borderBottomRightRadius = parseFloat(style.borderBottomRightRadius) || 0;
2219
+ const borderTopLeftRadius = parseFloat(style.borderTopLeftRadius) || 0;
2220
+ const borderTopRightRadius = parseFloat(style.borderTopRightRadius) || 0;
2221
+
2222
+ const hasPartialBorderRadius =
2223
+ (borderBottomLeftRadius > 0 && borderBottomLeftRadius !== borderRadiusValue) ||
2224
+ (borderBottomRightRadius > 0 && borderBottomRightRadius !== borderRadiusValue) ||
2225
+ (borderTopLeftRadius > 0 && borderTopLeftRadius !== borderRadiusValue) ||
2226
+ (borderTopRightRadius > 0 && borderTopRightRadius !== borderRadiusValue) ||
2227
+ (borderRadiusValue === 0 &&
2228
+ (borderBottomLeftRadius ||
2229
+ borderBottomRightRadius ||
2230
+ borderTopLeftRadius ||
2231
+ borderTopRightRadius));
2232
+
2233
+ // --- PRIORITY SVG: Solid Fill with Partial Border Radius (Vector Cone/Tab) ---
2234
+ // Fix for "missing cone": Prioritize SVG vector generation over Raster Canvas for simple shapes with partial radii.
2235
+ // This avoids html2canvas failures on empty divs.
2236
+ const tempBg = parseColor(style.backgroundColor);
2237
+ const isTxt = isTextContainer(node);
2238
+
2239
+ if (hasPartialBorderRadius && tempBg.hex && !isTxt) {
2240
+ const shapeSvg = generateCustomShapeSVG(
2241
+ widthPx,
2242
+ heightPx,
2243
+ tempBg.hex,
2244
+ tempBg.opacity,
2245
+ {
2246
+ tl: parseFloat(style.borderTopLeftRadius) || 0,
2247
+ tr: parseFloat(style.borderTopRightRadius) || 0,
2248
+ br: parseFloat(style.borderBottomRightRadius) || 0,
2249
+ bl: parseFloat(style.borderBottomLeftRadius) || 0,
2250
+ }
2251
+ );
2252
+
2253
+ return {
2254
+ items: [{
2255
+ type: 'image',
2256
+ zIndex,
2257
+ domOrder,
2258
+ options: { data: shapeSvg, x, y, w, h, rotate: rotation },
2259
+ }],
2260
+ stopRecursion: true // Treat as leaf
2261
+ };
2262
+ }
2263
+
2264
+ // --- ASYNC JOB: Clipped Divs via Canvas ---
2265
+ if (hasPartialBorderRadius && isClippedByParent(node)) {
2266
+ const marginLeft = parseFloat(style.marginLeft) || 0;
2267
+ const marginTop = parseFloat(style.marginTop) || 0;
2268
+ x += marginLeft * PX_TO_INCH * config.scale;
2269
+ y += marginTop * PX_TO_INCH * config.scale;
2270
+
2271
+ const item = {
2272
+ type: 'image',
2273
+ zIndex,
2274
+ domOrder,
2275
+ options: { x, y, w, h, rotate: rotation, data: null },
2276
+ };
2277
+
2278
+ const job = async () => {
2279
+ const canvasImageData = await elementToCanvasImage(node, widthPx, heightPx);
2280
+ if (canvasImageData) item.options.data = canvasImageData;
2281
+ else item.skip = true;
2282
+ };
2283
+
2284
+ return { items: [item], job, stopRecursion: true };
2285
+ }
2286
+
2287
+ // --- SYNC: Standard CSS Extraction ---
2288
+ const bgColorObj = parseColor(style.backgroundColor);
2289
+ const bgClip = style.webkitBackgroundClip || style.backgroundClip;
2290
+ const isBgClipText = bgClip === 'text';
2291
+ const hasGradient =
2292
+ !isBgClipText && style.backgroundImage && style.backgroundImage.includes('linear-gradient');
2293
+
2294
+ const borderColorObj = parseColor(style.borderColor);
2295
+ const borderWidth = parseFloat(style.borderWidth);
2296
+ const hasBorder = borderWidth > 0 && borderColorObj.hex;
2297
+
2298
+ const borderInfo = getBorderInfo(style, config.scale);
2299
+ const hasUniformBorder = borderInfo.type === 'uniform';
2300
+ const hasCompositeBorder = borderInfo.type === 'composite';
2301
+
2302
+ const shadowStr = style.boxShadow;
2303
+ const hasShadow = shadowStr && shadowStr !== 'none';
2304
+ const softEdge = getSoftEdges(style.filter, config.scale);
2305
+
2306
+ let isImageWrapper = false;
2307
+ const imgChild = Array.from(node.children).find((c) => c.tagName === 'IMG');
2308
+ if (imgChild) {
2309
+ const childW = imgChild.offsetWidth || imgChild.getBoundingClientRect().width;
2310
+ const childH = imgChild.offsetHeight || imgChild.getBoundingClientRect().height;
2311
+ if (childW >= widthPx - 2 && childH >= heightPx - 2) isImageWrapper = true;
2312
+ }
2313
+
2314
+ let textPayload = null;
2315
+ const isText = isTextContainer(node);
2316
+
2317
+ if (isText) {
2318
+ const textParts = [];
2319
+ let trimNextLeading = false;
2320
+
2321
+ node.childNodes.forEach((child, index) => {
2322
+ // Handle <br> tags
2323
+ if (child.tagName === 'BR') {
2324
+ // 1. Trim trailing space from the *previous* text part to prevent double wrapping
2325
+ if (textParts.length > 0) {
2326
+ const lastPart = textParts[textParts.length - 1];
2327
+ if (lastPart.text && typeof lastPart.text === 'string') {
2328
+ lastPart.text = lastPart.text.trimEnd();
2329
+ }
2330
+ }
2331
+
2332
+ textParts.push({ text: '', options: { breakLine: true } });
2333
+
2334
+ // 2. Signal to trim leading space from the *next* text part
2335
+ trimNextLeading = true;
2336
+ return;
2337
+ }
2338
+
2339
+ let textVal = child.nodeType === 3 ? child.nodeValue : child.textContent;
2340
+ let nodeStyle = child.nodeType === 1 ? window.getComputedStyle(child) : style;
2341
+ textVal = textVal.replace(/[\n\r\t]+/g, ' ').replace(/\s{2,}/g, ' ');
2342
+
2343
+ // Trimming logic
2344
+ if (index === 0) textVal = textVal.trimStart();
2345
+ if (trimNextLeading) {
2346
+ textVal = textVal.trimStart();
2347
+ trimNextLeading = false;
2348
+ }
2349
+
2350
+ if (index === node.childNodes.length - 1) textVal = textVal.trimEnd();
2351
+ if (nodeStyle.textTransform === 'uppercase') textVal = textVal.toUpperCase();
2352
+ if (nodeStyle.textTransform === 'lowercase') textVal = textVal.toLowerCase();
2353
+
2354
+ if (textVal.length > 0) {
2355
+ const textOpts = getTextStyle(nodeStyle, config.scale, textVal, globalOptions);
2356
+
2357
+ // BUG FIX: Numbers 1 and 2 having background.
2358
+ // If this is a naked Text Node (nodeType 3), it inherits style from the parent container.
2359
+ // The parent container's background is already rendered as the Shape Fill.
2360
+ // We must NOT render it again as a Text Highlight, otherwise it looks like a solid marker on top of the shape.
2361
+ if (child.nodeType === 3 && textOpts.highlight) {
2362
+ delete textOpts.highlight;
2363
+ }
2364
+
2365
+ textParts.push({ text: textVal, options: textOpts });
2366
+ }
2367
+ });
2368
+
2369
+ if (textParts.length > 0) {
2370
+ let align = style.textAlign || 'left';
2371
+ if (align === 'start') align = 'left';
2372
+ if (align === 'end') align = 'right';
2373
+ let valign = 'top';
2374
+ if (style.alignItems === 'center') valign = 'middle';
2375
+ if (style.justifyContent === 'center' && style.display.includes('flex')) align = 'center';
2376
+
2377
+ const pt = parseFloat(style.paddingTop) || 0;
2378
+ const pb = parseFloat(style.paddingBottom) || 0;
2379
+ if (Math.abs(pt - pb) < 2 && bgColorObj.hex) valign = 'middle';
2380
+
2381
+ let padding = getPadding(style, config.scale);
2382
+ if (align === 'center' && valign === 'middle') padding = [0, 0, 0, 0];
2383
+
2384
+ textPayload = { text: textParts, align, valign, inset: padding };
2385
+ }
2386
+ }
2387
+
2388
+ if (hasGradient || (softEdge && bgColorObj.hex && !isImageWrapper)) {
2389
+ let bgData = null;
2390
+ let padIn = 0;
2391
+ if (softEdge) {
2392
+ const svgInfo = generateBlurredSVG(
2393
+ widthPx,
2394
+ heightPx,
2395
+ bgColorObj.hex,
2396
+ borderRadiusValue,
2397
+ softEdge
2398
+ );
2399
+ bgData = svgInfo.data;
2400
+ padIn = svgInfo.padding * PX_TO_INCH * config.scale;
2401
+ } else {
2402
+ bgData = generateGradientSVG(
2403
+ widthPx,
2404
+ heightPx,
2405
+ style.backgroundImage,
2406
+ borderRadiusValue,
2407
+ hasBorder ? { color: borderColorObj.hex, width: borderWidth } : null
2408
+ );
2409
+ }
2410
+
2411
+ if (bgData) {
2412
+ items.push({
2413
+ type: 'image',
2414
+ zIndex,
2415
+ domOrder,
2416
+ options: {
2417
+ data: bgData,
2418
+ x: x - padIn,
2419
+ y: y - padIn,
2420
+ w: w + padIn * 2,
2421
+ h: h + padIn * 2,
2422
+ rotate: rotation,
2423
+ },
2424
+ });
2425
+ }
2426
+
2427
+ if (textPayload) {
2428
+ textPayload.text[0].options.fontSize =
2429
+ Math.floor(textPayload.text[0]?.options?.fontSize) || 12;
2430
+ items.push({
2431
+ type: 'text',
2432
+ zIndex: zIndex + 1,
2433
+ domOrder,
2434
+ textParts: textPayload.text,
2435
+ options: {
2436
+ x,
2437
+ y,
2438
+ w,
2439
+ h,
2440
+ align: textPayload.align,
2441
+ valign: textPayload.valign,
2442
+ inset: textPayload.inset,
2443
+ rotate: rotation,
2444
+ margin: 0,
2445
+ wrap: true,
2446
+ autoFit: false,
2447
+ },
2448
+ });
2449
+ }
2450
+ if (hasCompositeBorder) {
2451
+ const borderItems = createCompositeBorderItems(
2452
+ borderInfo.sides,
2453
+ x,
2454
+ y,
2455
+ w,
2456
+ h,
2457
+ config.scale,
2458
+ zIndex,
2459
+ domOrder
2460
+ );
2461
+ items.push(...borderItems);
2462
+ }
2463
+ } else if (
2464
+ (bgColorObj.hex && !isImageWrapper) ||
2465
+ hasUniformBorder ||
2466
+ hasCompositeBorder ||
2467
+ hasShadow ||
2468
+ textPayload
2469
+ ) {
2470
+ const finalAlpha = safeOpacity * bgColorObj.opacity;
2471
+ const transparency = (1 - finalAlpha) * 100;
2472
+ const useSolidFill = bgColorObj.hex && !isImageWrapper;
2473
+
2474
+ if (hasPartialBorderRadius && useSolidFill && !textPayload) {
2475
+ const shapeSvg = generateCustomShapeSVG(
2476
+ widthPx,
2477
+ heightPx,
2478
+ bgColorObj.hex,
2479
+ bgColorObj.opacity,
2480
+ {
2481
+ tl: parseFloat(style.borderTopLeftRadius) || 0,
2482
+ tr: parseFloat(style.borderTopRightRadius) || 0,
2483
+ br: parseFloat(style.borderBottomRightRadius) || 0,
2484
+ bl: parseFloat(style.borderBottomLeftRadius) || 0,
2485
+ }
2486
+ );
2487
+
2488
+ items.push({
2489
+ type: 'image',
2490
+ zIndex,
2491
+ domOrder,
2492
+ options: { data: shapeSvg, x, y, w, h, rotate: rotation },
2493
+ });
2494
+ } else {
2495
+ const shapeOpts = {
2496
+ x,
2497
+ y,
2498
+ w,
2499
+ h,
2500
+ rotate: rotation,
2501
+ fill: useSolidFill
2502
+ ? { color: bgColorObj.hex, transparency: transparency }
2503
+ : { type: 'none' },
2504
+ line: hasUniformBorder ? borderInfo.options : null,
2505
+ };
2506
+
2507
+ if (hasShadow) shapeOpts.shadow = getVisibleShadow(shadowStr, config.scale);
2508
+
2509
+ // 1. Calculate dimensions first
2510
+ const minDimension = Math.min(widthPx, heightPx);
2511
+
2512
+ let rawRadius = parseFloat(style.borderRadius) || 0;
2513
+ const isPercentage = style.borderRadius && style.borderRadius.toString().includes('%');
2514
+
2515
+ // 2. Normalize radius to pixels
2516
+ let radiusPx = rawRadius;
2517
+ if (isPercentage) {
2518
+ radiusPx = (rawRadius / 100) * minDimension;
2519
+ }
2520
+
2521
+ let shapeType = pptx.ShapeType.rect;
2522
+
2523
+ // 3. Determine Shape Logic
2524
+ const isSquare = Math.abs(widthPx - heightPx) < 1;
2525
+ const isFullyRound = radiusPx >= minDimension / 2;
2526
+
2527
+ // CASE A: It is an Ellipse if:
2528
+ // 1. It is explicitly "50%" (standard CSS way to make ovals/circles)
2529
+ // 2. OR it is a perfect square and fully rounded (a circle)
2530
+ if (isFullyRound && (isPercentage || isSquare)) {
2531
+ shapeType = pptx.ShapeType.ellipse;
2532
+ }
2533
+ // CASE B: It is a Rounded Rectangle (including "Pill" shapes)
2534
+ else if (radiusPx > 0) {
2535
+ shapeType = pptx.ShapeType.roundRect;
2536
+ let r = radiusPx / minDimension;
2537
+ if (r > 0.5) r = 0.5;
2538
+ if (minDimension < 100) r = r * 0.25; // Small size adjustment for small shapes
2539
+
2540
+ shapeOpts.rectRadius = r;
2541
+ }
2542
+
2543
+ if (textPayload) {
2544
+ textPayload.text[0].options.fontSize =
2545
+ Math.floor(textPayload.text[0]?.options?.fontSize) || 12;
2546
+ const textOptions = {
2547
+ shape: shapeType,
2548
+ ...shapeOpts,
2549
+ rotate: rotation,
2550
+ align: textPayload.align,
2551
+ valign: textPayload.valign,
2552
+ inset: textPayload.inset,
2553
+ margin: 0,
2554
+ wrap: true,
2555
+ autoFit: false,
2556
+ };
2557
+ items.push({
2558
+ type: 'text',
2559
+ zIndex,
2560
+ domOrder,
2561
+ textParts: textPayload.text,
2562
+ options: textOptions,
2563
+ });
2564
+ } else if (!hasPartialBorderRadius) {
2565
+ items.push({
2566
+ type: 'shape',
2567
+ zIndex,
2568
+ domOrder,
2569
+ shapeType,
2570
+ options: shapeOpts,
2571
+ });
2572
+ }
2573
+ }
2574
+
2575
+ if (hasCompositeBorder) {
2576
+ const borderSvgData = generateCompositeBorderSVG(
2577
+ widthPx,
2578
+ heightPx,
2579
+ borderRadiusValue,
2580
+ borderInfo.sides
2581
+ );
2582
+ if (borderSvgData) {
2583
+ items.push({
2584
+ type: 'image',
2585
+ zIndex: zIndex + 1,
2586
+ domOrder,
2587
+ options: { data: borderSvgData, x, y, w, h, rotate: rotation },
2588
+ });
2589
+ }
2590
+ }
2591
+ }
2592
+
2593
+ return { items, stopRecursion: !!textPayload };
2594
+ }
2595
+
2596
+ function isComplexHierarchy(root) {
2597
+ // Use a simple tree traversal to find forbidden elements in the list structure
2598
+ if (root?.getAttribute?.('data-pptx-list') === 'complex') return true;
2599
+
2600
+ const stack = [root];
2601
+ while (stack.length > 0) {
2602
+ const el = stack.pop();
2603
+
2604
+ // 1. Layouts: Flex/Grid on LIs
2605
+ if (el.tagName === 'LI') {
2606
+ const s = window.getComputedStyle(el);
2607
+ if (s.display === 'flex' || s.display === 'grid' || s.display === 'inline-flex') return true;
2608
+
2609
+ // Custom list items (e.g., list-style: none + structured children)
2610
+ const listStyleType = s.listStyleType || s.listStyle;
2611
+ if (listStyleType === 'none') {
2612
+ const hasStructuredChild = Array.from(el.children).some((child) => {
2613
+ const cs = window.getComputedStyle(child);
2614
+ const display = cs.display || '';
2615
+ if (!display.includes('inline')) return true;
2616
+
2617
+ const bg = parseColor(cs.backgroundColor);
2618
+ if (bg.hex && bg.opacity > 0) return true;
2619
+
2620
+ const bw = parseFloat(cs.borderWidth) || 0;
2621
+ const bc = parseColor(cs.borderColor);
2622
+ if (bw > 0 && bc.opacity > 0) return true;
2623
+
2624
+ return false;
2625
+ });
2626
+
2627
+ if (hasStructuredChild) return true;
2628
+ }
2629
+ }
2630
+
2631
+ // 2. Media / Icons
2632
+ if (['IMG', 'SVG', 'CANVAS', 'VIDEO', 'IFRAME'].includes(el.tagName)) return true;
2633
+ if (isIconElement(el)) return true;
2634
+
2635
+ // 3. Nested Lists (Flattening logic doesn't support nested bullets well yet)
2636
+ if (el !== root && (el.tagName === 'UL' || el.tagName === 'OL')) return true;
2637
+
2638
+ // Recurse, but don't go too deep if not needed
2639
+ for (let i = 0; i < el.children.length; i++) {
2640
+ stack.push(el.children[i]);
2641
+ }
2642
+ }
2643
+ return false;
2644
+ }
2645
+
2646
+ function collectListParts(node, parentStyle, scale, globalOptions) {
2647
+ const parts = [];
2648
+
2649
+ // Check for CSS Content (::before) - often used for icons
2650
+ if (node.nodeType === 1) {
2651
+ const beforeStyle = window.getComputedStyle(node, '::before');
2652
+ const content = beforeStyle.content;
2653
+ if (content && content !== 'none' && content !== 'normal' && content !== '""') {
2654
+ // Strip quotes
2655
+ const cleanContent = content.replace(/^['"]|['"]$/g, '');
2656
+ if (cleanContent.trim()) {
2657
+ parts.push({
2658
+ text: cleanContent + ' ', // Add space after icon
2659
+ options: getTextStyle(window.getComputedStyle(node), scale, cleanContent, globalOptions),
2660
+ });
2661
+ }
2662
+ }
2663
+ }
2664
+
2665
+ node.childNodes.forEach((child) => {
2666
+ if (child.nodeType === 3) {
2667
+ // Text
2668
+ const val = child.nodeValue.replace(/[\n\r\t]+/g, ' ').replace(/\s{2,}/g, ' ');
2669
+ if (val) {
2670
+ // Use parent style if child is text node, otherwise current style
2671
+ const styleToUse = node.nodeType === 1 ? window.getComputedStyle(node) : parentStyle;
2672
+ parts.push({
2673
+ text: val,
2674
+ options: getTextStyle(styleToUse, scale, val, globalOptions),
2675
+ });
2676
+ }
2677
+ } else if (child.nodeType === 1) {
2678
+ // Element (span, i, b)
2679
+ // Recurse
2680
+ parts.push(...collectListParts(child, parentStyle, scale, globalOptions));
2681
+ }
2682
+ });
2683
+
2684
+ return parts;
2685
+ }
2686
+
2687
+ function createCompositeBorderItems(sides, x, y, w, h, scale, zIndex, domOrder) {
2688
+ const items = [];
2689
+ const pxToInch = 1 / 96;
2690
+ const common = { zIndex: zIndex + 1, domOrder, shapeType: 'rect' };
2691
+
2692
+ if (sides.top.width > 0)
2693
+ items.push({
2694
+ ...common,
2695
+ options: { x, y, w, h: sides.top.width * pxToInch * scale, fill: { color: sides.top.color } },
2696
+ });
2697
+ if (sides.right.width > 0)
2698
+ items.push({
2699
+ ...common,
2700
+ options: {
2701
+ x: x + w - sides.right.width * pxToInch * scale,
2702
+ y,
2703
+ w: sides.right.width * pxToInch * scale,
2704
+ h,
2705
+ fill: { color: sides.right.color },
2706
+ },
2707
+ });
2708
+ if (sides.bottom.width > 0)
2709
+ items.push({
2710
+ ...common,
2711
+ options: {
2712
+ x,
2713
+ y: y + h - sides.bottom.width * pxToInch * scale,
2714
+ w,
2715
+ h: sides.bottom.width * pxToInch * scale,
2716
+ fill: { color: sides.bottom.color },
2717
+ },
2718
+ });
2719
+ if (sides.left.width > 0)
2720
+ items.push({
2721
+ ...common,
2722
+ options: {
2723
+ x,
2724
+ y,
2725
+ w: sides.left.width * pxToInch * scale,
2726
+ h,
2727
+ fill: { color: sides.left.color },
2728
+ },
2729
+ });
2730
+
2731
+ return items;
2732
+ }
2733
+
2734
+ exports.exportToPptx = exportToPptx;
2735
+ //# sourceMappingURL=dom-to-pptx.cjs.map