dom-to-pptx 1.0.9 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js CHANGED
@@ -1,833 +1,971 @@
1
- // src/index.js
2
- import * as PptxGenJSImport from 'pptxgenjs';
3
- import html2canvas from 'html2canvas';
4
-
5
- // Normalize import
6
- const PptxGenJS = PptxGenJSImport?.default ?? PptxGenJSImport;
7
-
8
- import {
9
- parseColor,
10
- getTextStyle,
11
- isTextContainer,
12
- getVisibleShadow,
13
- generateGradientSVG,
14
- getRotation,
15
- svgToPng,
16
- getPadding,
17
- getSoftEdges,
18
- generateBlurredSVG,
19
- getBorderInfo,
20
- generateCompositeBorderSVG,
21
- isClippedByParent,
22
- generateCustomShapeSVG,
23
- } from './utils.js';
24
- import { getProcessedImage } from './image-processor.js';
25
-
26
- const PPI = 96;
27
- const PX_TO_INCH = 1 / PPI;
28
-
29
- /**
30
- * Main export function. Accepts single element or an array.
31
- * @param {HTMLElement | string | Array<HTMLElement | string>} target - The root element(s) to convert.
32
- * @param {Object} options - { fileName: string }
33
- */
34
- export async function exportToPptx(target, options = {}) {
35
- const resolvePptxConstructor = (pkg) => {
36
- if (!pkg) return null;
37
- if (typeof pkg === 'function') return pkg;
38
- if (pkg && typeof pkg.default === 'function') return pkg.default;
39
- if (pkg && typeof pkg.PptxGenJS === 'function') return pkg.PptxGenJS;
40
- if (pkg && pkg.PptxGenJS && typeof pkg.PptxGenJS.default === 'function')
41
- return pkg.PptxGenJS.default;
42
- return null;
43
- };
44
-
45
- const PptxConstructor = resolvePptxConstructor(PptxGenJS);
46
- if (!PptxConstructor) throw new Error('PptxGenJS constructor not found.');
47
- const pptx = new PptxConstructor();
48
- pptx.layout = 'LAYOUT_16x9';
49
-
50
- const elements = Array.isArray(target) ? target : [target];
51
-
52
- for (const el of elements) {
53
- const root = typeof el === 'string' ? document.querySelector(el) : el;
54
- if (!root) {
55
- console.warn('Element not found, skipping slide:', el);
56
- continue;
57
- }
58
- const slide = pptx.addSlide();
59
- await processSlide(root, slide, pptx);
60
- }
61
-
62
- const fileName = options.fileName || 'export.pptx';
63
- pptx.writeFile({ fileName });
64
- }
65
-
66
- /**
67
- * Worker function to process a single DOM element into a single PPTX slide.
68
- * @param {HTMLElement} root - The root element for this slide.
69
- * @param {PptxGenJS.Slide} slide - The PPTX slide object to add content to.
70
- * @param {PptxGenJS} pptx - The main PPTX instance.
71
- */
72
- async function processSlide(root, slide, pptx) {
73
- const rootRect = root.getBoundingClientRect();
74
- const PPTX_WIDTH_IN = 10;
75
- const PPTX_HEIGHT_IN = 5.625;
76
-
77
- const contentWidthIn = rootRect.width * PX_TO_INCH;
78
- const contentHeightIn = rootRect.height * PX_TO_INCH;
79
- const scale = Math.min(PPTX_WIDTH_IN / contentWidthIn, PPTX_HEIGHT_IN / contentHeightIn);
80
-
81
- const layoutConfig = {
82
- rootX: rootRect.x,
83
- rootY: rootRect.y,
84
- scale: scale,
85
- offX: (PPTX_WIDTH_IN - contentWidthIn * scale) / 2,
86
- offY: (PPTX_HEIGHT_IN - contentHeightIn * scale) / 2,
87
- };
88
-
89
- const renderQueue = [];
90
- const asyncTasks = []; // Queue for heavy operations (Images, Canvas)
91
- let domOrderCounter = 0;
92
-
93
- // Sync Traversal Function
94
- function collect(node, parentZIndex) {
95
- const order = domOrderCounter++;
96
-
97
- let currentZ = parentZIndex;
98
- let nodeStyle = null;
99
- const nodeType = node.nodeType;
100
-
101
- if (nodeType === 1) {
102
- nodeStyle = window.getComputedStyle(node);
103
- // Optimization: Skip completely hidden elements immediately
104
- if (
105
- nodeStyle.display === 'none' ||
106
- nodeStyle.visibility === 'hidden' ||
107
- nodeStyle.opacity === '0'
108
- ) {
109
- return;
110
- }
111
- if (nodeStyle.zIndex !== 'auto') {
112
- currentZ = parseInt(nodeStyle.zIndex);
113
- }
114
- }
115
-
116
- // Prepare the item. If it needs async work, it returns a 'job'
117
- const result = prepareRenderItem(
118
- node,
119
- { ...layoutConfig, root },
120
- order,
121
- pptx,
122
- currentZ,
123
- nodeStyle
124
- );
125
-
126
- if (result) {
127
- if (result.items) {
128
- // Push items immediately to queue (data might be missing but filled later)
129
- renderQueue.push(...result.items);
130
- }
131
- if (result.job) {
132
- // Push the promise-returning function to the task list
133
- asyncTasks.push(result.job);
134
- }
135
- if (result.stopRecursion) return;
136
- }
137
-
138
- // Recurse children synchronously
139
- const childNodes = node.childNodes;
140
- for (let i = 0; i < childNodes.length; i++) {
141
- collect(childNodes[i], currentZ);
142
- }
143
- }
144
-
145
- // 1. Traverse and build the structure (Fast)
146
- collect(root, 0);
147
-
148
- // 2. Execute all heavy tasks in parallel (Fast)
149
- if (asyncTasks.length > 0) {
150
- await Promise.all(asyncTasks.map((task) => task()));
151
- }
152
-
153
- // 3. Cleanup and Sort
154
- // Remove items that failed to generate data (marked with skip)
155
- const finalQueue = renderQueue.filter(
156
- (item) => !item.skip && (item.type !== 'image' || item.options.data)
157
- );
158
-
159
- finalQueue.sort((a, b) => {
160
- if (a.zIndex !== b.zIndex) return a.zIndex - b.zIndex;
161
- return a.domOrder - b.domOrder;
162
- });
163
-
164
- // 4. Add to Slide
165
- for (const item of finalQueue) {
166
- if (item.type === 'shape') slide.addShape(item.shapeType, item.options);
167
- if (item.type === 'image') slide.addImage(item.options);
168
- if (item.type === 'text') slide.addText(item.textParts, item.options);
169
- }
170
- }
171
-
172
- /**
173
- * Optimized html2canvas wrapper
174
- * Now strictly captures the node itself, not the root.
175
- */
176
- /**
177
- * Optimized html2canvas wrapper
178
- * Includes fix for cropped icons by adjusting styles in the cloned document.
179
- */
180
- async function elementToCanvasImage(node, widthPx, heightPx) {
181
- return new Promise((resolve) => {
182
- // 1. Assign a temp ID to locate the node inside the cloned document
183
- const originalId = node.id;
184
- const tempId = 'pptx-capture-' + Math.random().toString(36).substr(2, 9);
185
- node.id = tempId;
186
-
187
- const width = Math.max(Math.ceil(widthPx), 1);
188
- const height = Math.max(Math.ceil(heightPx), 1);
189
- const style = window.getComputedStyle(node);
190
-
191
- html2canvas(node, {
192
- backgroundColor: null,
193
- logging: false,
194
- scale: 3, // Higher scale for sharper icons
195
- useCORS: true, // critical for external fonts/images
196
- onclone: (clonedDoc) => {
197
- const clonedNode = clonedDoc.getElementById(tempId);
198
- if (clonedNode) {
199
- // --- FIX: PREVENT ICON CLIPPING ---
200
- // 1. Force overflow visible so glyphs bleeding out aren't cut
201
- clonedNode.style.overflow = 'visible';
202
-
203
- // 2. Adjust alignment for Icons to prevent baseline clipping
204
- // (Applies to <i>, <span>, or standard icon classes)
205
- const tag = clonedNode.tagName;
206
- if (tag === 'I' || tag === 'SPAN' || clonedNode.className.includes('fa-')) {
207
- // Flex center helps align the glyph exactly in the middle of the box
208
- // preventing top/bottom cropping due to line-height mismatches.
209
- clonedNode.style.display = 'inline-flex';
210
- clonedNode.style.justifyContent = 'center';
211
- clonedNode.style.alignItems = 'center';
212
-
213
- // Remove margins that might offset the capture
214
- clonedNode.style.margin = '0';
215
-
216
- // Ensure the font fits
217
- clonedNode.style.lineHeight = '1';
218
- clonedNode.style.verticalAlign = 'middle';
219
- }
220
- }
221
- },
222
- })
223
- .then((canvas) => {
224
- // Restore the original ID
225
- if (originalId) node.id = originalId;
226
- else node.removeAttribute('id');
227
-
228
- const destCanvas = document.createElement('canvas');
229
- destCanvas.width = width;
230
- destCanvas.height = height;
231
- const ctx = destCanvas.getContext('2d');
232
-
233
- // Draw captured canvas.
234
- // We simply draw it to fill the box. Since we centered it in 'onclone',
235
- // the glyph should now be visible within the bounds.
236
- ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, width, height);
237
-
238
- // --- Border Radius Clipping (Existing Logic) ---
239
- let tl = parseFloat(style.borderTopLeftRadius) || 0;
240
- let tr = parseFloat(style.borderTopRightRadius) || 0;
241
- let br = parseFloat(style.borderBottomRightRadius) || 0;
242
- let bl = parseFloat(style.borderBottomLeftRadius) || 0;
243
-
244
- const f = Math.min(
245
- width / (tl + tr) || Infinity,
246
- height / (tr + br) || Infinity,
247
- width / (br + bl) || Infinity,
248
- height / (bl + tl) || Infinity
249
- );
250
-
251
- if (f < 1) {
252
- tl *= f;
253
- tr *= f;
254
- br *= f;
255
- bl *= f;
256
- }
257
-
258
- if (tl + tr + br + bl > 0) {
259
- ctx.globalCompositeOperation = 'destination-in';
260
- ctx.beginPath();
261
- ctx.moveTo(tl, 0);
262
- ctx.lineTo(width - tr, 0);
263
- ctx.arcTo(width, 0, width, tr, tr);
264
- ctx.lineTo(width, height - br);
265
- ctx.arcTo(width, height, width - br, height, br);
266
- ctx.lineTo(bl, height);
267
- ctx.arcTo(0, height, 0, height - bl, bl);
268
- ctx.lineTo(0, tl);
269
- ctx.arcTo(0, 0, tl, 0, tl);
270
- ctx.closePath();
271
- ctx.fill();
272
- }
273
-
274
- resolve(destCanvas.toDataURL('image/png'));
275
- })
276
- .catch((e) => {
277
- if (originalId) node.id = originalId;
278
- else node.removeAttribute('id');
279
- console.warn('Canvas capture failed for node', node, e);
280
- resolve(null);
281
- });
282
- });
283
- }
284
-
285
- /**
286
- * Helper to identify elements that should be rendered as icons (Images).
287
- * Detects Custom Elements AND generic tags (<i>, <span>) with icon classes/pseudo-elements.
288
- */
289
- function isIconElement(node) {
290
- // 1. Custom Elements (hyphenated tags) or Explicit Library Tags
291
- const tag = node.tagName.toUpperCase();
292
- if (
293
- tag.includes('-') ||
294
- [
295
- 'MATERIAL-ICON',
296
- 'ICONIFY-ICON',
297
- 'REMIX-ICON',
298
- 'ION-ICON',
299
- 'EVA-ICON',
300
- 'BOX-ICON',
301
- 'FA-ICON',
302
- ].includes(tag)
303
- ) {
304
- return true;
305
- }
306
-
307
- // 2. Class-based Icons (FontAwesome, Bootstrap, Material symbols) on <i> or <span>
308
- if (tag === 'I' || tag === 'SPAN') {
309
- const cls = node.getAttribute('class') || '';
310
- if (
311
- typeof cls === 'string' &&
312
- (cls.includes('fa-') ||
313
- cls.includes('fas') ||
314
- cls.includes('far') ||
315
- cls.includes('fab') ||
316
- cls.includes('bi-') ||
317
- cls.includes('material-icons') ||
318
- cls.includes('icon'))
319
- ) {
320
- // Double-check: Must have pseudo-element content to be a CSS icon
321
- const before = window.getComputedStyle(node, '::before').content;
322
- const after = window.getComputedStyle(node, '::after').content;
323
- const hasContent = (c) => c && c !== 'none' && c !== 'normal' && c !== '""';
324
-
325
- if (hasContent(before) || hasContent(after)) return true;
326
- }
327
- console.log('Icon element:', node, cls);
328
- }
329
-
330
- return false;
331
- }
332
-
333
- /**
334
- * Replaces createRenderItem.
335
- * Returns { items: [], job: () => Promise, stopRecursion: boolean }
336
- */
337
- function prepareRenderItem(node, config, domOrder, pptx, effectiveZIndex, computedStyle) {
338
- // 1. Text Node Handling
339
- if (node.nodeType === 3) {
340
- const textContent = node.nodeValue.trim();
341
- if (!textContent) return null;
342
-
343
- const parent = node.parentElement;
344
- if (!parent) return null;
345
-
346
- if (isTextContainer(parent)) return null; // Parent handles it
347
-
348
- const range = document.createRange();
349
- range.selectNode(node);
350
- const rect = range.getBoundingClientRect();
351
- range.detach();
352
-
353
- const style = window.getComputedStyle(parent);
354
- const widthPx = rect.width;
355
- const heightPx = rect.height;
356
- const unrotatedW = widthPx * PX_TO_INCH * config.scale;
357
- const unrotatedH = heightPx * PX_TO_INCH * config.scale;
358
-
359
- const x = config.offX + (rect.left - config.rootX) * PX_TO_INCH * config.scale;
360
- const y = config.offY + (rect.top - config.rootY) * PX_TO_INCH * config.scale;
361
-
362
- return {
363
- items: [
364
- {
365
- type: 'text',
366
- zIndex: effectiveZIndex,
367
- domOrder,
368
- textParts: [
369
- {
370
- text: textContent,
371
- options: getTextStyle(style, config.scale),
372
- },
373
- ],
374
- options: { x, y, w: unrotatedW, h: unrotatedH, margin: 0, autoFit: false },
375
- },
376
- ],
377
- stopRecursion: false,
378
- };
379
- }
380
-
381
- if (node.nodeType !== 1) return null;
382
- const style = computedStyle; // Use pre-computed style
383
-
384
- const rect = node.getBoundingClientRect();
385
- if (rect.width < 0.5 || rect.height < 0.5) return null;
386
-
387
- const zIndex = effectiveZIndex;
388
- const rotation = getRotation(style.transform);
389
- const elementOpacity = parseFloat(style.opacity);
390
- const safeOpacity = isNaN(elementOpacity) ? 1 : elementOpacity;
391
-
392
- const widthPx = node.offsetWidth || rect.width;
393
- const heightPx = node.offsetHeight || rect.height;
394
- const unrotatedW = widthPx * PX_TO_INCH * config.scale;
395
- const unrotatedH = heightPx * PX_TO_INCH * config.scale;
396
- const centerX = rect.left + rect.width / 2;
397
- const centerY = rect.top + rect.height / 2;
398
-
399
- let x = config.offX + (centerX - config.rootX) * PX_TO_INCH * config.scale - unrotatedW / 2;
400
- let y = config.offY + (centerY - config.rootY) * PX_TO_INCH * config.scale - unrotatedH / 2;
401
- let w = unrotatedW;
402
- let h = unrotatedH;
403
-
404
- const items = [];
405
-
406
- // --- ASYNC JOB: SVG Tags ---
407
- if (node.nodeName.toUpperCase() === 'SVG') {
408
- const item = {
409
- type: 'image',
410
- zIndex,
411
- domOrder,
412
- options: { data: null, x, y, w, h, rotate: rotation },
413
- };
414
-
415
- const job = async () => {
416
- const processed = await svgToPng(node);
417
- if (processed) item.options.data = processed;
418
- else item.skip = true;
419
- };
420
-
421
- return { items: [item], job, stopRecursion: true };
422
- }
423
-
424
- // --- ASYNC JOB: IMG Tags ---
425
- if (node.tagName === 'IMG') {
426
- let radii = {
427
- tl: parseFloat(style.borderTopLeftRadius) || 0,
428
- tr: parseFloat(style.borderTopRightRadius) || 0,
429
- br: parseFloat(style.borderBottomRightRadius) || 0,
430
- bl: parseFloat(style.borderBottomLeftRadius) || 0,
431
- };
432
-
433
- const hasAnyRadius = radii.tl > 0 || radii.tr > 0 || radii.br > 0 || radii.bl > 0;
434
- if (!hasAnyRadius) {
435
- const parent = node.parentElement;
436
- const parentStyle = window.getComputedStyle(parent);
437
- if (parentStyle.overflow !== 'visible') {
438
- const pRadii = {
439
- tl: parseFloat(parentStyle.borderTopLeftRadius) || 0,
440
- tr: parseFloat(parentStyle.borderTopRightRadius) || 0,
441
- br: parseFloat(parentStyle.borderBottomRightRadius) || 0,
442
- bl: parseFloat(parentStyle.borderBottomLeftRadius) || 0,
443
- };
444
- const pRect = parent.getBoundingClientRect();
445
- if (Math.abs(pRect.width - rect.width) < 5 && Math.abs(pRect.height - rect.height) < 5) {
446
- radii = pRadii;
447
- }
448
- }
449
- }
450
-
451
- const item = {
452
- type: 'image',
453
- zIndex,
454
- domOrder,
455
- options: { x, y, w, h, rotate: rotation, data: null },
456
- };
457
-
458
- const job = async () => {
459
- const processed = await getProcessedImage(node.src, widthPx, heightPx, radii);
460
- if (processed) item.options.data = processed;
461
- else item.skip = true;
462
- };
463
-
464
- return { items: [item], job, stopRecursion: true };
465
- }
466
-
467
- // --- ASYNC JOB: Icons and Other Elements ---
468
- if (isIconElement(node)) {
469
- const item = {
470
- type: 'image',
471
- zIndex,
472
- domOrder,
473
- options: { x, y, w, h, rotate: rotation, data: null },
474
- };
475
- const job = async () => {
476
- const pngData = await elementToCanvasImage(node, widthPx, heightPx);
477
- if (pngData) item.options.data = pngData;
478
- else item.skip = true;
479
- };
480
- return { items: [item], job, stopRecursion: true };
481
- }
482
-
483
- // Radii logic
484
- const borderRadiusValue = parseFloat(style.borderRadius) || 0;
485
- const borderBottomLeftRadius = parseFloat(style.borderBottomLeftRadius) || 0;
486
- const borderBottomRightRadius = parseFloat(style.borderBottomRightRadius) || 0;
487
- const borderTopLeftRadius = parseFloat(style.borderTopLeftRadius) || 0;
488
- const borderTopRightRadius = parseFloat(style.borderTopRightRadius) || 0;
489
-
490
- const hasPartialBorderRadius =
491
- (borderBottomLeftRadius > 0 && borderBottomLeftRadius !== borderRadiusValue) ||
492
- (borderBottomRightRadius > 0 && borderBottomRightRadius !== borderRadiusValue) ||
493
- (borderTopLeftRadius > 0 && borderTopLeftRadius !== borderRadiusValue) ||
494
- (borderTopRightRadius > 0 && borderTopRightRadius !== borderRadiusValue) ||
495
- (borderRadiusValue === 0 &&
496
- (borderBottomLeftRadius ||
497
- borderBottomRightRadius ||
498
- borderTopLeftRadius ||
499
- borderTopRightRadius));
500
-
501
- // --- ASYNC JOB: Clipped Divs via Canvas ---
502
- if (hasPartialBorderRadius && isClippedByParent(node)) {
503
- const marginLeft = parseFloat(style.marginLeft) || 0;
504
- const marginTop = parseFloat(style.marginTop) || 0;
505
- x += marginLeft * PX_TO_INCH * config.scale;
506
- y += marginTop * PX_TO_INCH * config.scale;
507
-
508
- const item = {
509
- type: 'image',
510
- zIndex,
511
- domOrder,
512
- options: { x, y, w, h, rotate: rotation, data: null },
513
- };
514
-
515
- const job = async () => {
516
- const canvasImageData = await elementToCanvasImage(node, widthPx, heightPx);
517
- if (canvasImageData) item.options.data = canvasImageData;
518
- else item.skip = true;
519
- };
520
-
521
- return { items: [item], job, stopRecursion: true };
522
- }
523
-
524
- // --- SYNC: Standard CSS Extraction ---
525
- const bgColorObj = parseColor(style.backgroundColor);
526
- const bgClip = style.webkitBackgroundClip || style.backgroundClip;
527
- const isBgClipText = bgClip === 'text';
528
- const hasGradient =
529
- !isBgClipText && style.backgroundImage && style.backgroundImage.includes('linear-gradient');
530
-
531
- const borderColorObj = parseColor(style.borderColor);
532
- const borderWidth = parseFloat(style.borderWidth);
533
- const hasBorder = borderWidth > 0 && borderColorObj.hex;
534
-
535
- const borderInfo = getBorderInfo(style, config.scale);
536
- const hasUniformBorder = borderInfo.type === 'uniform';
537
- const hasCompositeBorder = borderInfo.type === 'composite';
538
-
539
- const shadowStr = style.boxShadow;
540
- const hasShadow = shadowStr && shadowStr !== 'none';
541
- const softEdge = getSoftEdges(style.filter, config.scale);
542
-
543
- let isImageWrapper = false;
544
- const imgChild = Array.from(node.children).find((c) => c.tagName === 'IMG');
545
- if (imgChild) {
546
- const childW = imgChild.offsetWidth || imgChild.getBoundingClientRect().width;
547
- const childH = imgChild.offsetHeight || imgChild.getBoundingClientRect().height;
548
- if (childW >= widthPx - 2 && childH >= heightPx - 2) isImageWrapper = true;
549
- }
550
-
551
- let textPayload = null;
552
- const isText = isTextContainer(node);
553
-
554
- if (isText) {
555
- const textParts = [];
556
- const isList = style.display === 'list-item';
557
- if (isList) {
558
- const fontSizePt = parseFloat(style.fontSize) * 0.75 * config.scale;
559
- const bulletShift = (parseFloat(style.fontSize) || 16) * PX_TO_INCH * config.scale * 1.5;
560
- x -= bulletShift;
561
- w += bulletShift;
562
- textParts.push({
563
- text: ' ',
564
- options: {
565
- color: parseColor(style.color).hex || '000000',
566
- fontSize: fontSizePt,
567
- },
568
- });
569
- }
570
-
571
- node.childNodes.forEach((child, index) => {
572
- let textVal = child.nodeType === 3 ? child.nodeValue : child.textContent;
573
- let nodeStyle = child.nodeType === 1 ? window.getComputedStyle(child) : style;
574
- textVal = textVal.replace(/[\n\r\t]+/g, ' ').replace(/\s{2,}/g, ' ');
575
- if (index === 0 && !isList) textVal = textVal.trimStart();
576
- else if (index === 0) textVal = textVal.trimStart();
577
- if (index === node.childNodes.length - 1) textVal = textVal.trimEnd();
578
- if (nodeStyle.textTransform === 'uppercase') textVal = textVal.toUpperCase();
579
- if (nodeStyle.textTransform === 'lowercase') textVal = textVal.toLowerCase();
580
-
581
- if (textVal.length > 0) {
582
- textParts.push({
583
- text: textVal,
584
- options: getTextStyle(nodeStyle, config.scale),
585
- });
586
- }
587
- });
588
-
589
- if (textParts.length > 0) {
590
- let align = style.textAlign || 'left';
591
- if (align === 'start') align = 'left';
592
- if (align === 'end') align = 'right';
593
- let valign = 'top';
594
- if (style.alignItems === 'center') valign = 'middle';
595
- if (style.justifyContent === 'center' && style.display.includes('flex')) align = 'center';
596
-
597
- const pt = parseFloat(style.paddingTop) || 0;
598
- const pb = parseFloat(style.paddingBottom) || 0;
599
- if (Math.abs(pt - pb) < 2 && bgColorObj.hex) valign = 'middle';
600
-
601
- let padding = getPadding(style, config.scale);
602
- if (align === 'center' && valign === 'middle') padding = [0, 0, 0, 0];
603
-
604
- textPayload = { text: textParts, align, valign, inset: padding };
605
- }
606
- }
607
-
608
- if (hasGradient || (softEdge && bgColorObj.hex && !isImageWrapper)) {
609
- let bgData = null;
610
- let padIn = 0;
611
- if (softEdge) {
612
- const svgInfo = generateBlurredSVG(
613
- widthPx,
614
- heightPx,
615
- bgColorObj.hex,
616
- borderRadiusValue,
617
- softEdge
618
- );
619
- bgData = svgInfo.data;
620
- padIn = svgInfo.padding * PX_TO_INCH * config.scale;
621
- } else {
622
- bgData = generateGradientSVG(
623
- widthPx,
624
- heightPx,
625
- style.backgroundImage,
626
- borderRadiusValue,
627
- hasBorder ? { color: borderColorObj.hex, width: borderWidth } : null
628
- );
629
- }
630
-
631
- if (bgData) {
632
- items.push({
633
- type: 'image',
634
- zIndex,
635
- domOrder,
636
- options: {
637
- data: bgData,
638
- x: x - padIn,
639
- y: y - padIn,
640
- w: w + padIn * 2,
641
- h: h + padIn * 2,
642
- rotate: rotation,
643
- },
644
- });
645
- }
646
-
647
- if (textPayload) {
648
- items.push({
649
- type: 'text',
650
- zIndex: zIndex + 1,
651
- domOrder,
652
- textParts: textPayload.text,
653
- options: {
654
- x,
655
- y,
656
- w,
657
- h,
658
- align: textPayload.align,
659
- valign: textPayload.valign,
660
- inset: textPayload.inset,
661
- rotate: rotation,
662
- margin: 0,
663
- wrap: true,
664
- autoFit: false,
665
- },
666
- });
667
- }
668
- if (hasCompositeBorder) {
669
- const borderItems = createCompositeBorderItems(
670
- borderInfo.sides,
671
- x,
672
- y,
673
- w,
674
- h,
675
- config.scale,
676
- zIndex,
677
- domOrder
678
- );
679
- items.push(...borderItems);
680
- }
681
- } else if (
682
- (bgColorObj.hex && !isImageWrapper) ||
683
- hasUniformBorder ||
684
- hasCompositeBorder ||
685
- hasShadow ||
686
- textPayload
687
- ) {
688
- const finalAlpha = safeOpacity * bgColorObj.opacity;
689
- const transparency = (1 - finalAlpha) * 100;
690
- const useSolidFill = bgColorObj.hex && !isImageWrapper;
691
-
692
- if (hasPartialBorderRadius && useSolidFill && !textPayload) {
693
- const shapeSvg = generateCustomShapeSVG(
694
- widthPx,
695
- heightPx,
696
- bgColorObj.hex,
697
- bgColorObj.opacity,
698
- {
699
- tl: parseFloat(style.borderTopLeftRadius) || 0,
700
- tr: parseFloat(style.borderTopRightRadius) || 0,
701
- br: parseFloat(style.borderBottomRightRadius) || 0,
702
- bl: parseFloat(style.borderBottomLeftRadius) || 0,
703
- }
704
- );
705
-
706
- items.push({
707
- type: 'image',
708
- zIndex,
709
- domOrder,
710
- options: { data: shapeSvg, x, y, w, h, rotate: rotation },
711
- });
712
- } else {
713
- const shapeOpts = {
714
- x,
715
- y,
716
- w,
717
- h,
718
- rotate: rotation,
719
- fill: useSolidFill
720
- ? { color: bgColorObj.hex, transparency: transparency }
721
- : { type: 'none' },
722
- line: hasUniformBorder ? borderInfo.options : null,
723
- };
724
-
725
- if (hasShadow) shapeOpts.shadow = getVisibleShadow(shadowStr, config.scale);
726
-
727
- const borderRadius = parseFloat(style.borderRadius) || 0;
728
- const aspectRatio = Math.max(widthPx, heightPx) / Math.min(widthPx, heightPx);
729
- const isCircle = aspectRatio < 1.1 && borderRadius >= Math.min(widthPx, heightPx) / 2 - 1;
730
-
731
- let shapeType = pptx.ShapeType.rect;
732
- if (isCircle) shapeType = pptx.ShapeType.ellipse;
733
- else if (borderRadius > 0) {
734
- shapeType = pptx.ShapeType.roundRect;
735
- shapeOpts.rectRadius = Math.min(0.5, borderRadius / Math.min(widthPx, heightPx));
736
- }
737
-
738
- if (textPayload) {
739
- const textOptions = {
740
- shape: shapeType,
741
- ...shapeOpts,
742
- align: textPayload.align,
743
- valign: textPayload.valign,
744
- inset: textPayload.inset,
745
- margin: 0,
746
- wrap: true,
747
- autoFit: false,
748
- };
749
- items.push({
750
- type: 'text',
751
- zIndex,
752
- domOrder,
753
- textParts: textPayload.text,
754
- options: textOptions,
755
- });
756
- } else if (!hasPartialBorderRadius) {
757
- items.push({
758
- type: 'shape',
759
- zIndex,
760
- domOrder,
761
- shapeType,
762
- options: shapeOpts,
763
- });
764
- }
765
- }
766
-
767
- if (hasCompositeBorder) {
768
- const borderSvgData = generateCompositeBorderSVG(
769
- widthPx,
770
- heightPx,
771
- borderRadiusValue,
772
- borderInfo.sides
773
- );
774
- if (borderSvgData) {
775
- items.push({
776
- type: 'image',
777
- zIndex: zIndex + 1,
778
- domOrder,
779
- options: { data: borderSvgData, x, y, w, h, rotate: rotation },
780
- });
781
- }
782
- }
783
- }
784
-
785
- return { items, stopRecursion: !!textPayload };
786
- }
787
-
788
- function createCompositeBorderItems(sides, x, y, w, h, scale, zIndex, domOrder) {
789
- const items = [];
790
- const pxToInch = 1 / 96;
791
- const common = { zIndex: zIndex + 1, domOrder, shapeType: 'rect' };
792
-
793
- if (sides.top.width > 0)
794
- items.push({
795
- ...common,
796
- options: { x, y, w, h: sides.top.width * pxToInch * scale, fill: { color: sides.top.color } },
797
- });
798
- if (sides.right.width > 0)
799
- items.push({
800
- ...common,
801
- options: {
802
- x: x + w - sides.right.width * pxToInch * scale,
803
- y,
804
- w: sides.right.width * pxToInch * scale,
805
- h,
806
- fill: { color: sides.right.color },
807
- },
808
- });
809
- if (sides.bottom.width > 0)
810
- items.push({
811
- ...common,
812
- options: {
813
- x,
814
- y: y + h - sides.bottom.width * pxToInch * scale,
815
- w,
816
- h: sides.bottom.width * pxToInch * scale,
817
- fill: { color: sides.bottom.color },
818
- },
819
- });
820
- if (sides.left.width > 0)
821
- items.push({
822
- ...common,
823
- options: {
824
- x,
825
- y,
826
- w: sides.left.width * pxToInch * scale,
827
- h,
828
- fill: { color: sides.left.color },
829
- },
830
- });
831
-
832
- return items;
833
- }
1
+ // src/index.js
2
+ import * as PptxGenJSImport from 'pptxgenjs';
3
+ import html2canvas from 'html2canvas';
4
+ import { PPTXEmbedFonts } from './font-embedder.js';
5
+ import JSZip from 'jszip';
6
+
7
+ // Normalize import
8
+ const PptxGenJS = PptxGenJSImport?.default ?? PptxGenJSImport;
9
+
10
+ import {
11
+ parseColor,
12
+ getTextStyle,
13
+ isTextContainer,
14
+ getVisibleShadow,
15
+ generateGradientSVG,
16
+ getRotation,
17
+ svgToPng,
18
+ getPadding,
19
+ getSoftEdges,
20
+ generateBlurredSVG,
21
+ getBorderInfo,
22
+ generateCompositeBorderSVG,
23
+ isClippedByParent,
24
+ generateCustomShapeSVG,
25
+ getUsedFontFamilies,
26
+ getAutoDetectedFonts,
27
+ } from './utils.js';
28
+ import { getProcessedImage } from './image-processor.js';
29
+
30
+ const PPI = 96;
31
+ const PX_TO_INCH = 1 / PPI;
32
+
33
+ /**
34
+ * Main export function.
35
+ * @param {HTMLElement | string | Array<HTMLElement | string>} target
36
+ * @param {Object} options
37
+ * @param {string} [options.fileName]
38
+ * @param {Array<{name: string, url: string}>} [options.fonts] - Explicit fonts
39
+ * @param {boolean} [options.autoEmbedFonts=true] - Attempt to auto-detect and embed used fonts
40
+ */
41
+ export async function exportToPptx(target, options = {}) {
42
+ const resolvePptxConstructor = (pkg) => {
43
+ if (!pkg) return null;
44
+ if (typeof pkg === 'function') return pkg;
45
+ if (pkg && typeof pkg.default === 'function') return pkg.default;
46
+ if (pkg && typeof pkg.PptxGenJS === 'function') return pkg.PptxGenJS;
47
+ if (pkg && pkg.PptxGenJS && typeof pkg.PptxGenJS.default === 'function')
48
+ return pkg.PptxGenJS.default;
49
+ return null;
50
+ };
51
+
52
+ const PptxConstructor = resolvePptxConstructor(PptxGenJS);
53
+ if (!PptxConstructor) throw new Error('PptxGenJS constructor not found.');
54
+ const pptx = new PptxConstructor();
55
+ pptx.layout = 'LAYOUT_16x9';
56
+
57
+ const elements = Array.isArray(target) ? target : [target];
58
+
59
+ for (const el of elements) {
60
+ const root = typeof el === 'string' ? document.querySelector(el) : el;
61
+ if (!root) {
62
+ console.warn('Element not found, skipping slide:', el);
63
+ continue;
64
+ }
65
+ const slide = pptx.addSlide();
66
+ await processSlide(root, slide, pptx);
67
+ }
68
+
69
+ // 3. Font Embedding Logic
70
+ let finalBlob;
71
+ let fontsToEmbed = options.fonts || [];
72
+
73
+ if (options.autoEmbedFonts) {
74
+ // A. Scan DOM for used font families
75
+ const usedFamilies = getUsedFontFamilies(elements);
76
+
77
+ // B. Scan CSS for URLs matches
78
+ const detectedFonts = await getAutoDetectedFonts(usedFamilies);
79
+
80
+ // C. Merge (Avoid duplicates)
81
+ const explicitNames = new Set(fontsToEmbed.map((f) => f.name));
82
+ for (const autoFont of detectedFonts) {
83
+ if (!explicitNames.has(autoFont.name)) {
84
+ fontsToEmbed.push(autoFont);
85
+ }
86
+ }
87
+
88
+ if (detectedFonts.length > 0) {
89
+ console.log(
90
+ 'Auto-detected fonts:',
91
+ detectedFonts.map((f) => f.name)
92
+ );
93
+ }
94
+ }
95
+
96
+ if (fontsToEmbed.length > 0) {
97
+ // Generate initial PPTX
98
+ const initialBlob = await pptx.write({ outputType: 'blob' });
99
+
100
+ // Load into Embedder
101
+ const zip = await JSZip.loadAsync(initialBlob);
102
+ const embedder = new PPTXEmbedFonts();
103
+ await embedder.loadZip(zip);
104
+
105
+ // Fetch and Embed
106
+ for (const fontCfg of fontsToEmbed) {
107
+ try {
108
+ const response = await fetch(fontCfg.url);
109
+ if (!response.ok) throw new Error(`Failed to fetch ${fontCfg.url}`);
110
+ const buffer = await response.arrayBuffer();
111
+
112
+ // Infer type
113
+ const ext = fontCfg.url.split('.').pop().split(/[?#]/)[0].toLowerCase();
114
+ let type = 'ttf';
115
+ if (['woff', 'otf'].includes(ext)) type = ext;
116
+
117
+ await embedder.addFont(fontCfg.name, buffer, type);
118
+ } catch (e) {
119
+ console.warn(`Failed to embed font: ${fontCfg.name} (${fontCfg.url})`, e);
120
+ }
121
+ }
122
+
123
+ await embedder.updateFiles();
124
+ finalBlob = await embedder.generateBlob();
125
+ } else {
126
+ // No fonts to embed
127
+ finalBlob = await pptx.write({ outputType: 'blob' });
128
+ }
129
+
130
+ // 4. Download
131
+ const fileName = options.fileName || 'export.pptx';
132
+ const url = URL.createObjectURL(finalBlob);
133
+ const a = document.createElement('a');
134
+ a.href = url;
135
+ a.download = fileName;
136
+ document.body.appendChild(a);
137
+ a.click();
138
+ document.body.removeChild(a);
139
+ URL.revokeObjectURL(url);
140
+ }
141
+
142
+ /**
143
+ * Worker function to process a single DOM element into a single PPTX slide.
144
+ * @param {HTMLElement} root - The root element for this slide.
145
+ * @param {PptxGenJS.Slide} slide - The PPTX slide object to add content to.
146
+ * @param {PptxGenJS} pptx - The main PPTX instance.
147
+ */
148
+ async function processSlide(root, slide, pptx) {
149
+ const rootRect = root.getBoundingClientRect();
150
+ const PPTX_WIDTH_IN = 10;
151
+ const PPTX_HEIGHT_IN = 5.625;
152
+
153
+ const contentWidthIn = rootRect.width * PX_TO_INCH;
154
+ const contentHeightIn = rootRect.height * PX_TO_INCH;
155
+ const scale = Math.min(PPTX_WIDTH_IN / contentWidthIn, PPTX_HEIGHT_IN / contentHeightIn);
156
+
157
+ const layoutConfig = {
158
+ rootX: rootRect.x,
159
+ rootY: rootRect.y,
160
+ scale: scale,
161
+ offX: (PPTX_WIDTH_IN - contentWidthIn * scale) / 2,
162
+ offY: (PPTX_HEIGHT_IN - contentHeightIn * scale) / 2,
163
+ };
164
+
165
+ const renderQueue = [];
166
+ const asyncTasks = []; // Queue for heavy operations (Images, Canvas)
167
+ let domOrderCounter = 0;
168
+
169
+ // Sync Traversal Function
170
+ function collect(node, parentZIndex) {
171
+ const order = domOrderCounter++;
172
+
173
+ let currentZ = parentZIndex;
174
+ let nodeStyle = null;
175
+ const nodeType = node.nodeType;
176
+
177
+ if (nodeType === 1) {
178
+ nodeStyle = window.getComputedStyle(node);
179
+ // Optimization: Skip completely hidden elements immediately
180
+ if (
181
+ nodeStyle.display === 'none' ||
182
+ nodeStyle.visibility === 'hidden' ||
183
+ nodeStyle.opacity === '0'
184
+ ) {
185
+ return;
186
+ }
187
+ if (nodeStyle.zIndex !== 'auto') {
188
+ currentZ = parseInt(nodeStyle.zIndex);
189
+ }
190
+ }
191
+
192
+ // Prepare the item. If it needs async work, it returns a 'job'
193
+ const result = prepareRenderItem(
194
+ node,
195
+ { ...layoutConfig, root },
196
+ order,
197
+ pptx,
198
+ currentZ,
199
+ nodeStyle
200
+ );
201
+
202
+ if (result) {
203
+ if (result.items) {
204
+ // Push items immediately to queue (data might be missing but filled later)
205
+ renderQueue.push(...result.items);
206
+ }
207
+ if (result.job) {
208
+ // Push the promise-returning function to the task list
209
+ asyncTasks.push(result.job);
210
+ }
211
+ if (result.stopRecursion) return;
212
+ }
213
+
214
+ // Recurse children synchronously
215
+ const childNodes = node.childNodes;
216
+ for (let i = 0; i < childNodes.length; i++) {
217
+ collect(childNodes[i], currentZ);
218
+ }
219
+ }
220
+
221
+ // 1. Traverse and build the structure (Fast)
222
+ collect(root, 0);
223
+
224
+ // 2. Execute all heavy tasks in parallel (Fast)
225
+ if (asyncTasks.length > 0) {
226
+ await Promise.all(asyncTasks.map((task) => task()));
227
+ }
228
+
229
+ // 3. Cleanup and Sort
230
+ // Remove items that failed to generate data (marked with skip)
231
+ const finalQueue = renderQueue.filter(
232
+ (item) => !item.skip && (item.type !== 'image' || item.options.data)
233
+ );
234
+
235
+ finalQueue.sort((a, b) => {
236
+ if (a.zIndex !== b.zIndex) return a.zIndex - b.zIndex;
237
+ return a.domOrder - b.domOrder;
238
+ });
239
+
240
+ // 4. Add to Slide
241
+ for (const item of finalQueue) {
242
+ if (item.type === 'shape') slide.addShape(item.shapeType, item.options);
243
+ if (item.type === 'image') slide.addImage(item.options);
244
+ if (item.type === 'text') slide.addText(item.textParts, item.options);
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Optimized html2canvas wrapper
250
+ * Includes fix for cropped icons by adjusting styles in the cloned document.
251
+ */
252
+ async function elementToCanvasImage(node, widthPx, heightPx) {
253
+ return new Promise((resolve) => {
254
+ // 1. Assign a temp ID to locate the node inside the cloned document
255
+ const originalId = node.id;
256
+ const tempId = 'pptx-capture-' + Math.random().toString(36).substr(2, 9);
257
+ node.id = tempId;
258
+
259
+ const width = Math.max(Math.ceil(widthPx), 1);
260
+ const height = Math.max(Math.ceil(heightPx), 1);
261
+ const style = window.getComputedStyle(node);
262
+
263
+ html2canvas(node, {
264
+ backgroundColor: null,
265
+ logging: false,
266
+ scale: 3, // Higher scale for sharper icons
267
+ useCORS: true, // critical for external fonts/images
268
+ onclone: (clonedDoc) => {
269
+ const clonedNode = clonedDoc.getElementById(tempId);
270
+ if (clonedNode) {
271
+ // --- FIX: PREVENT ICON CLIPPING ---
272
+ // 1. Force overflow visible so glyphs bleeding out aren't cut
273
+ clonedNode.style.overflow = 'visible';
274
+
275
+ // 2. Adjust alignment for Icons to prevent baseline clipping
276
+ // (Applies to <i>, <span>, or standard icon classes)
277
+ const tag = clonedNode.tagName;
278
+ if (tag === 'I' || tag === 'SPAN' || clonedNode.className.includes('fa-')) {
279
+ // Flex center helps align the glyph exactly in the middle of the box
280
+ // preventing top/bottom cropping due to line-height mismatches.
281
+ clonedNode.style.display = 'inline-flex';
282
+ clonedNode.style.justifyContent = 'center';
283
+ clonedNode.style.alignItems = 'center';
284
+
285
+ // Remove margins that might offset the capture
286
+ clonedNode.style.margin = '0';
287
+
288
+ // Ensure the font fits
289
+ clonedNode.style.lineHeight = '1';
290
+ clonedNode.style.verticalAlign = 'middle';
291
+ }
292
+ }
293
+ },
294
+ })
295
+ .then((canvas) => {
296
+ // Restore the original ID
297
+ if (originalId) node.id = originalId;
298
+ else node.removeAttribute('id');
299
+
300
+ const destCanvas = document.createElement('canvas');
301
+ destCanvas.width = width;
302
+ destCanvas.height = height;
303
+ const ctx = destCanvas.getContext('2d');
304
+
305
+ // Draw captured canvas.
306
+ // We simply draw it to fill the box. Since we centered it in 'onclone',
307
+ // the glyph should now be visible within the bounds.
308
+ ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, width, height);
309
+
310
+ // --- Border Radius Clipping (Existing Logic) ---
311
+ let tl = parseFloat(style.borderTopLeftRadius) || 0;
312
+ let tr = parseFloat(style.borderTopRightRadius) || 0;
313
+ let br = parseFloat(style.borderBottomRightRadius) || 0;
314
+ let bl = parseFloat(style.borderBottomLeftRadius) || 0;
315
+
316
+ const f = Math.min(
317
+ width / (tl + tr) || Infinity,
318
+ height / (tr + br) || Infinity,
319
+ width / (br + bl) || Infinity,
320
+ height / (bl + tl) || Infinity
321
+ );
322
+
323
+ if (f < 1) {
324
+ tl *= f;
325
+ tr *= f;
326
+ br *= f;
327
+ bl *= f;
328
+ }
329
+
330
+ if (tl + tr + br + bl > 0) {
331
+ ctx.globalCompositeOperation = 'destination-in';
332
+ ctx.beginPath();
333
+ ctx.moveTo(tl, 0);
334
+ ctx.lineTo(width - tr, 0);
335
+ ctx.arcTo(width, 0, width, tr, tr);
336
+ ctx.lineTo(width, height - br);
337
+ ctx.arcTo(width, height, width - br, height, br);
338
+ ctx.lineTo(bl, height);
339
+ ctx.arcTo(0, height, 0, height - bl, bl);
340
+ ctx.lineTo(0, tl);
341
+ ctx.arcTo(0, 0, tl, 0, tl);
342
+ ctx.closePath();
343
+ ctx.fill();
344
+ }
345
+
346
+ resolve(destCanvas.toDataURL('image/png'));
347
+ })
348
+ .catch((e) => {
349
+ if (originalId) node.id = originalId;
350
+ else node.removeAttribute('id');
351
+ console.warn('Canvas capture failed for node', node, e);
352
+ resolve(null);
353
+ });
354
+ });
355
+ }
356
+
357
+ /**
358
+ * Helper to identify elements that should be rendered as icons (Images).
359
+ * Detects Custom Elements AND generic tags (<i>, <span>) with icon classes/pseudo-elements.
360
+ */
361
+ function isIconElement(node) {
362
+ // 1. Custom Elements (hyphenated tags) or Explicit Library Tags
363
+ const tag = node.tagName.toUpperCase();
364
+ if (
365
+ tag.includes('-') ||
366
+ [
367
+ 'MATERIAL-ICON',
368
+ 'ICONIFY-ICON',
369
+ 'REMIX-ICON',
370
+ 'ION-ICON',
371
+ 'EVA-ICON',
372
+ 'BOX-ICON',
373
+ 'FA-ICON',
374
+ ].includes(tag)
375
+ ) {
376
+ return true;
377
+ }
378
+
379
+ // 2. Class-based Icons (FontAwesome, Bootstrap, Material symbols) on <i> or <span>
380
+ if (tag === 'I' || tag === 'SPAN') {
381
+ const cls = node.getAttribute('class') || '';
382
+ if (
383
+ typeof cls === 'string' &&
384
+ (cls.includes('fa-') ||
385
+ cls.includes('fas') ||
386
+ cls.includes('far') ||
387
+ cls.includes('fab') ||
388
+ cls.includes('bi-') ||
389
+ cls.includes('material-icons') ||
390
+ cls.includes('icon'))
391
+ ) {
392
+ // Double-check: Must have pseudo-element content to be a CSS icon
393
+ const before = window.getComputedStyle(node, '::before').content;
394
+ const after = window.getComputedStyle(node, '::after').content;
395
+ const hasContent = (c) => c && c !== 'none' && c !== 'normal' && c !== '""';
396
+
397
+ if (hasContent(before) || hasContent(after)) return true;
398
+ }
399
+ }
400
+
401
+ return false;
402
+ }
403
+
404
+ /**
405
+ * Replaces createRenderItem.
406
+ * Returns { items: [], job: () => Promise, stopRecursion: boolean }
407
+ */
408
+ function prepareRenderItem(node, config, domOrder, pptx, effectiveZIndex, computedStyle) {
409
+ // 1. Text Node Handling
410
+ if (node.nodeType === 3) {
411
+ const textContent = node.nodeValue.trim();
412
+ if (!textContent) return null;
413
+
414
+ const parent = node.parentElement;
415
+ if (!parent) return null;
416
+
417
+ if (isTextContainer(parent)) return null; // Parent handles it
418
+
419
+ const range = document.createRange();
420
+ range.selectNode(node);
421
+ const rect = range.getBoundingClientRect();
422
+ range.detach();
423
+
424
+ const style = window.getComputedStyle(parent);
425
+ const widthPx = rect.width;
426
+ const heightPx = rect.height;
427
+ const unrotatedW = widthPx * PX_TO_INCH * config.scale;
428
+ const unrotatedH = heightPx * PX_TO_INCH * config.scale;
429
+
430
+ const x = config.offX + (rect.left - config.rootX) * PX_TO_INCH * config.scale;
431
+ const y = config.offY + (rect.top - config.rootY) * PX_TO_INCH * config.scale;
432
+
433
+ return {
434
+ items: [
435
+ {
436
+ type: 'text',
437
+ zIndex: effectiveZIndex,
438
+ domOrder,
439
+ textParts: [
440
+ {
441
+ text: textContent,
442
+ options: getTextStyle(style, config.scale),
443
+ },
444
+ ],
445
+ options: { x, y, w: unrotatedW, h: unrotatedH, margin: 0, autoFit: false },
446
+ },
447
+ ],
448
+ stopRecursion: false,
449
+ };
450
+ }
451
+
452
+ if (node.nodeType !== 1) return null;
453
+ const style = computedStyle; // Use pre-computed style
454
+
455
+ const rect = node.getBoundingClientRect();
456
+ if (rect.width < 0.5 || rect.height < 0.5) return null;
457
+
458
+ const zIndex = effectiveZIndex;
459
+ const rotation = getRotation(style.transform);
460
+ const elementOpacity = parseFloat(style.opacity);
461
+ const safeOpacity = isNaN(elementOpacity) ? 1 : elementOpacity;
462
+
463
+ const widthPx = node.offsetWidth || rect.width;
464
+ const heightPx = node.offsetHeight || rect.height;
465
+ const unrotatedW = widthPx * PX_TO_INCH * config.scale;
466
+ const unrotatedH = heightPx * PX_TO_INCH * config.scale;
467
+ const centerX = rect.left + rect.width / 2;
468
+ const centerY = rect.top + rect.height / 2;
469
+
470
+ let x = config.offX + (centerX - config.rootX) * PX_TO_INCH * config.scale - unrotatedW / 2;
471
+ let y = config.offY + (centerY - config.rootY) * PX_TO_INCH * config.scale - unrotatedH / 2;
472
+ let w = unrotatedW;
473
+ let h = unrotatedH;
474
+
475
+ const items = [];
476
+
477
+ // --- ASYNC JOB: SVG Tags ---
478
+ if (node.nodeName.toUpperCase() === 'SVG') {
479
+ const item = {
480
+ type: 'image',
481
+ zIndex,
482
+ domOrder,
483
+ options: { data: null, x, y, w, h, rotate: rotation },
484
+ };
485
+
486
+ const job = async () => {
487
+ const processed = await svgToPng(node);
488
+ if (processed) item.options.data = processed;
489
+ else item.skip = true;
490
+ };
491
+
492
+ return { items: [item], job, stopRecursion: true };
493
+ }
494
+
495
+ // --- ASYNC JOB: IMG Tags ---
496
+ if (node.tagName === 'IMG') {
497
+ let radii = {
498
+ tl: parseFloat(style.borderTopLeftRadius) || 0,
499
+ tr: parseFloat(style.borderTopRightRadius) || 0,
500
+ br: parseFloat(style.borderBottomRightRadius) || 0,
501
+ bl: parseFloat(style.borderBottomLeftRadius) || 0,
502
+ };
503
+
504
+ const hasAnyRadius = radii.tl > 0 || radii.tr > 0 || radii.br > 0 || radii.bl > 0;
505
+ if (!hasAnyRadius) {
506
+ const parent = node.parentElement;
507
+ const parentStyle = window.getComputedStyle(parent);
508
+ if (parentStyle.overflow !== 'visible') {
509
+ const pRadii = {
510
+ tl: parseFloat(parentStyle.borderTopLeftRadius) || 0,
511
+ tr: parseFloat(parentStyle.borderTopRightRadius) || 0,
512
+ br: parseFloat(parentStyle.borderBottomRightRadius) || 0,
513
+ bl: parseFloat(parentStyle.borderBottomLeftRadius) || 0,
514
+ };
515
+ const pRect = parent.getBoundingClientRect();
516
+ if (Math.abs(pRect.width - rect.width) < 5 && Math.abs(pRect.height - rect.height) < 5) {
517
+ radii = pRadii;
518
+ }
519
+ }
520
+ }
521
+
522
+ const objectFit = style.objectFit || 'fill'; // default CSS behavior is fill
523
+ const objectPosition = style.objectPosition || '50% 50%';
524
+
525
+ const item = {
526
+ type: 'image',
527
+ zIndex,
528
+ domOrder,
529
+ options: { x, y, w, h, rotate: rotation, data: null },
530
+ };
531
+
532
+ const job = async () => {
533
+ const processed = await getProcessedImage(
534
+ node.src,
535
+ widthPx,
536
+ heightPx,
537
+ radii,
538
+ objectFit,
539
+ objectPosition
540
+ );
541
+ if (processed) item.options.data = processed;
542
+ else item.skip = true;
543
+ };
544
+
545
+ return { items: [item], job, stopRecursion: true };
546
+ }
547
+
548
+ // --- ASYNC JOB: Icons and Other Elements ---
549
+ if (isIconElement(node)) {
550
+ const item = {
551
+ type: 'image',
552
+ zIndex,
553
+ domOrder,
554
+ options: { x, y, w, h, rotate: rotation, data: null },
555
+ };
556
+ const job = async () => {
557
+ const pngData = await elementToCanvasImage(node, widthPx, heightPx);
558
+ if (pngData) item.options.data = pngData;
559
+ else item.skip = true;
560
+ };
561
+ return { items: [item], job, stopRecursion: true };
562
+ }
563
+
564
+ // Radii logic
565
+ const borderRadiusValue = parseFloat(style.borderRadius) || 0;
566
+ const borderBottomLeftRadius = parseFloat(style.borderBottomLeftRadius) || 0;
567
+ const borderBottomRightRadius = parseFloat(style.borderBottomRightRadius) || 0;
568
+ const borderTopLeftRadius = parseFloat(style.borderTopLeftRadius) || 0;
569
+ const borderTopRightRadius = parseFloat(style.borderTopRightRadius) || 0;
570
+
571
+ const hasPartialBorderRadius =
572
+ (borderBottomLeftRadius > 0 && borderBottomLeftRadius !== borderRadiusValue) ||
573
+ (borderBottomRightRadius > 0 && borderBottomRightRadius !== borderRadiusValue) ||
574
+ (borderTopLeftRadius > 0 && borderTopLeftRadius !== borderRadiusValue) ||
575
+ (borderTopRightRadius > 0 && borderTopRightRadius !== borderRadiusValue) ||
576
+ (borderRadiusValue === 0 &&
577
+ (borderBottomLeftRadius ||
578
+ borderBottomRightRadius ||
579
+ borderTopLeftRadius ||
580
+ borderTopRightRadius));
581
+
582
+ // --- ASYNC JOB: Clipped Divs via Canvas ---
583
+ if (hasPartialBorderRadius && isClippedByParent(node)) {
584
+ const marginLeft = parseFloat(style.marginLeft) || 0;
585
+ const marginTop = parseFloat(style.marginTop) || 0;
586
+ x += marginLeft * PX_TO_INCH * config.scale;
587
+ y += marginTop * PX_TO_INCH * config.scale;
588
+
589
+ const item = {
590
+ type: 'image',
591
+ zIndex,
592
+ domOrder,
593
+ options: { x, y, w, h, rotate: rotation, data: null },
594
+ };
595
+
596
+ const job = async () => {
597
+ const canvasImageData = await elementToCanvasImage(node, widthPx, heightPx);
598
+ if (canvasImageData) item.options.data = canvasImageData;
599
+ else item.skip = true;
600
+ };
601
+
602
+ return { items: [item], job, stopRecursion: true };
603
+ }
604
+
605
+ // --- SYNC: Standard CSS Extraction ---
606
+ const bgColorObj = parseColor(style.backgroundColor);
607
+ const bgClip = style.webkitBackgroundClip || style.backgroundClip;
608
+ const isBgClipText = bgClip === 'text';
609
+ const hasGradient =
610
+ !isBgClipText && style.backgroundImage && style.backgroundImage.includes('linear-gradient');
611
+
612
+ const borderColorObj = parseColor(style.borderColor);
613
+ const borderWidth = parseFloat(style.borderWidth);
614
+ const hasBorder = borderWidth > 0 && borderColorObj.hex;
615
+
616
+ const borderInfo = getBorderInfo(style, config.scale);
617
+ const hasUniformBorder = borderInfo.type === 'uniform';
618
+ const hasCompositeBorder = borderInfo.type === 'composite';
619
+
620
+ const shadowStr = style.boxShadow;
621
+ const hasShadow = shadowStr && shadowStr !== 'none';
622
+ const softEdge = getSoftEdges(style.filter, config.scale);
623
+
624
+ let isImageWrapper = false;
625
+ const imgChild = Array.from(node.children).find((c) => c.tagName === 'IMG');
626
+ if (imgChild) {
627
+ const childW = imgChild.offsetWidth || imgChild.getBoundingClientRect().width;
628
+ const childH = imgChild.offsetHeight || imgChild.getBoundingClientRect().height;
629
+ if (childW >= widthPx - 2 && childH >= heightPx - 2) isImageWrapper = true;
630
+ }
631
+
632
+ let textPayload = null;
633
+ const isText = isTextContainer(node);
634
+
635
+ if (isText) {
636
+ const textParts = [];
637
+ const isList = style.display === 'list-item';
638
+ if (isList) {
639
+ const fontSizePt = parseFloat(style.fontSize) * 0.75 * config.scale;
640
+ const listStyleType = style.listStyleType || 'disc';
641
+ const listStylePos = style.listStylePosition || 'outside';
642
+
643
+ let marker = null;
644
+
645
+ // 1. Determine the marker character based on list-style-type
646
+ if (listStyleType !== 'none') {
647
+ if (listStyleType === 'decimal') {
648
+ // Calculate index for ordered lists (1., 2., etc.)
649
+ const index = Array.prototype.indexOf.call(node.parentNode.children, node) + 1;
650
+ marker = `${index}.`;
651
+ } else if (listStyleType === 'circle') {
652
+ marker = '○';
653
+ } else if (listStyleType === 'square') {
654
+ marker = '■';
655
+ } else {
656
+ marker = '•'; // Default to disc
657
+ }
658
+ }
659
+
660
+ // 2. Apply alignment and add marker
661
+ if (marker) {
662
+ // Only shift the text box to the left if the bullet is OUTSIDE the content box.
663
+ // Tailwind 'list-inside' puts the bullet inside the box, so we must NOT shift X.
664
+ if (listStylePos === 'outside') {
665
+ const bulletShift = (parseFloat(style.fontSize) || 16) * PX_TO_INCH * config.scale * 1.5;
666
+ x -= bulletShift;
667
+ w += bulletShift;
668
+ }
669
+
670
+ // Add the bullet + 3 spaces for visual separation
671
+ textParts.push({
672
+ text: marker + ' ',
673
+ options: {
674
+ color: parseColor(style.color).hex || '000000',
675
+ fontSize: fontSizePt,
676
+ },
677
+ });
678
+ }
679
+ }
680
+
681
+ node.childNodes.forEach((child, index) => {
682
+ let textVal = child.nodeType === 3 ? child.nodeValue : child.textContent;
683
+ let nodeStyle = child.nodeType === 1 ? window.getComputedStyle(child) : style;
684
+ textVal = textVal.replace(/[\n\r\t]+/g, ' ').replace(/\s{2,}/g, ' ');
685
+ if (index === 0 && !isList) textVal = textVal.trimStart();
686
+ else if (index === 0) textVal = textVal.trimStart();
687
+ if (index === node.childNodes.length - 1) textVal = textVal.trimEnd();
688
+ if (nodeStyle.textTransform === 'uppercase') textVal = textVal.toUpperCase();
689
+ if (nodeStyle.textTransform === 'lowercase') textVal = textVal.toLowerCase();
690
+
691
+ if (textVal.length > 0) {
692
+ textParts.push({
693
+ text: textVal,
694
+ options: getTextStyle(nodeStyle, config.scale),
695
+ });
696
+ }
697
+ });
698
+
699
+ if (textParts.length > 0) {
700
+ let align = style.textAlign || 'left';
701
+ if (align === 'start') align = 'left';
702
+ if (align === 'end') align = 'right';
703
+ let valign = 'top';
704
+ if (style.alignItems === 'center') valign = 'middle';
705
+ if (style.justifyContent === 'center' && style.display.includes('flex')) align = 'center';
706
+
707
+ const pt = parseFloat(style.paddingTop) || 0;
708
+ const pb = parseFloat(style.paddingBottom) || 0;
709
+ if (Math.abs(pt - pb) < 2 && bgColorObj.hex) valign = 'middle';
710
+
711
+ let padding = getPadding(style, config.scale);
712
+ if (align === 'center' && valign === 'middle') padding = [0, 0, 0, 0];
713
+
714
+ textPayload = { text: textParts, align, valign, inset: padding };
715
+ }
716
+ }
717
+
718
+ if (hasGradient || (softEdge && bgColorObj.hex && !isImageWrapper)) {
719
+ let bgData = null;
720
+ let padIn = 0;
721
+ if (softEdge) {
722
+ const svgInfo = generateBlurredSVG(
723
+ widthPx,
724
+ heightPx,
725
+ bgColorObj.hex,
726
+ borderRadiusValue,
727
+ softEdge
728
+ );
729
+ bgData = svgInfo.data;
730
+ padIn = svgInfo.padding * PX_TO_INCH * config.scale;
731
+ } else {
732
+ bgData = generateGradientSVG(
733
+ widthPx,
734
+ heightPx,
735
+ style.backgroundImage,
736
+ borderRadiusValue,
737
+ hasBorder ? { color: borderColorObj.hex, width: borderWidth } : null
738
+ );
739
+ }
740
+
741
+ if (bgData) {
742
+ items.push({
743
+ type: 'image',
744
+ zIndex,
745
+ domOrder,
746
+ options: {
747
+ data: bgData,
748
+ x: x - padIn,
749
+ y: y - padIn,
750
+ w: w + padIn * 2,
751
+ h: h + padIn * 2,
752
+ rotate: rotation,
753
+ },
754
+ });
755
+ }
756
+
757
+ if (textPayload) {
758
+ textPayload.text[0].options.fontSize =
759
+ Math.floor(textPayload.text[0]?.options?.fontSize) || 12;
760
+ items.push({
761
+ type: 'text',
762
+ zIndex: zIndex + 1,
763
+ domOrder,
764
+ textParts: textPayload.text,
765
+ options: {
766
+ x,
767
+ y,
768
+ w,
769
+ h,
770
+ align: textPayload.align,
771
+ valign: textPayload.valign,
772
+ inset: textPayload.inset,
773
+ rotate: rotation,
774
+ margin: 0,
775
+ wrap: true,
776
+ autoFit: false,
777
+ },
778
+ });
779
+ }
780
+ if (hasCompositeBorder) {
781
+ const borderItems = createCompositeBorderItems(
782
+ borderInfo.sides,
783
+ x,
784
+ y,
785
+ w,
786
+ h,
787
+ config.scale,
788
+ zIndex,
789
+ domOrder
790
+ );
791
+ items.push(...borderItems);
792
+ }
793
+ } else if (
794
+ (bgColorObj.hex && !isImageWrapper) ||
795
+ hasUniformBorder ||
796
+ hasCompositeBorder ||
797
+ hasShadow ||
798
+ textPayload
799
+ ) {
800
+ const finalAlpha = safeOpacity * bgColorObj.opacity;
801
+ const transparency = (1 - finalAlpha) * 100;
802
+ const useSolidFill = bgColorObj.hex && !isImageWrapper;
803
+
804
+ if (hasPartialBorderRadius && useSolidFill && !textPayload) {
805
+ const shapeSvg = generateCustomShapeSVG(
806
+ widthPx,
807
+ heightPx,
808
+ bgColorObj.hex,
809
+ bgColorObj.opacity,
810
+ {
811
+ tl: parseFloat(style.borderTopLeftRadius) || 0,
812
+ tr: parseFloat(style.borderTopRightRadius) || 0,
813
+ br: parseFloat(style.borderBottomRightRadius) || 0,
814
+ bl: parseFloat(style.borderBottomLeftRadius) || 0,
815
+ }
816
+ );
817
+
818
+ items.push({
819
+ type: 'image',
820
+ zIndex,
821
+ domOrder,
822
+ options: { data: shapeSvg, x, y, w, h, rotate: rotation },
823
+ });
824
+ } else {
825
+ const shapeOpts = {
826
+ x,
827
+ y,
828
+ w,
829
+ h,
830
+ rotate: rotation,
831
+ fill: useSolidFill
832
+ ? { color: bgColorObj.hex, transparency: transparency }
833
+ : { type: 'none' },
834
+ line: hasUniformBorder ? borderInfo.options : null,
835
+ };
836
+
837
+ if (hasShadow) shapeOpts.shadow = getVisibleShadow(shadowStr, config.scale);
838
+
839
+ // 1. Calculate dimensions first
840
+ const minDimension = Math.min(widthPx, heightPx);
841
+
842
+ let rawRadius = parseFloat(style.borderRadius) || 0;
843
+ const isPercentage = style.borderRadius && style.borderRadius.toString().includes('%');
844
+
845
+ // 2. Normalize radius to pixels
846
+ let radiusPx = rawRadius;
847
+ if (isPercentage) {
848
+ radiusPx = (rawRadius / 100) * minDimension;
849
+ }
850
+
851
+ let shapeType = pptx.ShapeType.rect;
852
+
853
+ // 3. Determine Shape Logic
854
+ const isSquare = Math.abs(widthPx - heightPx) < 1;
855
+ const isFullyRound = radiusPx >= minDimension / 2;
856
+
857
+ // CASE A: It is an Ellipse if:
858
+ // 1. It is explicitly "50%" (standard CSS way to make ovals/circles)
859
+ // 2. OR it is a perfect square and fully rounded (a circle)
860
+ if (isFullyRound && (isPercentage || isSquare)) {
861
+ shapeType = pptx.ShapeType.ellipse;
862
+ }
863
+ // CASE B: It is a Rounded Rectangle (including "Pill" shapes)
864
+ else if (radiusPx > 0) {
865
+ shapeType = pptx.ShapeType.roundRect;
866
+ let r = radiusPx / minDimension;
867
+ if (r > 0.5) r = 0.5;
868
+ if (minDimension < 100) r = r * 0.25; // Small size adjustment for small shapes
869
+
870
+ shapeOpts.rectRadius = r;
871
+ }
872
+
873
+ if (textPayload) {
874
+ textPayload.text[0].options.fontSize =
875
+ Math.floor(textPayload.text[0]?.options?.fontSize) || 12;
876
+ const textOptions = {
877
+ shape: shapeType,
878
+ ...shapeOpts,
879
+ rotate: rotation,
880
+ align: textPayload.align,
881
+ valign: textPayload.valign,
882
+ inset: textPayload.inset,
883
+ margin: 0,
884
+ wrap: true,
885
+ autoFit: false,
886
+ };
887
+ items.push({
888
+ type: 'text',
889
+ zIndex,
890
+ domOrder,
891
+ textParts: textPayload.text,
892
+ options: textOptions,
893
+ });
894
+ } else if (!hasPartialBorderRadius) {
895
+ items.push({
896
+ type: 'shape',
897
+ zIndex,
898
+ domOrder,
899
+ shapeType,
900
+ options: shapeOpts,
901
+ });
902
+ }
903
+ }
904
+
905
+ if (hasCompositeBorder) {
906
+ const borderSvgData = generateCompositeBorderSVG(
907
+ widthPx,
908
+ heightPx,
909
+ borderRadiusValue,
910
+ borderInfo.sides
911
+ );
912
+ if (borderSvgData) {
913
+ items.push({
914
+ type: 'image',
915
+ zIndex: zIndex + 1,
916
+ domOrder,
917
+ options: { data: borderSvgData, x, y, w, h, rotate: rotation },
918
+ });
919
+ }
920
+ }
921
+ }
922
+
923
+ return { items, stopRecursion: !!textPayload };
924
+ }
925
+
926
+ function createCompositeBorderItems(sides, x, y, w, h, scale, zIndex, domOrder) {
927
+ const items = [];
928
+ const pxToInch = 1 / 96;
929
+ const common = { zIndex: zIndex + 1, domOrder, shapeType: 'rect' };
930
+
931
+ if (sides.top.width > 0)
932
+ items.push({
933
+ ...common,
934
+ options: { x, y, w, h: sides.top.width * pxToInch * scale, fill: { color: sides.top.color } },
935
+ });
936
+ if (sides.right.width > 0)
937
+ items.push({
938
+ ...common,
939
+ options: {
940
+ x: x + w - sides.right.width * pxToInch * scale,
941
+ y,
942
+ w: sides.right.width * pxToInch * scale,
943
+ h,
944
+ fill: { color: sides.right.color },
945
+ },
946
+ });
947
+ if (sides.bottom.width > 0)
948
+ items.push({
949
+ ...common,
950
+ options: {
951
+ x,
952
+ y: y + h - sides.bottom.width * pxToInch * scale,
953
+ w,
954
+ h: sides.bottom.width * pxToInch * scale,
955
+ fill: { color: sides.bottom.color },
956
+ },
957
+ });
958
+ if (sides.left.width > 0)
959
+ items.push({
960
+ ...common,
961
+ options: {
962
+ x,
963
+ y,
964
+ w: sides.left.width * pxToInch * scale,
965
+ h,
966
+ fill: { color: sides.left.color },
967
+ },
968
+ });
969
+
970
+ return items;
971
+ }