dom-to-pptx 1.0.6 → 1.0.7

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.
@@ -7820,484 +7820,430 @@ var parseBackgroundColor = function (context, element, backgroundColorOverride)
7820
7820
  : defaultBackgroundColor;
7821
7821
  };
7822
7822
 
7823
- // src/utils.js
7824
-
7825
- /**
7826
- * Checks if any parent element has overflow: hidden which would clip this element
7827
- * @param {HTMLElement} node - The DOM node to check
7828
- * @returns {boolean} - True if a parent has overflow-hidden or overflow-clip
7829
- */
7830
- function isClippedByParent(node) {
7831
- let parent = node.parentElement;
7832
- while (parent && parent !== document.body) {
7833
- const style = window.getComputedStyle(parent);
7834
- const overflow = style.overflow;
7835
- if (overflow === 'hidden' || overflow === 'clip') {
7836
- return true;
7837
- }
7838
- parent = parent.parentElement;
7839
- }
7840
- return false;
7841
- }
7842
-
7843
- // Helper to save gradient text
7844
- function getGradientFallbackColor(bgImage) {
7845
- if (!bgImage) return null;
7846
- const hexMatch = bgImage.match(/#(?:[0-9a-fA-F]{3}){1,2}/);
7847
- if (hexMatch) return hexMatch[0];
7848
- const rgbMatch = bgImage.match(/rgba?\(.*?\)/);
7849
- if (rgbMatch) return rgbMatch[0];
7850
- return null;
7851
- }
7852
-
7853
- function mapDashType(style) {
7854
- if (style === 'dashed') return 'dash';
7855
- if (style === 'dotted') return 'dot';
7856
- return 'solid';
7857
- }
7858
-
7859
- /**
7860
- * Analyzes computed border styles and determines the rendering strategy.
7861
- */
7862
- function getBorderInfo(style, scale) {
7863
- const top = {
7864
- width: parseFloat(style.borderTopWidth) || 0,
7865
- style: style.borderTopStyle,
7866
- color: parseColor(style.borderTopColor).hex,
7867
- };
7868
- const right = {
7869
- width: parseFloat(style.borderRightWidth) || 0,
7870
- style: style.borderRightStyle,
7871
- color: parseColor(style.borderRightColor).hex,
7872
- };
7873
- const bottom = {
7874
- width: parseFloat(style.borderBottomWidth) || 0,
7875
- style: style.borderBottomStyle,
7876
- color: parseColor(style.borderBottomColor).hex,
7877
- };
7878
- const left = {
7879
- width: parseFloat(style.borderLeftWidth) || 0,
7880
- style: style.borderLeftStyle,
7881
- color: parseColor(style.borderLeftColor).hex,
7882
- };
7883
-
7884
- const hasAnyBorder = top.width > 0 || right.width > 0 || bottom.width > 0 || left.width > 0;
7885
- if (!hasAnyBorder) return { type: 'none' };
7886
-
7887
- // Check if all sides are uniform
7888
- const isUniform =
7889
- top.width === right.width &&
7890
- top.width === bottom.width &&
7891
- top.width === left.width &&
7892
- top.style === right.style &&
7893
- top.style === bottom.style &&
7894
- top.style === left.style &&
7895
- top.color === right.color &&
7896
- top.color === bottom.color &&
7897
- top.color === left.color;
7898
-
7899
- if (isUniform) {
7900
- return {
7901
- type: 'uniform',
7902
- options: {
7903
- width: top.width * 0.75 * scale,
7904
- color: top.color,
7905
- transparency: (1 - parseColor(style.borderTopColor).opacity) * 100,
7906
- dashType: mapDashType(top.style),
7907
- },
7908
- };
7909
- } else {
7910
- return {
7911
- type: 'composite',
7912
- sides: { top, right, bottom, left },
7913
- };
7914
- }
7915
- }
7916
-
7917
- /**
7918
- * Generates an SVG image for composite borders that respects border-radius.
7919
- */
7920
- function generateCompositeBorderSVG(w, h, radius, sides) {
7921
- radius = radius / 2; // Adjust for SVG rendering
7922
- const clipId = 'clip_' + Math.random().toString(36).substr(2, 9);
7923
- let borderRects = '';
7924
-
7925
- if (sides.top.width > 0 && sides.top.color) {
7926
- borderRects += `<rect x="0" y="0" width="${w}" height="${sides.top.width}" fill="#${sides.top.color}" />`;
7927
- }
7928
- if (sides.right.width > 0 && sides.right.color) {
7929
- borderRects += `<rect x="${w - sides.right.width}" y="0" width="${sides.right.width}" height="${h}" fill="#${sides.right.color}" />`;
7930
- }
7931
- if (sides.bottom.width > 0 && sides.bottom.color) {
7932
- borderRects += `<rect x="0" y="${h - sides.bottom.width}" width="${w}" height="${sides.bottom.width}" fill="#${sides.bottom.color}" />`;
7933
- }
7934
- if (sides.left.width > 0 && sides.left.color) {
7935
- borderRects += `<rect x="0" y="0" width="${sides.left.width}" height="${h}" fill="#${sides.left.color}" />`;
7936
- }
7937
-
7938
- const svg = `
7939
- <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
7940
- <defs>
7941
- <clipPath id="${clipId}">
7942
- <rect x="0" y="0" width="${w}" height="${h}" rx="${radius}" ry="${radius}" />
7943
- </clipPath>
7944
- </defs>
7945
- <g clip-path="url(#${clipId})">
7946
- ${borderRects}
7947
- </g>
7948
- </svg>`;
7949
-
7950
- return 'data:image/svg+xml;base64,' + btoa(svg);
7951
- }
7952
-
7953
- /**
7954
- * Generates an SVG data URL for a solid shape with non-uniform corner radii.
7955
- */
7956
- function generateCustomShapeSVG(w, h, color, opacity, radii) {
7957
- let { tl, tr, br, bl } = radii;
7958
-
7959
- // Clamp radii using CSS spec logic (avoid overlap)
7960
- const factor = Math.min(
7961
- w / (tl + tr) || Infinity,
7962
- h / (tr + br) || Infinity,
7963
- w / (br + bl) || Infinity,
7964
- h / (bl + tl) || Infinity
7965
- );
7966
-
7967
- if (factor < 1) {
7968
- tl *= factor;
7969
- tr *= factor;
7970
- br *= factor;
7971
- bl *= factor;
7972
- }
7973
-
7974
- const path = `
7975
- M ${tl} 0
7976
- L ${w - tr} 0
7977
- A ${tr} ${tr} 0 0 1 ${w} ${tr}
7978
- L ${w} ${h - br}
7979
- A ${br} ${br} 0 0 1 ${w - br} ${h}
7980
- L ${bl} ${h}
7981
- A ${bl} ${bl} 0 0 1 0 ${h - bl}
7982
- L 0 ${tl}
7983
- A ${tl} ${tl} 0 0 1 ${tl} 0
7984
- Z
7985
- `;
7986
-
7987
- const svg = `
7988
- <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
7989
- <path d="${path}" fill="#${color}" fill-opacity="${opacity}" />
7990
- </svg>`;
7991
-
7992
- return 'data:image/svg+xml;base64,' + btoa(svg);
7993
- }
7994
-
7995
- function parseColor(str) {
7996
- if (!str || str === 'transparent' || str.startsWith('rgba(0, 0, 0, 0)')) {
7997
- return { hex: null, opacity: 0 };
7998
- }
7999
- if (str.startsWith('#')) {
8000
- let hex = str.slice(1);
8001
- if (hex.length === 3)
8002
- hex = hex
8003
- .split('')
8004
- .map((c) => c + c)
8005
- .join('');
8006
- return { hex: hex.toUpperCase(), opacity: 1 };
8007
- }
8008
- const match = str.match(/[\d.]+/g);
8009
- if (match && match.length >= 3) {
8010
- const r = parseInt(match[0]);
8011
- const g = parseInt(match[1]);
8012
- const b = parseInt(match[2]);
8013
- const a = match.length > 3 ? parseFloat(match[3]) : 1;
8014
- const hex = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase();
8015
- return { hex, opacity: a };
8016
- }
8017
- return { hex: null, opacity: 0 };
8018
- }
8019
-
8020
- function getPadding(style, scale) {
8021
- const pxToInch = 1 / 96;
8022
- return [
8023
- (parseFloat(style.paddingTop) || 0) * pxToInch * scale,
8024
- (parseFloat(style.paddingRight) || 0) * pxToInch * scale,
8025
- (parseFloat(style.paddingBottom) || 0) * pxToInch * scale,
8026
- (parseFloat(style.paddingLeft) || 0) * pxToInch * scale,
8027
- ];
8028
- }
8029
-
8030
- function getSoftEdges(filterStr, scale) {
8031
- if (!filterStr || filterStr === 'none') return null;
8032
- const match = filterStr.match(/blur\(([\d.]+)px\)/);
8033
- if (match) return parseFloat(match[1]) * 0.75 * scale;
8034
- return null;
8035
- }
8036
-
8037
- function getTextStyle(style, scale) {
8038
- let colorObj = parseColor(style.color);
8039
-
8040
- const bgClip = style.webkitBackgroundClip || style.backgroundClip;
8041
- if (colorObj.opacity === 0 && bgClip === 'text') {
8042
- const fallback = getGradientFallbackColor(style.backgroundImage);
8043
- if (fallback) colorObj = parseColor(fallback);
8044
- }
8045
-
8046
- return {
8047
- color: colorObj.hex || '000000',
8048
- fontFace: style.fontFamily.split(',')[0].replace(/['"]/g, ''),
8049
- fontSize: parseFloat(style.fontSize) * 0.75 * scale,
8050
- bold: parseInt(style.fontWeight) >= 600,
8051
- italic: style.fontStyle === 'italic',
8052
- underline: style.textDecoration.includes('underline'),
8053
- };
8054
- }
8055
-
8056
- /**
8057
- * Determines if a given DOM node is primarily a text container.
8058
- */
8059
- function isTextContainer(node) {
8060
- const hasText = node.textContent.trim().length > 0;
8061
- if (!hasText) return false;
8062
-
8063
- const children = Array.from(node.children);
8064
- if (children.length === 0) return true;
8065
-
8066
- // Check if children are purely inline text formatting or visual shapes
8067
- const isSafeInline = (el) => {
8068
- const style = window.getComputedStyle(el);
8069
- const display = style.display;
8070
-
8071
- // If it's a standard inline element
8072
- const isInlineTag = ['SPAN', 'B', 'STRONG', 'EM', 'I', 'A', 'SMALL'].includes(el.tagName);
8073
- const isInlineDisplay = display.includes('inline');
8074
-
8075
- if (!isInlineTag && !isInlineDisplay) return false;
8076
-
8077
- // Check if element is a shape (visual object without text)
8078
- // If an element is empty but has a visible background/border, it's a shape (like a dot).
8079
- // We must return false so the parent isn't treated as a text-only container.
8080
- const hasContent = el.textContent.trim().length > 0;
8081
- const bgColor = parseColor(style.backgroundColor);
8082
- const hasVisibleBg = bgColor.hex && bgColor.opacity > 0;
8083
- const hasBorder =
8084
- parseFloat(style.borderWidth) > 0 && parseColor(style.borderColor).opacity > 0;
8085
-
8086
- if (!hasContent && (hasVisibleBg || hasBorder)) {
8087
- return false;
8088
- }
8089
-
8090
- return true;
8091
- };
8092
-
8093
- return children.every(isSafeInline);
8094
- }
8095
-
8096
- function getRotation(transformStr) {
8097
- if (!transformStr || transformStr === 'none') return 0;
8098
- const values = transformStr.split('(')[1].split(')')[0].split(',');
8099
- if (values.length < 4) return 0;
8100
- const a = parseFloat(values[0]);
8101
- const b = parseFloat(values[1]);
8102
- return Math.round(Math.atan2(b, a) * (180 / Math.PI));
8103
- }
8104
-
8105
- function svgToPng(node) {
8106
- return new Promise((resolve) => {
8107
- const clone = node.cloneNode(true);
8108
- const rect = node.getBoundingClientRect();
8109
- const width = rect.width || 300;
8110
- const height = rect.height || 150;
8111
-
8112
- function inlineStyles(source, target) {
8113
- const computed = window.getComputedStyle(source);
8114
- const properties = [
8115
- 'fill',
8116
- 'stroke',
8117
- 'stroke-width',
8118
- 'stroke-linecap',
8119
- 'stroke-linejoin',
8120
- 'opacity',
8121
- 'font-family',
8122
- 'font-size',
8123
- 'font-weight',
8124
- ];
8125
-
8126
- if (computed.fill === 'none') target.setAttribute('fill', 'none');
8127
- else if (computed.fill) target.style.fill = computed.fill;
8128
-
8129
- if (computed.stroke === 'none') target.setAttribute('stroke', 'none');
8130
- else if (computed.stroke) target.style.stroke = computed.stroke;
8131
-
8132
- properties.forEach((prop) => {
8133
- if (prop !== 'fill' && prop !== 'stroke') {
8134
- const val = computed[prop];
8135
- if (val && val !== 'auto') target.style[prop] = val;
8136
- }
8137
- });
8138
-
8139
- for (let i = 0; i < source.children.length; i++) {
8140
- if (target.children[i]) inlineStyles(source.children[i], target.children[i]);
8141
- }
8142
- }
8143
-
8144
- inlineStyles(node, clone);
8145
- clone.setAttribute('width', width);
8146
- clone.setAttribute('height', height);
8147
- clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
8148
-
8149
- const xml = new XMLSerializer().serializeToString(clone);
8150
- const svgUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(xml)}`;
8151
- const img = new Image();
8152
- img.crossOrigin = 'Anonymous';
8153
- img.onload = () => {
8154
- const canvas = document.createElement('canvas');
8155
- const scale = 3;
8156
- canvas.width = width * scale;
8157
- canvas.height = height * scale;
8158
- const ctx = canvas.getContext('2d');
8159
- ctx.scale(scale, scale);
8160
- ctx.drawImage(img, 0, 0, width, height);
8161
- resolve(canvas.toDataURL('image/png'));
8162
- };
8163
- img.onerror = () => resolve(null);
8164
- img.src = svgUrl;
8165
- });
8166
- }
8167
-
8168
- function getVisibleShadow(shadowStr, scale) {
8169
- if (!shadowStr || shadowStr === 'none') return null;
8170
- const shadows = shadowStr.split(/,(?![^()]*\))/);
8171
- for (let s of shadows) {
8172
- s = s.trim();
8173
- if (s.startsWith('rgba(0, 0, 0, 0)')) continue;
8174
- const match = s.match(
8175
- /(rgba?\([^)]+\)|#[0-9a-fA-F]+)\s+(-?[\d.]+)px\s+(-?[\d.]+)px\s+([\d.]+)px/
8176
- );
8177
- if (match) {
8178
- const colorStr = match[1];
8179
- const x = parseFloat(match[2]);
8180
- const y = parseFloat(match[3]);
8181
- const blur = parseFloat(match[4]);
8182
- const distance = Math.sqrt(x * x + y * y);
8183
- let angle = Math.atan2(y, x) * (180 / Math.PI);
8184
- if (angle < 0) angle += 360;
8185
- const colorObj = parseColor(colorStr);
8186
- return {
8187
- type: 'outer',
8188
- angle: angle,
8189
- blur: blur * 0.75 * scale,
8190
- offset: distance * 0.75 * scale,
8191
- color: colorObj.hex || '000000',
8192
- opacity: colorObj.opacity,
8193
- };
8194
- }
8195
- }
8196
- return null;
8197
- }
8198
-
8199
- function generateGradientSVG(w, h, bgString, radius, border) {
8200
- try {
8201
- const match = bgString.match(/linear-gradient\((.*)\)/);
8202
- if (!match) return null;
8203
- const content = match[1];
8204
- const parts = content.split(/,(?![^()]*\))/).map((p) => p.trim());
8205
-
8206
- let x1 = '0%',
8207
- y1 = '0%',
8208
- x2 = '0%',
8209
- y2 = '100%';
8210
- let stopsStartIdx = 0;
8211
- if (parts[0].includes('to right')) {
8212
- x1 = '0%';
8213
- x2 = '100%';
8214
- y2 = '0%';
8215
- stopsStartIdx = 1;
8216
- } else if (parts[0].includes('to left')) {
8217
- x1 = '100%';
8218
- x2 = '0%';
8219
- y2 = '0%';
8220
- stopsStartIdx = 1;
8221
- } else if (parts[0].includes('to top')) {
8222
- y1 = '100%';
8223
- y2 = '0%';
8224
- stopsStartIdx = 1;
8225
- } else if (parts[0].includes('to bottom')) {
8226
- y1 = '0%';
8227
- y2 = '100%';
8228
- stopsStartIdx = 1;
8229
- }
8230
-
8231
- let stopsXML = '';
8232
- const stopParts = parts.slice(stopsStartIdx);
8233
- stopParts.forEach((part, idx) => {
8234
- let color = part;
8235
- let offset = Math.round((idx / (stopParts.length - 1)) * 100) + '%';
8236
- const posMatch = part.match(/(.*?)\s+(\d+(\.\d+)?%?)$/);
8237
- if (posMatch) {
8238
- color = posMatch[1];
8239
- offset = posMatch[2];
8240
- }
8241
- let opacity = 1;
8242
- if (color.includes('rgba')) {
8243
- const rgba = color.match(/[\d.]+/g);
8244
- if (rgba && rgba.length > 3) {
8245
- opacity = rgba[3];
8246
- color = `rgb(${rgba[0]},${rgba[1]},${rgba[2]})`;
8247
- }
8248
- }
8249
- stopsXML += `<stop offset="${offset}" stop-color="${color}" stop-opacity="${opacity}"/>`;
8250
- });
8251
-
8252
- let strokeAttr = '';
8253
- if (border) {
8254
- strokeAttr = `stroke="#${border.color}" stroke-width="${border.width}"`;
8255
- }
8256
-
8257
- const svg = `
8258
- <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
8259
- <defs><linearGradient id="grad" x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}">${stopsXML}</linearGradient></defs>
8260
- <rect x="0" y="0" width="${w}" height="${h}" rx="${radius}" ry="${radius}" fill="url(#grad)" ${strokeAttr} />
8261
- </svg>`;
8262
- return 'data:image/svg+xml;base64,' + btoa(svg);
8263
- } catch {
8264
- return null;
8265
- }
8266
- }
8267
-
8268
- function generateBlurredSVG(w, h, color, radius, blurPx) {
8269
- const padding = blurPx * 3;
8270
- const fullW = w + padding * 2;
8271
- const fullH = h + padding * 2;
8272
- const x = padding;
8273
- const y = padding;
8274
- let shapeTag = '';
8275
- const isCircle = radius >= Math.min(w, h) / 2 - 1 && Math.abs(w - h) < 2;
8276
-
8277
- if (isCircle) {
8278
- const cx = x + w / 2;
8279
- const cy = y + h / 2;
8280
- const rx = w / 2;
8281
- const ry = h / 2;
8282
- shapeTag = `<ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" fill="#${color}" filter="url(#f1)" />`;
8283
- } else {
8284
- shapeTag = `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${radius}" ry="${radius}" fill="#${color}" filter="url(#f1)" />`;
8285
- }
8286
-
8287
- const svg = `
8288
- <svg xmlns="http://www.w3.org/2000/svg" width="${fullW}" height="${fullH}" viewBox="0 0 ${fullW} ${fullH}">
8289
- <defs>
8290
- <filter id="f1" x="-50%" y="-50%" width="200%" height="200%">
8291
- <feGaussianBlur in="SourceGraphic" stdDeviation="${blurPx}" />
8292
- </filter>
8293
- </defs>
8294
- ${shapeTag}
8295
- </svg>`;
8296
-
8297
- return {
8298
- data: 'data:image/svg+xml;base64,' + btoa(svg),
8299
- padding: padding,
8300
- };
7823
+ // src/utils.js
7824
+
7825
+ /**
7826
+ * Checks if any parent element has overflow: hidden which would clip this element
7827
+ * @param {HTMLElement} node - The DOM node to check
7828
+ * @returns {boolean} - True if a parent has overflow-hidden or overflow-clip
7829
+ */
7830
+ function isClippedByParent(node) {
7831
+ let parent = node.parentElement;
7832
+ while (parent && parent !== document.body) {
7833
+ const style = window.getComputedStyle(parent);
7834
+ const overflow = style.overflow;
7835
+ if (overflow === 'hidden' || overflow === 'clip') {
7836
+ return true;
7837
+ }
7838
+ parent = parent.parentElement;
7839
+ }
7840
+ return false;
7841
+ }
7842
+
7843
+ // Helper to save gradient text
7844
+ function getGradientFallbackColor(bgImage) {
7845
+ if (!bgImage) return null;
7846
+ const hexMatch = bgImage.match(/#(?:[0-9a-fA-F]{3}){1,2}/);
7847
+ if (hexMatch) return hexMatch[0];
7848
+ const rgbMatch = bgImage.match(/rgba?\(.*?\)/);
7849
+ if (rgbMatch) return rgbMatch[0];
7850
+ return null;
7851
+ }
7852
+
7853
+ function mapDashType(style) {
7854
+ if (style === 'dashed') return 'dash';
7855
+ if (style === 'dotted') return 'dot';
7856
+ return 'solid';
7857
+ }
7858
+
7859
+ /**
7860
+ * Analyzes computed border styles and determines the rendering strategy.
7861
+ */
7862
+ function getBorderInfo(style, scale) {
7863
+ const top = {
7864
+ width: parseFloat(style.borderTopWidth) || 0,
7865
+ style: style.borderTopStyle,
7866
+ color: parseColor(style.borderTopColor).hex,
7867
+ };
7868
+ const right = {
7869
+ width: parseFloat(style.borderRightWidth) || 0,
7870
+ style: style.borderRightStyle,
7871
+ color: parseColor(style.borderRightColor).hex,
7872
+ };
7873
+ const bottom = {
7874
+ width: parseFloat(style.borderBottomWidth) || 0,
7875
+ style: style.borderBottomStyle,
7876
+ color: parseColor(style.borderBottomColor).hex,
7877
+ };
7878
+ const left = {
7879
+ width: parseFloat(style.borderLeftWidth) || 0,
7880
+ style: style.borderLeftStyle,
7881
+ color: parseColor(style.borderLeftColor).hex,
7882
+ };
7883
+
7884
+ const hasAnyBorder = top.width > 0 || right.width > 0 || bottom.width > 0 || left.width > 0;
7885
+ if (!hasAnyBorder) return { type: 'none' };
7886
+
7887
+ // Check if all sides are uniform
7888
+ const isUniform =
7889
+ top.width === right.width &&
7890
+ top.width === bottom.width &&
7891
+ top.width === left.width &&
7892
+ top.style === right.style &&
7893
+ top.style === bottom.style &&
7894
+ top.style === left.style &&
7895
+ top.color === right.color &&
7896
+ top.color === bottom.color &&
7897
+ top.color === left.color;
7898
+
7899
+ if (isUniform) {
7900
+ return {
7901
+ type: 'uniform',
7902
+ options: {
7903
+ width: top.width * 0.75 * scale,
7904
+ color: top.color,
7905
+ transparency: (1 - parseColor(style.borderTopColor).opacity) * 100,
7906
+ dashType: mapDashType(top.style),
7907
+ },
7908
+ };
7909
+ } else {
7910
+ return {
7911
+ type: 'composite',
7912
+ sides: { top, right, bottom, left },
7913
+ };
7914
+ }
7915
+ }
7916
+
7917
+ /**
7918
+ * Generates an SVG image for composite borders that respects border-radius.
7919
+ */
7920
+ function generateCompositeBorderSVG(w, h, radius, sides) {
7921
+ radius = radius / 2; // Adjust for SVG rendering
7922
+ const clipId = 'clip_' + Math.random().toString(36).substr(2, 9);
7923
+ let borderRects = '';
7924
+
7925
+ if (sides.top.width > 0 && sides.top.color) {
7926
+ borderRects += `<rect x="0" y="0" width="${w}" height="${sides.top.width}" fill="#${sides.top.color}" />`;
7927
+ }
7928
+ if (sides.right.width > 0 && sides.right.color) {
7929
+ borderRects += `<rect x="${w - sides.right.width}" y="0" width="${sides.right.width}" height="${h}" fill="#${sides.right.color}" />`;
7930
+ }
7931
+ if (sides.bottom.width > 0 && sides.bottom.color) {
7932
+ borderRects += `<rect x="0" y="${h - sides.bottom.width}" width="${w}" height="${sides.bottom.width}" fill="#${sides.bottom.color}" />`;
7933
+ }
7934
+ if (sides.left.width > 0 && sides.left.color) {
7935
+ borderRects += `<rect x="0" y="0" width="${sides.left.width}" height="${h}" fill="#${sides.left.color}" />`;
7936
+ }
7937
+
7938
+ const svg = `
7939
+ <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
7940
+ <defs>
7941
+ <clipPath id="${clipId}">
7942
+ <rect x="0" y="0" width="${w}" height="${h}" rx="${radius}" ry="${radius}" />
7943
+ </clipPath>
7944
+ </defs>
7945
+ <g clip-path="url(#${clipId})">
7946
+ ${borderRects}
7947
+ </g>
7948
+ </svg>`;
7949
+
7950
+ return 'data:image/svg+xml;base64,' + btoa(svg);
7951
+ }
7952
+
7953
+ /**
7954
+ * Generates an SVG data URL for a solid shape with non-uniform corner radii.
7955
+ */
7956
+ function generateCustomShapeSVG(w, h, color, opacity, radii) {
7957
+ let { tl, tr, br, bl } = radii;
7958
+
7959
+ // Clamp radii using CSS spec logic (avoid overlap)
7960
+ const factor = Math.min(
7961
+ w / (tl + tr) || Infinity,
7962
+ h / (tr + br) || Infinity,
7963
+ w / (br + bl) || Infinity,
7964
+ h / (bl + tl) || Infinity
7965
+ );
7966
+
7967
+ if (factor < 1) {
7968
+ tl *= factor;
7969
+ tr *= factor;
7970
+ br *= factor;
7971
+ bl *= factor;
7972
+ }
7973
+
7974
+ const path = `
7975
+ M ${tl} 0
7976
+ L ${w - tr} 0
7977
+ A ${tr} ${tr} 0 0 1 ${w} ${tr}
7978
+ L ${w} ${h - br}
7979
+ A ${br} ${br} 0 0 1 ${w - br} ${h}
7980
+ L ${bl} ${h}
7981
+ A ${bl} ${bl} 0 0 1 0 ${h - bl}
7982
+ L 0 ${tl}
7983
+ A ${tl} ${tl} 0 0 1 ${tl} 0
7984
+ Z
7985
+ `;
7986
+
7987
+ const svg = `
7988
+ <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
7989
+ <path d="${path}" fill="#${color}" fill-opacity="${opacity}" />
7990
+ </svg>`;
7991
+
7992
+ return 'data:image/svg+xml;base64,' + btoa(svg);
7993
+ }
7994
+
7995
+ function parseColor(str) {
7996
+ if (!str || str === 'transparent' || str.startsWith('rgba(0, 0, 0, 0)')) {
7997
+ return { hex: null, opacity: 0 };
7998
+ }
7999
+ if (str.startsWith('#')) {
8000
+ let hex = str.slice(1);
8001
+ if (hex.length === 3)
8002
+ hex = hex
8003
+ .split('')
8004
+ .map((c) => c + c)
8005
+ .join('');
8006
+ return { hex: hex.toUpperCase(), opacity: 1 };
8007
+ }
8008
+ const match = str.match(/[\d.]+/g);
8009
+ if (match && match.length >= 3) {
8010
+ const r = parseInt(match[0]);
8011
+ const g = parseInt(match[1]);
8012
+ const b = parseInt(match[2]);
8013
+ const a = match.length > 3 ? parseFloat(match[3]) : 1;
8014
+ const hex = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase();
8015
+ return { hex, opacity: a };
8016
+ }
8017
+ return { hex: null, opacity: 0 };
8018
+ }
8019
+
8020
+ function getPadding(style, scale) {
8021
+ const pxToInch = 1 / 96;
8022
+ return [
8023
+ (parseFloat(style.paddingTop) || 0) * pxToInch * scale,
8024
+ (parseFloat(style.paddingRight) || 0) * pxToInch * scale,
8025
+ (parseFloat(style.paddingBottom) || 0) * pxToInch * scale,
8026
+ (parseFloat(style.paddingLeft) || 0) * pxToInch * scale,
8027
+ ];
8028
+ }
8029
+
8030
+ function getSoftEdges(filterStr, scale) {
8031
+ if (!filterStr || filterStr === 'none') return null;
8032
+ const match = filterStr.match(/blur\(([\d.]+)px\)/);
8033
+ if (match) return parseFloat(match[1]) * 0.75 * scale;
8034
+ return null;
8035
+ }
8036
+
8037
+ function getTextStyle(style, scale) {
8038
+ let colorObj = parseColor(style.color);
8039
+
8040
+ const bgClip = style.webkitBackgroundClip || style.backgroundClip;
8041
+ if (colorObj.opacity === 0 && bgClip === 'text') {
8042
+ const fallback = getGradientFallbackColor(style.backgroundImage);
8043
+ if (fallback) colorObj = parseColor(fallback);
8044
+ }
8045
+
8046
+ return {
8047
+ color: colorObj.hex || '000000',
8048
+ fontFace: style.fontFamily.split(',')[0].replace(/['"]/g, ''),
8049
+ fontSize: parseFloat(style.fontSize) * 0.75 * scale,
8050
+ bold: parseInt(style.fontWeight) >= 600,
8051
+ italic: style.fontStyle === 'italic',
8052
+ underline: style.textDecoration.includes('underline'),
8053
+ };
8054
+ }
8055
+
8056
+ /**
8057
+ * Determines if a given DOM node is primarily a text container.
8058
+ */
8059
+ function isTextContainer(node) {
8060
+ const hasText = node.textContent.trim().length > 0;
8061
+ if (!hasText) return false;
8062
+
8063
+ const children = Array.from(node.children);
8064
+ if (children.length === 0) return true;
8065
+
8066
+ // Check if children are purely inline text formatting or visual shapes
8067
+ const isSafeInline = (el) => {
8068
+ // 1. Reject Web Components / Icons / Images
8069
+ if (el.tagName.includes('-')) return false;
8070
+ if (el.tagName === 'IMG' || el.tagName === 'SVG') return false;
8071
+
8072
+ const style = window.getComputedStyle(el);
8073
+ const display = style.display;
8074
+
8075
+ // 2. Initial check: Must be a standard inline tag OR display:inline
8076
+ const isInlineTag = ['SPAN', 'B', 'STRONG', 'EM', 'I', 'A', 'SMALL', 'MARK'].includes(el.tagName);
8077
+ const isInlineDisplay = display.includes('inline');
8078
+
8079
+ if (!isInlineTag && !isInlineDisplay) return false;
8080
+
8081
+ // 3. CRITICAL FIX: Check for Structural Styling
8082
+ // PPTX Text Runs (parts of a text line) CANNOT have backgrounds, borders, or padding.
8083
+ // If a child element has these, the parent is NOT a simple text container;
8084
+ // it is a layout container composed of styled blocks.
8085
+ const bgColor = parseColor(style.backgroundColor);
8086
+ const hasVisibleBg = bgColor.hex && bgColor.opacity > 0;
8087
+ const hasBorder = parseFloat(style.borderWidth) > 0 && parseColor(style.borderColor).opacity > 0;
8088
+
8089
+ if (hasVisibleBg || hasBorder) {
8090
+ return false;
8091
+ }
8092
+
8093
+ // 4. Check for empty shapes (visual objects without text, like dots)
8094
+ const hasContent = el.textContent.trim().length > 0;
8095
+ if (!hasContent && (hasVisibleBg || hasBorder)) {
8096
+ return false;
8097
+ }
8098
+
8099
+ return true;
8100
+ };
8101
+
8102
+ return children.every(isSafeInline);
8103
+ }
8104
+
8105
+ function getRotation(transformStr) {
8106
+ if (!transformStr || transformStr === 'none') return 0;
8107
+ const values = transformStr.split('(')[1].split(')')[0].split(',');
8108
+ if (values.length < 4) return 0;
8109
+ const a = parseFloat(values[0]);
8110
+ const b = parseFloat(values[1]);
8111
+ return Math.round(Math.atan2(b, a) * (180 / Math.PI));
8112
+ }
8113
+
8114
+ function getVisibleShadow(shadowStr, scale) {
8115
+ if (!shadowStr || shadowStr === 'none') return null;
8116
+ const shadows = shadowStr.split(/,(?![^()]*\))/);
8117
+ for (let s of shadows) {
8118
+ s = s.trim();
8119
+ if (s.startsWith('rgba(0, 0, 0, 0)')) continue;
8120
+ const match = s.match(
8121
+ /(rgba?\([^)]+\)|#[0-9a-fA-F]+)\s+(-?[\d.]+)px\s+(-?[\d.]+)px\s+([\d.]+)px/
8122
+ );
8123
+ if (match) {
8124
+ const colorStr = match[1];
8125
+ const x = parseFloat(match[2]);
8126
+ const y = parseFloat(match[3]);
8127
+ const blur = parseFloat(match[4]);
8128
+ const distance = Math.sqrt(x * x + y * y);
8129
+ let angle = Math.atan2(y, x) * (180 / Math.PI);
8130
+ if (angle < 0) angle += 360;
8131
+ const colorObj = parseColor(colorStr);
8132
+ return {
8133
+ type: 'outer',
8134
+ angle: angle,
8135
+ blur: blur * 0.75 * scale,
8136
+ offset: distance * 0.75 * scale,
8137
+ color: colorObj.hex || '000000',
8138
+ opacity: colorObj.opacity,
8139
+ };
8140
+ }
8141
+ }
8142
+ return null;
8143
+ }
8144
+
8145
+ function generateGradientSVG(w, h, bgString, radius, border) {
8146
+ try {
8147
+ const match = bgString.match(/linear-gradient\((.*)\)/);
8148
+ if (!match) return null;
8149
+ const content = match[1];
8150
+ const parts = content.split(/,(?![^()]*\))/).map((p) => p.trim());
8151
+
8152
+ let x1 = '0%',
8153
+ y1 = '0%',
8154
+ x2 = '0%',
8155
+ y2 = '100%';
8156
+ let stopsStartIdx = 0;
8157
+ if (parts[0].includes('to right')) {
8158
+ x1 = '0%';
8159
+ x2 = '100%';
8160
+ y2 = '0%';
8161
+ stopsStartIdx = 1;
8162
+ } else if (parts[0].includes('to left')) {
8163
+ x1 = '100%';
8164
+ x2 = '0%';
8165
+ y2 = '0%';
8166
+ stopsStartIdx = 1;
8167
+ } else if (parts[0].includes('to top')) {
8168
+ y1 = '100%';
8169
+ y2 = '0%';
8170
+ stopsStartIdx = 1;
8171
+ } else if (parts[0].includes('to bottom')) {
8172
+ y1 = '0%';
8173
+ y2 = '100%';
8174
+ stopsStartIdx = 1;
8175
+ }
8176
+
8177
+ let stopsXML = '';
8178
+ const stopParts = parts.slice(stopsStartIdx);
8179
+ stopParts.forEach((part, idx) => {
8180
+ let color = part;
8181
+ let offset = Math.round((idx / (stopParts.length - 1)) * 100) + '%';
8182
+ const posMatch = part.match(/(.*?)\s+(\d+(\.\d+)?%?)$/);
8183
+ if (posMatch) {
8184
+ color = posMatch[1];
8185
+ offset = posMatch[2];
8186
+ }
8187
+ let opacity = 1;
8188
+ if (color.includes('rgba')) {
8189
+ const rgba = color.match(/[\d.]+/g);
8190
+ if (rgba && rgba.length > 3) {
8191
+ opacity = rgba[3];
8192
+ color = `rgb(${rgba[0]},${rgba[1]},${rgba[2]})`;
8193
+ }
8194
+ }
8195
+ stopsXML += `<stop offset="${offset}" stop-color="${color}" stop-opacity="${opacity}"/>`;
8196
+ });
8197
+
8198
+ let strokeAttr = '';
8199
+ if (border) {
8200
+ strokeAttr = `stroke="#${border.color}" stroke-width="${border.width}"`;
8201
+ }
8202
+
8203
+ const svg = `
8204
+ <svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">
8205
+ <defs><linearGradient id="grad" x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}">${stopsXML}</linearGradient></defs>
8206
+ <rect x="0" y="0" width="${w}" height="${h}" rx="${radius}" ry="${radius}" fill="url(#grad)" ${strokeAttr} />
8207
+ </svg>`;
8208
+ return 'data:image/svg+xml;base64,' + btoa(svg);
8209
+ } catch {
8210
+ return null;
8211
+ }
8212
+ }
8213
+
8214
+ function generateBlurredSVG(w, h, color, radius, blurPx) {
8215
+ const padding = blurPx * 3;
8216
+ const fullW = w + padding * 2;
8217
+ const fullH = h + padding * 2;
8218
+ const x = padding;
8219
+ const y = padding;
8220
+ let shapeTag = '';
8221
+ const isCircle = radius >= Math.min(w, h) / 2 - 1 && Math.abs(w - h) < 2;
8222
+
8223
+ if (isCircle) {
8224
+ const cx = x + w / 2;
8225
+ const cy = y + h / 2;
8226
+ const rx = w / 2;
8227
+ const ry = h / 2;
8228
+ shapeTag = `<ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" fill="#${color}" filter="url(#f1)" />`;
8229
+ } else {
8230
+ shapeTag = `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${radius}" ry="${radius}" fill="#${color}" filter="url(#f1)" />`;
8231
+ }
8232
+
8233
+ const svg = `
8234
+ <svg xmlns="http://www.w3.org/2000/svg" width="${fullW}" height="${fullH}" viewBox="0 0 ${fullW} ${fullH}">
8235
+ <defs>
8236
+ <filter id="f1" x="-50%" y="-50%" width="200%" height="200%">
8237
+ <feGaussianBlur in="SourceGraphic" stdDeviation="${blurPx}" />
8238
+ </filter>
8239
+ </defs>
8240
+ ${shapeTag}
8241
+ </svg>`;
8242
+
8243
+ return {
8244
+ data: 'data:image/svg+xml;base64,' + btoa(svg),
8245
+ padding: padding,
8246
+ };
8301
8247
  }
8302
8248
 
8303
8249
  // src/image-processor.js
@@ -8380,642 +8326,717 @@ async function getProcessedImage(src, targetW, targetH, radius) {
8380
8326
  });
8381
8327
  }
8382
8328
 
8383
- // src/index.js
8384
-
8385
- // Normalize import
8386
- const PptxGenJS = PptxGenJSImport?.default ?? PptxGenJSImport;
8387
-
8388
- const PPI = 96;
8389
- const PX_TO_INCH = 1 / PPI;
8390
-
8391
- /**
8392
- * Main export function. Accepts single element or an array.
8393
- * @param {HTMLElement | string | Array<HTMLElement | string>} target - The root element(s) to convert.
8394
- * @param {Object} options - { fileName: string }
8395
- */
8396
- async function exportToPptx(target, options = {}) {
8397
- const resolvePptxConstructor = (pkg) => {
8398
- if (!pkg) return null;
8399
- if (typeof pkg === 'function') return pkg;
8400
- if (pkg && typeof pkg.default === 'function') return pkg.default;
8401
- if (pkg && typeof pkg.PptxGenJS === 'function') return pkg.PptxGenJS;
8402
- if (pkg && pkg.PptxGenJS && typeof pkg.PptxGenJS.default === 'function')
8403
- return pkg.PptxGenJS.default;
8404
- return null;
8405
- };
8406
-
8407
- const PptxConstructor = resolvePptxConstructor(PptxGenJS);
8408
- if (!PptxConstructor) throw new Error('PptxGenJS constructor not found.');
8409
- const pptx = new PptxConstructor();
8410
- pptx.layout = 'LAYOUT_16x9';
8411
-
8412
- const elements = Array.isArray(target) ? target : [target];
8413
-
8414
- for (const el of elements) {
8415
- const root = typeof el === 'string' ? document.querySelector(el) : el;
8416
- if (!root) {
8417
- console.warn('Element not found, skipping slide:', el);
8418
- continue;
8419
- }
8420
- const slide = pptx.addSlide();
8421
- await processSlide(root, slide, pptx);
8422
- }
8423
-
8424
- const fileName = options.fileName || 'export.pptx';
8425
- pptx.writeFile({ fileName });
8426
- }
8427
-
8428
- /**
8429
- * Worker function to process a single DOM element into a single PPTX slide.
8430
- * @param {HTMLElement} root - The root element for this slide.
8431
- * @param {PptxGenJS.Slide} slide - The PPTX slide object to add content to.
8432
- * @param {PptxGenJS} pptx - The main PPTX instance.
8433
- */
8434
- async function processSlide(root, slide, pptx) {
8435
- const rootRect = root.getBoundingClientRect();
8436
- const PPTX_WIDTH_IN = 10;
8437
- const PPTX_HEIGHT_IN = 5.625;
8438
-
8439
- const contentWidthIn = rootRect.width * PX_TO_INCH;
8440
- const contentHeightIn = rootRect.height * PX_TO_INCH;
8441
- const scale = Math.min(PPTX_WIDTH_IN / contentWidthIn, PPTX_HEIGHT_IN / contentHeightIn);
8442
-
8443
- const layoutConfig = {
8444
- rootX: rootRect.x,
8445
- rootY: rootRect.y,
8446
- scale: scale,
8447
- offX: (PPTX_WIDTH_IN - contentWidthIn * scale) / 2,
8448
- offY: (PPTX_HEIGHT_IN - contentHeightIn * scale) / 2,
8449
- };
8450
-
8451
- const renderQueue = [];
8452
- let domOrderCounter = 0;
8453
-
8454
- async function collect(node) {
8455
- const order = domOrderCounter++;
8456
- const result = await createRenderItem(node, { ...layoutConfig, root }, order, pptx);
8457
- if (result) {
8458
- if (result.items) renderQueue.push(...result.items);
8459
- if (result.stopRecursion) return;
8460
- }
8461
- for (const child of node.children) await collect(child);
8462
- }
8463
-
8464
- await collect(root);
8465
-
8466
- renderQueue.sort((a, b) => {
8467
- if (a.zIndex !== b.zIndex) return a.zIndex - b.zIndex;
8468
- return a.domOrder - b.domOrder;
8469
- });
8470
-
8471
- for (const item of renderQueue) {
8472
- if (item.type === 'shape') slide.addShape(item.shapeType, item.options);
8473
- if (item.type === 'image') slide.addImage(item.options);
8474
- if (item.type === 'text') slide.addText(item.textParts, item.options);
8475
- }
8476
- }
8477
-
8478
- async function elementToCanvasImage(node, widthPx, heightPx, root) {
8479
- return new Promise((resolve) => {
8480
- const width = Math.ceil(widthPx);
8481
- const height = Math.ceil(heightPx);
8482
-
8483
- if (width <= 0 || height <= 0) {
8484
- resolve(null);
8485
- return;
8486
- }
8487
-
8488
- const style = window.getComputedStyle(node);
8489
-
8490
- html2canvas(root, {
8491
- width: root.scrollWidth,
8492
- height: root.scrollHeight,
8493
- useCORS: true,
8494
- allowTaint: true,
8495
- backgroundColor: null,
8496
- })
8497
- .then((canvas) => {
8498
- const rootCanvas = canvas;
8499
- const nodeRect = node.getBoundingClientRect();
8500
- const rootRect = root.getBoundingClientRect();
8501
- const sourceX = nodeRect.left - rootRect.left;
8502
- const sourceY = nodeRect.top - rootRect.top;
8503
-
8504
- const destCanvas = document.createElement('canvas');
8505
- destCanvas.width = width;
8506
- destCanvas.height = height;
8507
- const ctx = destCanvas.getContext('2d');
8508
-
8509
- ctx.drawImage(rootCanvas, sourceX, sourceY, width, height, 0, 0, width, height);
8510
-
8511
- // Parse radii
8512
- let tl = parseFloat(style.borderTopLeftRadius) || 0;
8513
- let tr = parseFloat(style.borderTopRightRadius) || 0;
8514
- let br = parseFloat(style.borderBottomRightRadius) || 0;
8515
- let bl = parseFloat(style.borderBottomLeftRadius) || 0;
8516
-
8517
- const f = Math.min(
8518
- width / (tl + tr) || Infinity,
8519
- height / (tr + br) || Infinity,
8520
- width / (br + bl) || Infinity,
8521
- height / (bl + tl) || Infinity
8522
- );
8523
-
8524
- if (f < 1) {
8525
- tl *= f;
8526
- tr *= f;
8527
- br *= f;
8528
- bl *= f;
8529
- }
8530
-
8531
- ctx.globalCompositeOperation = 'destination-in';
8532
- ctx.beginPath();
8533
- ctx.moveTo(tl, 0);
8534
- ctx.lineTo(width - tr, 0);
8535
- ctx.arcTo(width, 0, width, tr, tr);
8536
- ctx.lineTo(width, height - br);
8537
- ctx.arcTo(width, height, width - br, height, br);
8538
- ctx.lineTo(bl, height);
8539
- ctx.arcTo(0, height, 0, height - bl, bl);
8540
- ctx.lineTo(0, tl);
8541
- ctx.arcTo(0, 0, tl, 0, tl);
8542
- ctx.closePath();
8543
- ctx.fill();
8544
-
8545
- resolve(destCanvas.toDataURL('image/png'));
8546
- })
8547
- .catch(() => resolve(null));
8548
- });
8549
- }
8550
-
8551
- async function createRenderItem(node, config, domOrder, pptx) {
8552
- if (node.nodeType !== 1) return null;
8553
- const style = window.getComputedStyle(node);
8554
- if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0')
8555
- return null;
8556
-
8557
- const rect = node.getBoundingClientRect();
8558
- if (rect.width < 0.5 || rect.height < 0.5) return null;
8559
-
8560
- const zIndex = style.zIndex !== 'auto' ? parseInt(style.zIndex) : 0;
8561
- const rotation = getRotation(style.transform);
8562
- const elementOpacity = parseFloat(style.opacity);
8563
-
8564
- const widthPx = node.offsetWidth || rect.width;
8565
- const heightPx = node.offsetHeight || rect.height;
8566
- const unrotatedW = widthPx * PX_TO_INCH * config.scale;
8567
- const unrotatedH = heightPx * PX_TO_INCH * config.scale;
8568
- const centerX = rect.left + rect.width / 2;
8569
- const centerY = rect.top + rect.height / 2;
8570
-
8571
- let x = config.offX + (centerX - config.rootX) * PX_TO_INCH * config.scale - unrotatedW / 2;
8572
- let y = config.offY + (centerY - config.rootY) * PX_TO_INCH * config.scale - unrotatedH / 2;
8573
- let w = unrotatedW;
8574
- let h = unrotatedH;
8575
-
8576
- const items = [];
8577
-
8578
- if (node.nodeName.toUpperCase() === 'SVG') {
8579
- const pngData = await svgToPng(node);
8580
- if (pngData)
8581
- items.push({
8582
- type: 'image',
8583
- zIndex,
8584
- domOrder,
8585
- options: { data: pngData, x, y, w, h, rotate: rotation },
8586
- });
8587
- return { items, stopRecursion: true };
8588
- }
8589
-
8590
- // --- UPDATED IMG BLOCK START ---
8591
- if (node.tagName === 'IMG') {
8592
- // Extract individual corner radii
8593
- let radii = {
8594
- tl: parseFloat(style.borderTopLeftRadius) || 0,
8595
- tr: parseFloat(style.borderTopRightRadius) || 0,
8596
- br: parseFloat(style.borderBottomRightRadius) || 0,
8597
- bl: parseFloat(style.borderBottomLeftRadius) || 0,
8598
- };
8599
-
8600
- const hasAnyRadius = radii.tl > 0 || radii.tr > 0 || radii.br > 0 || radii.bl > 0;
8601
-
8602
- // Fallback: Check parent if image has no specific radius but parent clips it
8603
- if (!hasAnyRadius) {
8604
- const parent = node.parentElement;
8605
- const parentStyle = window.getComputedStyle(parent);
8606
- if (parentStyle.overflow !== 'visible') {
8607
- const pRadii = {
8608
- tl: parseFloat(parentStyle.borderTopLeftRadius) || 0,
8609
- tr: parseFloat(parentStyle.borderTopRightRadius) || 0,
8610
- br: parseFloat(parentStyle.borderBottomRightRadius) || 0,
8611
- bl: parseFloat(parentStyle.borderBottomLeftRadius) || 0,
8612
- };
8613
- // Simple heuristic: If image takes up full size of parent, inherit radii.
8614
- // For complex grids (like slide-1), this blindly applies parent radius.
8615
- // In a perfect world, we'd calculate intersection, but for now we apply parent radius
8616
- // if the image is close to the parent's size, effectively masking it.
8617
- const pRect = parent.getBoundingClientRect();
8618
- if (Math.abs(pRect.width - rect.width) < 5 && Math.abs(pRect.height - rect.height) < 5) {
8619
- radii = pRadii;
8620
- }
8621
- }
8622
- }
8623
-
8624
- const processed = await getProcessedImage(node.src, widthPx, heightPx, radii);
8625
- if (processed)
8626
- items.push({
8627
- type: 'image',
8628
- zIndex,
8629
- domOrder,
8630
- options: { data: processed, x, y, w, h, rotate: rotation },
8631
- });
8632
- return { items, stopRecursion: true };
8633
- }
8634
- // --- UPDATED IMG BLOCK END ---
8635
-
8636
- // Radii processing for Divs/Shapes
8637
- const borderRadiusValue = parseFloat(style.borderRadius) || 0;
8638
- const borderBottomLeftRadius = parseFloat(style.borderBottomLeftRadius) || 0;
8639
- const borderBottomRightRadius = parseFloat(style.borderBottomRightRadius) || 0;
8640
- const borderTopLeftRadius = parseFloat(style.borderTopLeftRadius) || 0;
8641
- const borderTopRightRadius = parseFloat(style.borderTopRightRadius) || 0;
8642
-
8643
- const hasPartialBorderRadius =
8644
- (borderBottomLeftRadius > 0 && borderBottomLeftRadius !== borderRadiusValue) ||
8645
- (borderBottomRightRadius > 0 && borderBottomRightRadius !== borderRadiusValue) ||
8646
- (borderTopLeftRadius > 0 && borderTopLeftRadius !== borderRadiusValue) ||
8647
- (borderTopRightRadius > 0 && borderTopRightRadius !== borderRadiusValue) ||
8648
- (borderRadiusValue === 0 &&
8649
- (borderBottomLeftRadius ||
8650
- borderBottomRightRadius ||
8651
- borderTopLeftRadius ||
8652
- borderTopRightRadius));
8653
-
8654
- // Allow clipped elements to be rendered via canvas
8655
- if (hasPartialBorderRadius && isClippedByParent(node)) {
8656
- const marginLeft = parseFloat(style.marginLeft) || 0;
8657
- const marginTop = parseFloat(style.marginTop) || 0;
8658
- x += marginLeft * PX_TO_INCH * config.scale;
8659
- y += marginTop * PX_TO_INCH * config.scale;
8660
-
8661
- const canvasImageData = await elementToCanvasImage(node, widthPx, heightPx, config.root);
8662
- if (canvasImageData) {
8663
- items.push({
8664
- type: 'image',
8665
- zIndex,
8666
- domOrder,
8667
- options: { data: canvasImageData, x, y, w, h, rotate: rotation },
8668
- });
8669
- return { items, stopRecursion: true };
8670
- }
8671
- }
8672
-
8673
- const bgColorObj = parseColor(style.backgroundColor);
8674
- const bgClip = style.webkitBackgroundClip || style.backgroundClip;
8675
- const isBgClipText = bgClip === 'text';
8676
- const hasGradient =
8677
- !isBgClipText && style.backgroundImage && style.backgroundImage.includes('linear-gradient');
8678
-
8679
- const borderColorObj = parseColor(style.borderColor);
8680
- const borderWidth = parseFloat(style.borderWidth);
8681
- const hasBorder = borderWidth > 0 && borderColorObj.hex;
8682
-
8683
- const borderInfo = getBorderInfo(style, config.scale);
8684
- const hasUniformBorder = borderInfo.type === 'uniform';
8685
- const hasCompositeBorder = borderInfo.type === 'composite';
8686
-
8687
- const shadowStr = style.boxShadow;
8688
- const hasShadow = shadowStr && shadowStr !== 'none';
8689
- const softEdge = getSoftEdges(style.filter, config.scale);
8690
-
8691
- let isImageWrapper = false;
8692
- const imgChild = Array.from(node.children).find((c) => c.tagName === 'IMG');
8693
- if (imgChild) {
8694
- const childW = imgChild.offsetWidth || imgChild.getBoundingClientRect().width;
8695
- const childH = imgChild.offsetHeight || imgChild.getBoundingClientRect().height;
8696
- if (childW >= widthPx - 2 && childH >= heightPx - 2) isImageWrapper = true;
8697
- }
8698
-
8699
- let textPayload = null;
8700
- const isText = isTextContainer(node);
8701
-
8702
- if (isText) {
8703
- const textParts = [];
8704
- const isList = style.display === 'list-item';
8705
- if (isList) {
8706
- const fontSizePt = parseFloat(style.fontSize) * 0.75 * config.scale;
8707
- const bulletShift = (parseFloat(style.fontSize) || 16) * PX_TO_INCH * config.scale * 1.5;
8708
- x -= bulletShift;
8709
- w += bulletShift;
8710
- textParts.push({
8711
- text: '• ',
8712
- options: {
8713
- color: parseColor(style.color).hex || '000000',
8714
- fontSize: fontSizePt,
8715
- },
8716
- });
8717
- }
8718
-
8719
- node.childNodes.forEach((child, index) => {
8720
- let textVal = child.nodeType === 3 ? child.nodeValue : child.textContent;
8721
- let nodeStyle = child.nodeType === 1 ? window.getComputedStyle(child) : style;
8722
- textVal = textVal.replace(/[\n\r\t]+/g, ' ').replace(/\s{2,}/g, ' ');
8723
- if (index === 0 && !isList) textVal = textVal.trimStart();
8724
- else if (index === 0) textVal = textVal.trimStart();
8725
- if (index === node.childNodes.length - 1) textVal = textVal.trimEnd();
8726
- if (nodeStyle.textTransform === 'uppercase') textVal = textVal.toUpperCase();
8727
- if (nodeStyle.textTransform === 'lowercase') textVal = textVal.toLowerCase();
8728
-
8729
- if (textVal.length > 0) {
8730
- textParts.push({
8731
- text: textVal,
8732
- options: getTextStyle(nodeStyle, config.scale),
8733
- });
8734
- }
8735
- });
8736
-
8737
- if (textParts.length > 0) {
8738
- let align = style.textAlign || 'left';
8739
- if (align === 'start') align = 'left';
8740
- if (align === 'end') align = 'right';
8741
- let valign = 'top';
8742
- if (style.alignItems === 'center') valign = 'middle';
8743
- if (style.justifyContent === 'center' && style.display.includes('flex')) align = 'center';
8744
-
8745
- const pt = parseFloat(style.paddingTop) || 0;
8746
- const pb = parseFloat(style.paddingBottom) || 0;
8747
- if (Math.abs(pt - pb) < 2 && bgColorObj.hex) valign = 'middle';
8748
-
8749
- let padding = getPadding(style, config.scale);
8750
- if (align === 'center' && valign === 'middle') padding = [0, 0, 0, 0];
8751
-
8752
- textPayload = { text: textParts, align, valign, inset: padding };
8753
- }
8754
- }
8755
-
8756
- if (hasGradient || (softEdge && bgColorObj.hex && !isImageWrapper)) {
8757
- let bgData = null;
8758
- let padIn = 0;
8759
- if (softEdge) {
8760
- const svgInfo = generateBlurredSVG(
8761
- widthPx,
8762
- heightPx,
8763
- bgColorObj.hex,
8764
- borderRadiusValue,
8765
- softEdge
8766
- );
8767
- bgData = svgInfo.data;
8768
- padIn = svgInfo.padding * PX_TO_INCH * config.scale;
8769
- } else {
8770
- bgData = generateGradientSVG(
8771
- widthPx,
8772
- heightPx,
8773
- style.backgroundImage,
8774
- borderRadiusValue,
8775
- hasBorder ? { color: borderColorObj.hex, width: borderWidth } : null
8776
- );
8777
- }
8778
-
8779
- if (bgData) {
8780
- items.push({
8781
- type: 'image',
8782
- zIndex,
8783
- domOrder,
8784
- options: {
8785
- data: bgData,
8786
- x: x - padIn,
8787
- y: y - padIn,
8788
- w: w + padIn * 2,
8789
- h: h + padIn * 2,
8790
- rotate: rotation,
8791
- },
8792
- });
8793
- }
8794
-
8795
- if (textPayload) {
8796
- items.push({
8797
- type: 'text',
8798
- zIndex: zIndex + 1,
8799
- domOrder,
8800
- textParts: textPayload.text,
8801
- options: {
8802
- x,
8803
- y,
8804
- w,
8805
- h,
8806
- align: textPayload.align,
8807
- valign: textPayload.valign,
8808
- inset: textPayload.inset,
8809
- rotate: rotation,
8810
- margin: 0,
8811
- wrap: true,
8812
- autoFit: false,
8813
- },
8814
- });
8815
- }
8816
- if (hasCompositeBorder) {
8817
- // Add border shapes after the main background
8818
- const borderItems = createCompositeBorderItems(
8819
- borderInfo.sides,
8820
- x,
8821
- y,
8822
- w,
8823
- h,
8824
- config.scale,
8825
- zIndex,
8826
- domOrder
8827
- );
8828
- items.push(...borderItems);
8829
- }
8830
- } else if (
8831
- (bgColorObj.hex && !isImageWrapper) ||
8832
- hasUniformBorder ||
8833
- hasCompositeBorder ||
8834
- hasShadow ||
8835
- textPayload
8836
- ) {
8837
- const finalAlpha = elementOpacity * bgColorObj.opacity;
8838
- const transparency = (1 - finalAlpha) * 100;
8839
- const useSolidFill = bgColorObj.hex && !isImageWrapper;
8840
-
8841
- if (hasPartialBorderRadius && useSolidFill && !textPayload) {
8842
- const shapeSvg = generateCustomShapeSVG(
8843
- widthPx,
8844
- heightPx,
8845
- bgColorObj.hex,
8846
- bgColorObj.opacity,
8847
- {
8848
- tl: parseFloat(style.borderTopLeftRadius) || 0,
8849
- tr: parseFloat(style.borderTopRightRadius) || 0,
8850
- br: parseFloat(style.borderBottomRightRadius) || 0,
8851
- bl: parseFloat(style.borderBottomLeftRadius) || 0,
8852
- }
8853
- );
8854
-
8855
- items.push({
8856
- type: 'image',
8857
- zIndex,
8858
- domOrder,
8859
- options: {
8860
- data: shapeSvg,
8861
- x,
8862
- y,
8863
- w,
8864
- h,
8865
- rotate: rotation,
8866
- },
8867
- });
8868
- } else {
8869
- const shapeOpts = {
8870
- x,
8871
- y,
8872
- w,
8873
- h,
8874
- rotate: rotation,
8875
- fill: useSolidFill
8876
- ? { color: bgColorObj.hex, transparency: transparency }
8877
- : { type: 'none' },
8878
- line: hasUniformBorder ? borderInfo.options : null,
8879
- };
8880
-
8881
- if (hasShadow) {
8882
- shapeOpts.shadow = getVisibleShadow(shadowStr, config.scale);
8883
- }
8884
-
8885
- const borderRadius = parseFloat(style.borderRadius) || 0;
8886
- const aspectRatio = Math.max(widthPx, heightPx) / Math.min(widthPx, heightPx);
8887
- const isCircle = aspectRatio < 1.1 && borderRadius >= Math.min(widthPx, heightPx) / 2 - 1;
8888
-
8889
- let shapeType = pptx.ShapeType.rect;
8890
- if (isCircle) shapeType = pptx.ShapeType.ellipse;
8891
- else if (borderRadius > 0) {
8892
- shapeType = pptx.ShapeType.roundRect;
8893
- shapeOpts.rectRadius = Math.min(0.5, borderRadius / Math.min(widthPx, heightPx));
8894
- }
8895
-
8896
- if (textPayload) {
8897
- const textOptions = {
8898
- shape: shapeType,
8899
- ...shapeOpts,
8900
- align: textPayload.align,
8901
- valign: textPayload.valign,
8902
- inset: textPayload.inset,
8903
- margin: 0,
8904
- wrap: true,
8905
- autoFit: false,
8906
- };
8907
- items.push({
8908
- type: 'text',
8909
- zIndex,
8910
- domOrder,
8911
- textParts: textPayload.text,
8912
- options: textOptions,
8913
- });
8914
- } else if (!hasPartialBorderRadius) {
8915
- items.push({
8916
- type: 'shape',
8917
- zIndex,
8918
- domOrder,
8919
- shapeType,
8920
- options: shapeOpts,
8921
- });
8922
- }
8923
- }
8924
-
8925
- if (hasCompositeBorder) {
8926
- const borderSvgData = generateCompositeBorderSVG(
8927
- widthPx,
8928
- heightPx,
8929
- borderRadiusValue,
8930
- borderInfo.sides
8931
- );
8932
- if (borderSvgData) {
8933
- items.push({
8934
- type: 'image',
8935
- zIndex: zIndex + 1,
8936
- domOrder,
8937
- options: { data: borderSvgData, x, y, w, h, rotate: rotation },
8938
- });
8939
- }
8940
- }
8941
- }
8942
-
8943
- return { items, stopRecursion: !!textPayload };
8944
- }
8945
-
8946
- /**
8947
- * Helper function to create individual border shapes
8948
- */
8949
- function createCompositeBorderItems(sides, x, y, w, h, scale, zIndex, domOrder) {
8950
- const items = [];
8951
- const pxToInch = 1 / 96;
8952
-
8953
- // TOP BORDER
8954
- if (sides.top.width > 0) {
8955
- items.push({
8956
- type: 'shape',
8957
- zIndex: zIndex + 1,
8958
- domOrder,
8959
- shapeType: 'rect',
8960
- options: {
8961
- x: x,
8962
- y: y,
8963
- w: w,
8964
- h: sides.top.width * pxToInch * scale,
8965
- fill: { color: sides.top.color },
8966
- },
8967
- });
8968
- }
8969
- // RIGHT BORDER
8970
- if (sides.right.width > 0) {
8971
- items.push({
8972
- type: 'shape',
8973
- zIndex: zIndex + 1,
8974
- domOrder,
8975
- shapeType: 'rect',
8976
- options: {
8977
- x: x + w - sides.right.width * pxToInch * scale,
8978
- y: y,
8979
- w: sides.right.width * pxToInch * scale,
8980
- h: h,
8981
- fill: { color: sides.right.color },
8982
- },
8983
- });
8984
- }
8985
- // BOTTOM BORDER
8986
- if (sides.bottom.width > 0) {
8987
- items.push({
8988
- type: 'shape',
8989
- zIndex: zIndex + 1,
8990
- domOrder,
8991
- shapeType: 'rect',
8992
- options: {
8993
- x: x,
8994
- y: y + h - sides.bottom.width * pxToInch * scale,
8995
- w: w,
8996
- h: sides.bottom.width * pxToInch * scale,
8997
- fill: { color: sides.bottom.color },
8998
- },
8999
- });
9000
- }
9001
- // LEFT BORDER
9002
- if (sides.left.width > 0) {
9003
- items.push({
9004
- type: 'shape',
9005
- zIndex: zIndex + 1,
9006
- domOrder,
9007
- shapeType: 'rect',
9008
- options: {
9009
- x: x,
9010
- y: y,
9011
- w: sides.left.width * pxToInch * scale,
9012
- h: h,
9013
- fill: { color: sides.left.color },
9014
- },
9015
- });
9016
- }
9017
-
9018
- return items;
8329
+ // src/index.js
8330
+
8331
+ // Normalize import
8332
+ const PptxGenJS = PptxGenJSImport?.default ?? PptxGenJSImport;
8333
+
8334
+ const PPI = 96;
8335
+ const PX_TO_INCH = 1 / PPI;
8336
+
8337
+ /**
8338
+ * Main export function. Accepts single element or an array.
8339
+ * @param {HTMLElement | string | Array<HTMLElement | string>} target - The root element(s) to convert.
8340
+ * @param {Object} options - { fileName: string }
8341
+ */
8342
+ async function exportToPptx(target, options = {}) {
8343
+ const resolvePptxConstructor = (pkg) => {
8344
+ if (!pkg) return null;
8345
+ if (typeof pkg === 'function') return pkg;
8346
+ if (pkg && typeof pkg.default === 'function') return pkg.default;
8347
+ if (pkg && typeof pkg.PptxGenJS === 'function') return pkg.PptxGenJS;
8348
+ if (pkg && pkg.PptxGenJS && typeof pkg.PptxGenJS.default === 'function')
8349
+ return pkg.PptxGenJS.default;
8350
+ return null;
8351
+ };
8352
+
8353
+ const PptxConstructor = resolvePptxConstructor(PptxGenJS);
8354
+ if (!PptxConstructor) throw new Error('PptxGenJS constructor not found.');
8355
+ const pptx = new PptxConstructor();
8356
+ pptx.layout = 'LAYOUT_16x9';
8357
+
8358
+ const elements = Array.isArray(target) ? target : [target];
8359
+
8360
+ for (const el of elements) {
8361
+ const root = typeof el === 'string' ? document.querySelector(el) : el;
8362
+ if (!root) {
8363
+ console.warn('Element not found, skipping slide:', el);
8364
+ continue;
8365
+ }
8366
+ const slide = pptx.addSlide();
8367
+ await processSlide(root, slide, pptx);
8368
+ }
8369
+
8370
+ const fileName = options.fileName || 'export.pptx';
8371
+ pptx.writeFile({ fileName });
8372
+ }
8373
+
8374
+ /**
8375
+ * Worker function to process a single DOM element into a single PPTX slide.
8376
+ * @param {HTMLElement} root - The root element for this slide.
8377
+ * @param {PptxGenJS.Slide} slide - The PPTX slide object to add content to.
8378
+ * @param {PptxGenJS} pptx - The main PPTX instance.
8379
+ */
8380
+ async function processSlide(root, slide, pptx) {
8381
+ const rootRect = root.getBoundingClientRect();
8382
+ const PPTX_WIDTH_IN = 10;
8383
+ const PPTX_HEIGHT_IN = 5.625;
8384
+
8385
+ const contentWidthIn = rootRect.width * PX_TO_INCH;
8386
+ const contentHeightIn = rootRect.height * PX_TO_INCH;
8387
+ const scale = Math.min(PPTX_WIDTH_IN / contentWidthIn, PPTX_HEIGHT_IN / contentHeightIn);
8388
+
8389
+ const layoutConfig = {
8390
+ rootX: rootRect.x,
8391
+ rootY: rootRect.y,
8392
+ scale: scale,
8393
+ offX: (PPTX_WIDTH_IN - contentWidthIn * scale) / 2,
8394
+ offY: (PPTX_HEIGHT_IN - contentHeightIn * scale) / 2,
8395
+ };
8396
+
8397
+ const renderQueue = [];
8398
+ const asyncTasks = []; // Queue for heavy operations (Images, Canvas)
8399
+ let domOrderCounter = 0;
8400
+
8401
+ // Sync Traversal Function
8402
+ function collect(node, parentZIndex) {
8403
+ const order = domOrderCounter++;
8404
+
8405
+ let currentZ = parentZIndex;
8406
+ let nodeStyle = null;
8407
+ const nodeType = node.nodeType;
8408
+
8409
+ if (nodeType === 1) {
8410
+ nodeStyle = window.getComputedStyle(node);
8411
+ // Optimization: Skip completely hidden elements immediately
8412
+ if (
8413
+ nodeStyle.display === 'none' ||
8414
+ nodeStyle.visibility === 'hidden' ||
8415
+ nodeStyle.opacity === '0'
8416
+ ) {
8417
+ return;
8418
+ }
8419
+ if (nodeStyle.zIndex !== 'auto') {
8420
+ currentZ = parseInt(nodeStyle.zIndex);
8421
+ }
8422
+ }
8423
+
8424
+ // Prepare the item. If it needs async work, it returns a 'job'
8425
+ const result = prepareRenderItem(
8426
+ node,
8427
+ { ...layoutConfig, root },
8428
+ order,
8429
+ pptx,
8430
+ currentZ,
8431
+ nodeStyle
8432
+ );
8433
+
8434
+ if (result) {
8435
+ if (result.items) {
8436
+ // Push items immediately to queue (data might be missing but filled later)
8437
+ renderQueue.push(...result.items);
8438
+ }
8439
+ if (result.job) {
8440
+ // Push the promise-returning function to the task list
8441
+ asyncTasks.push(result.job);
8442
+ }
8443
+ if (result.stopRecursion) return;
8444
+ }
8445
+
8446
+ // Recurse children synchronously
8447
+ const childNodes = node.childNodes;
8448
+ for (let i = 0; i < childNodes.length; i++) {
8449
+ collect(childNodes[i], currentZ);
8450
+ }
8451
+ }
8452
+
8453
+ // 1. Traverse and build the structure (Fast)
8454
+ collect(root, 0);
8455
+
8456
+ // 2. Execute all heavy tasks in parallel (Fast)
8457
+ if (asyncTasks.length > 0) {
8458
+ await Promise.all(asyncTasks.map((task) => task()));
8459
+ }
8460
+
8461
+ // 3. Cleanup and Sort
8462
+ // Remove items that failed to generate data (marked with skip)
8463
+ const finalQueue = renderQueue.filter(
8464
+ (item) => !item.skip && (item.type !== 'image' || item.options.data)
8465
+ );
8466
+
8467
+ finalQueue.sort((a, b) => {
8468
+ if (a.zIndex !== b.zIndex) return a.zIndex - b.zIndex;
8469
+ return a.domOrder - b.domOrder;
8470
+ });
8471
+
8472
+ // 4. Add to Slide
8473
+ for (const item of finalQueue) {
8474
+ if (item.type === 'shape') slide.addShape(item.shapeType, item.options);
8475
+ if (item.type === 'image') slide.addImage(item.options);
8476
+ if (item.type === 'text') slide.addText(item.textParts, item.options);
8477
+ }
8478
+ }
8479
+
8480
+ /**
8481
+ * Optimized html2canvas wrapper
8482
+ * Now strictly captures the node itself, not the root.
8483
+ */
8484
+ async function elementToCanvasImage(node, widthPx, heightPx) {
8485
+ return new Promise((resolve) => {
8486
+ const width = Math.max(Math.ceil(widthPx), 1);
8487
+ const height = Math.max(Math.ceil(heightPx), 1);
8488
+ const style = window.getComputedStyle(node);
8489
+
8490
+ // Optimized: Capture ONLY the specific node
8491
+ html2canvas(node, {
8492
+ backgroundColor: null,
8493
+ logging: false,
8494
+ scale: 2, // Slight quality boost
8495
+ })
8496
+ .then((canvas) => {
8497
+ const destCanvas = document.createElement('canvas');
8498
+ destCanvas.width = width;
8499
+ destCanvas.height = height;
8500
+ const ctx = destCanvas.getContext('2d');
8501
+
8502
+ // Draw the captured canvas into our sized canvas
8503
+ // html2canvas might return a larger canvas if scale > 1, so we fit it
8504
+ ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, width, height);
8505
+
8506
+ // Apply border radius clipping
8507
+ let tl = parseFloat(style.borderTopLeftRadius) || 0;
8508
+ let tr = parseFloat(style.borderTopRightRadius) || 0;
8509
+ let br = parseFloat(style.borderBottomRightRadius) || 0;
8510
+ let bl = parseFloat(style.borderBottomLeftRadius) || 0;
8511
+
8512
+ const f = Math.min(
8513
+ width / (tl + tr) || Infinity,
8514
+ height / (tr + br) || Infinity,
8515
+ width / (br + bl) || Infinity,
8516
+ height / (bl + tl) || Infinity
8517
+ );
8518
+
8519
+ if (f < 1) {
8520
+ tl *= f;
8521
+ tr *= f;
8522
+ br *= f;
8523
+ bl *= f;
8524
+ }
8525
+
8526
+ if (tl + tr + br + bl > 0) {
8527
+ ctx.globalCompositeOperation = 'destination-in';
8528
+ ctx.beginPath();
8529
+ ctx.moveTo(tl, 0);
8530
+ ctx.lineTo(width - tr, 0);
8531
+ ctx.arcTo(width, 0, width, tr, tr);
8532
+ ctx.lineTo(width, height - br);
8533
+ ctx.arcTo(width, height, width - br, height, br);
8534
+ ctx.lineTo(bl, height);
8535
+ ctx.arcTo(0, height, 0, height - bl, bl);
8536
+ ctx.lineTo(0, tl);
8537
+ ctx.arcTo(0, 0, tl, 0, tl);
8538
+ ctx.closePath();
8539
+ ctx.fill();
8540
+ }
8541
+
8542
+ resolve(destCanvas.toDataURL('image/png'));
8543
+ })
8544
+ .catch((e) => {
8545
+ console.warn('Canvas capture failed for node', node, e);
8546
+ resolve(null);
8547
+ });
8548
+ });
8549
+ }
8550
+
8551
+ /**
8552
+ * Replaces createRenderItem.
8553
+ * Returns { items: [], job: () => Promise, stopRecursion: boolean }
8554
+ */
8555
+ function prepareRenderItem(node, config, domOrder, pptx, effectiveZIndex, computedStyle) {
8556
+ // 1. Text Node Handling
8557
+ if (node.nodeType === 3) {
8558
+ const textContent = node.nodeValue.trim();
8559
+ if (!textContent) return null;
8560
+
8561
+ const parent = node.parentElement;
8562
+ if (!parent) return null;
8563
+
8564
+ if (isTextContainer(parent)) return null; // Parent handles it
8565
+
8566
+ const range = document.createRange();
8567
+ range.selectNode(node);
8568
+ const rect = range.getBoundingClientRect();
8569
+ range.detach();
8570
+
8571
+ const style = window.getComputedStyle(parent);
8572
+ const widthPx = rect.width;
8573
+ const heightPx = rect.height;
8574
+ const unrotatedW = widthPx * PX_TO_INCH * config.scale;
8575
+ const unrotatedH = heightPx * PX_TO_INCH * config.scale;
8576
+
8577
+ const x = config.offX + (rect.left - config.rootX) * PX_TO_INCH * config.scale;
8578
+ const y = config.offY + (rect.top - config.rootY) * PX_TO_INCH * config.scale;
8579
+
8580
+ return {
8581
+ items: [
8582
+ {
8583
+ type: 'text',
8584
+ zIndex: effectiveZIndex,
8585
+ domOrder,
8586
+ textParts: [
8587
+ {
8588
+ text: textContent,
8589
+ options: getTextStyle(style, config.scale),
8590
+ },
8591
+ ],
8592
+ options: { x, y, w: unrotatedW, h: unrotatedH, margin: 0, autoFit: false },
8593
+ },
8594
+ ],
8595
+ stopRecursion: false,
8596
+ };
8597
+ }
8598
+
8599
+ if (node.nodeType !== 1) return null;
8600
+ const style = computedStyle; // Use pre-computed style
8601
+
8602
+ const rect = node.getBoundingClientRect();
8603
+ if (rect.width < 0.5 || rect.height < 0.5) return null;
8604
+
8605
+ const zIndex = effectiveZIndex;
8606
+ const rotation = getRotation(style.transform);
8607
+ const elementOpacity = parseFloat(style.opacity);
8608
+ const safeOpacity = isNaN(elementOpacity) ? 1 : elementOpacity;
8609
+
8610
+ const widthPx = node.offsetWidth || rect.width;
8611
+ const heightPx = node.offsetHeight || rect.height;
8612
+ const unrotatedW = widthPx * PX_TO_INCH * config.scale;
8613
+ const unrotatedH = heightPx * PX_TO_INCH * config.scale;
8614
+ const centerX = rect.left + rect.width / 2;
8615
+ const centerY = rect.top + rect.height / 2;
8616
+
8617
+ let x = config.offX + (centerX - config.rootX) * PX_TO_INCH * config.scale - unrotatedW / 2;
8618
+ let y = config.offY + (centerY - config.rootY) * PX_TO_INCH * config.scale - unrotatedH / 2;
8619
+ let w = unrotatedW;
8620
+ let h = unrotatedH;
8621
+
8622
+ const items = [];
8623
+
8624
+ // --- ASYNC JOB: SVGs / Icons ---
8625
+ if (
8626
+ node.nodeName.toUpperCase() === 'SVG' ||
8627
+ node.tagName.includes('-') ||
8628
+ node.tagName === 'ION-ICON'
8629
+ ) {
8630
+ const item = {
8631
+ type: 'image',
8632
+ zIndex,
8633
+ domOrder,
8634
+ options: { x, y, w, h, rotate: rotation, data: null }, // Data null initially
8635
+ };
8636
+
8637
+ // Create Job
8638
+ const job = async () => {
8639
+ const pngData = await elementToCanvasImage(node, widthPx, heightPx);
8640
+ if (pngData) item.options.data = pngData;
8641
+ else item.skip = true;
8642
+ };
8643
+
8644
+ return { items: [item], job, stopRecursion: true };
8645
+ }
8646
+
8647
+ // --- ASYNC JOB: IMG Tags ---
8648
+ if (node.tagName === 'IMG') {
8649
+ let radii = {
8650
+ tl: parseFloat(style.borderTopLeftRadius) || 0,
8651
+ tr: parseFloat(style.borderTopRightRadius) || 0,
8652
+ br: parseFloat(style.borderBottomRightRadius) || 0,
8653
+ bl: parseFloat(style.borderBottomLeftRadius) || 0,
8654
+ };
8655
+
8656
+ const hasAnyRadius = radii.tl > 0 || radii.tr > 0 || radii.br > 0 || radii.bl > 0;
8657
+ if (!hasAnyRadius) {
8658
+ const parent = node.parentElement;
8659
+ const parentStyle = window.getComputedStyle(parent);
8660
+ if (parentStyle.overflow !== 'visible') {
8661
+ const pRadii = {
8662
+ tl: parseFloat(parentStyle.borderTopLeftRadius) || 0,
8663
+ tr: parseFloat(parentStyle.borderTopRightRadius) || 0,
8664
+ br: parseFloat(parentStyle.borderBottomRightRadius) || 0,
8665
+ bl: parseFloat(parentStyle.borderBottomLeftRadius) || 0,
8666
+ };
8667
+ const pRect = parent.getBoundingClientRect();
8668
+ if (Math.abs(pRect.width - rect.width) < 5 && Math.abs(pRect.height - rect.height) < 5) {
8669
+ radii = pRadii;
8670
+ }
8671
+ }
8672
+ }
8673
+
8674
+ const item = {
8675
+ type: 'image',
8676
+ zIndex,
8677
+ domOrder,
8678
+ options: { x, y, w, h, rotate: rotation, data: null },
8679
+ };
8680
+
8681
+ const job = async () => {
8682
+ const processed = await getProcessedImage(node.src, widthPx, heightPx, radii);
8683
+ if (processed) item.options.data = processed;
8684
+ else item.skip = true;
8685
+ };
8686
+
8687
+ return { items: [item], job, stopRecursion: true };
8688
+ }
8689
+
8690
+ // Radii logic
8691
+ const borderRadiusValue = parseFloat(style.borderRadius) || 0;
8692
+ const borderBottomLeftRadius = parseFloat(style.borderBottomLeftRadius) || 0;
8693
+ const borderBottomRightRadius = parseFloat(style.borderBottomRightRadius) || 0;
8694
+ const borderTopLeftRadius = parseFloat(style.borderTopLeftRadius) || 0;
8695
+ const borderTopRightRadius = parseFloat(style.borderTopRightRadius) || 0;
8696
+
8697
+ const hasPartialBorderRadius =
8698
+ (borderBottomLeftRadius > 0 && borderBottomLeftRadius !== borderRadiusValue) ||
8699
+ (borderBottomRightRadius > 0 && borderBottomRightRadius !== borderRadiusValue) ||
8700
+ (borderTopLeftRadius > 0 && borderTopLeftRadius !== borderRadiusValue) ||
8701
+ (borderTopRightRadius > 0 && borderTopRightRadius !== borderRadiusValue) ||
8702
+ (borderRadiusValue === 0 &&
8703
+ (borderBottomLeftRadius ||
8704
+ borderBottomRightRadius ||
8705
+ borderTopLeftRadius ||
8706
+ borderTopRightRadius));
8707
+
8708
+ // --- ASYNC JOB: Clipped Divs via Canvas ---
8709
+ if (hasPartialBorderRadius && isClippedByParent(node)) {
8710
+ const marginLeft = parseFloat(style.marginLeft) || 0;
8711
+ const marginTop = parseFloat(style.marginTop) || 0;
8712
+ x += marginLeft * PX_TO_INCH * config.scale;
8713
+ y += marginTop * PX_TO_INCH * config.scale;
8714
+
8715
+ const item = {
8716
+ type: 'image',
8717
+ zIndex,
8718
+ domOrder,
8719
+ options: { x, y, w, h, rotate: rotation, data: null },
8720
+ };
8721
+
8722
+ const job = async () => {
8723
+ const canvasImageData = await elementToCanvasImage(node, widthPx, heightPx);
8724
+ if (canvasImageData) item.options.data = canvasImageData;
8725
+ else item.skip = true;
8726
+ };
8727
+
8728
+ return { items: [item], job, stopRecursion: true };
8729
+ }
8730
+
8731
+ // --- SYNC: Standard CSS Extraction ---
8732
+ const bgColorObj = parseColor(style.backgroundColor);
8733
+ const bgClip = style.webkitBackgroundClip || style.backgroundClip;
8734
+ const isBgClipText = bgClip === 'text';
8735
+ const hasGradient =
8736
+ !isBgClipText && style.backgroundImage && style.backgroundImage.includes('linear-gradient');
8737
+
8738
+ const borderColorObj = parseColor(style.borderColor);
8739
+ const borderWidth = parseFloat(style.borderWidth);
8740
+ const hasBorder = borderWidth > 0 && borderColorObj.hex;
8741
+
8742
+ const borderInfo = getBorderInfo(style, config.scale);
8743
+ const hasUniformBorder = borderInfo.type === 'uniform';
8744
+ const hasCompositeBorder = borderInfo.type === 'composite';
8745
+
8746
+ const shadowStr = style.boxShadow;
8747
+ const hasShadow = shadowStr && shadowStr !== 'none';
8748
+ const softEdge = getSoftEdges(style.filter, config.scale);
8749
+
8750
+ let isImageWrapper = false;
8751
+ const imgChild = Array.from(node.children).find((c) => c.tagName === 'IMG');
8752
+ if (imgChild) {
8753
+ const childW = imgChild.offsetWidth || imgChild.getBoundingClientRect().width;
8754
+ const childH = imgChild.offsetHeight || imgChild.getBoundingClientRect().height;
8755
+ if (childW >= widthPx - 2 && childH >= heightPx - 2) isImageWrapper = true;
8756
+ }
8757
+
8758
+ let textPayload = null;
8759
+ const isText = isTextContainer(node);
8760
+
8761
+ if (isText) {
8762
+ const textParts = [];
8763
+ const isList = style.display === 'list-item';
8764
+ if (isList) {
8765
+ const fontSizePt = parseFloat(style.fontSize) * 0.75 * config.scale;
8766
+ const bulletShift = (parseFloat(style.fontSize) || 16) * PX_TO_INCH * config.scale * 1.5;
8767
+ x -= bulletShift;
8768
+ w += bulletShift;
8769
+ textParts.push({
8770
+ text: ' ',
8771
+ options: {
8772
+ color: parseColor(style.color).hex || '000000',
8773
+ fontSize: fontSizePt,
8774
+ },
8775
+ });
8776
+ }
8777
+
8778
+ node.childNodes.forEach((child, index) => {
8779
+ let textVal = child.nodeType === 3 ? child.nodeValue : child.textContent;
8780
+ let nodeStyle = child.nodeType === 1 ? window.getComputedStyle(child) : style;
8781
+ textVal = textVal.replace(/[\n\r\t]+/g, ' ').replace(/\s{2,}/g, ' ');
8782
+ if (index === 0 && !isList) textVal = textVal.trimStart();
8783
+ else if (index === 0) textVal = textVal.trimStart();
8784
+ if (index === node.childNodes.length - 1) textVal = textVal.trimEnd();
8785
+ if (nodeStyle.textTransform === 'uppercase') textVal = textVal.toUpperCase();
8786
+ if (nodeStyle.textTransform === 'lowercase') textVal = textVal.toLowerCase();
8787
+
8788
+ if (textVal.length > 0) {
8789
+ textParts.push({
8790
+ text: textVal,
8791
+ options: getTextStyle(nodeStyle, config.scale),
8792
+ });
8793
+ }
8794
+ });
8795
+
8796
+ if (textParts.length > 0) {
8797
+ let align = style.textAlign || 'left';
8798
+ if (align === 'start') align = 'left';
8799
+ if (align === 'end') align = 'right';
8800
+ let valign = 'top';
8801
+ if (style.alignItems === 'center') valign = 'middle';
8802
+ if (style.justifyContent === 'center' && style.display.includes('flex')) align = 'center';
8803
+
8804
+ const pt = parseFloat(style.paddingTop) || 0;
8805
+ const pb = parseFloat(style.paddingBottom) || 0;
8806
+ if (Math.abs(pt - pb) < 2 && bgColorObj.hex) valign = 'middle';
8807
+
8808
+ let padding = getPadding(style, config.scale);
8809
+ if (align === 'center' && valign === 'middle') padding = [0, 0, 0, 0];
8810
+
8811
+ textPayload = { text: textParts, align, valign, inset: padding };
8812
+ }
8813
+ }
8814
+
8815
+ if (hasGradient || (softEdge && bgColorObj.hex && !isImageWrapper)) {
8816
+ let bgData = null;
8817
+ let padIn = 0;
8818
+ if (softEdge) {
8819
+ const svgInfo = generateBlurredSVG(
8820
+ widthPx,
8821
+ heightPx,
8822
+ bgColorObj.hex,
8823
+ borderRadiusValue,
8824
+ softEdge
8825
+ );
8826
+ bgData = svgInfo.data;
8827
+ padIn = svgInfo.padding * PX_TO_INCH * config.scale;
8828
+ } else {
8829
+ bgData = generateGradientSVG(
8830
+ widthPx,
8831
+ heightPx,
8832
+ style.backgroundImage,
8833
+ borderRadiusValue,
8834
+ hasBorder ? { color: borderColorObj.hex, width: borderWidth } : null
8835
+ );
8836
+ }
8837
+
8838
+ if (bgData) {
8839
+ items.push({
8840
+ type: 'image',
8841
+ zIndex,
8842
+ domOrder,
8843
+ options: {
8844
+ data: bgData,
8845
+ x: x - padIn,
8846
+ y: y - padIn,
8847
+ w: w + padIn * 2,
8848
+ h: h + padIn * 2,
8849
+ rotate: rotation,
8850
+ },
8851
+ });
8852
+ }
8853
+
8854
+ if (textPayload) {
8855
+ items.push({
8856
+ type: 'text',
8857
+ zIndex: zIndex + 1,
8858
+ domOrder,
8859
+ textParts: textPayload.text,
8860
+ options: {
8861
+ x,
8862
+ y,
8863
+ w,
8864
+ h,
8865
+ align: textPayload.align,
8866
+ valign: textPayload.valign,
8867
+ inset: textPayload.inset,
8868
+ rotate: rotation,
8869
+ margin: 0,
8870
+ wrap: true,
8871
+ autoFit: false,
8872
+ },
8873
+ });
8874
+ }
8875
+ if (hasCompositeBorder) {
8876
+ const borderItems = createCompositeBorderItems(
8877
+ borderInfo.sides,
8878
+ x,
8879
+ y,
8880
+ w,
8881
+ h,
8882
+ config.scale,
8883
+ zIndex,
8884
+ domOrder
8885
+ );
8886
+ items.push(...borderItems);
8887
+ }
8888
+ } else if (
8889
+ (bgColorObj.hex && !isImageWrapper) ||
8890
+ hasUniformBorder ||
8891
+ hasCompositeBorder ||
8892
+ hasShadow ||
8893
+ textPayload
8894
+ ) {
8895
+ const finalAlpha = safeOpacity * bgColorObj.opacity;
8896
+ const transparency = (1 - finalAlpha) * 100;
8897
+ const useSolidFill = bgColorObj.hex && !isImageWrapper;
8898
+
8899
+ if (hasPartialBorderRadius && useSolidFill && !textPayload) {
8900
+ const shapeSvg = generateCustomShapeSVG(
8901
+ widthPx,
8902
+ heightPx,
8903
+ bgColorObj.hex,
8904
+ bgColorObj.opacity,
8905
+ {
8906
+ tl: parseFloat(style.borderTopLeftRadius) || 0,
8907
+ tr: parseFloat(style.borderTopRightRadius) || 0,
8908
+ br: parseFloat(style.borderBottomRightRadius) || 0,
8909
+ bl: parseFloat(style.borderBottomLeftRadius) || 0,
8910
+ }
8911
+ );
8912
+
8913
+ items.push({
8914
+ type: 'image',
8915
+ zIndex,
8916
+ domOrder,
8917
+ options: { data: shapeSvg, x, y, w, h, rotate: rotation },
8918
+ });
8919
+ } else {
8920
+ const shapeOpts = {
8921
+ x,
8922
+ y,
8923
+ w,
8924
+ h,
8925
+ rotate: rotation,
8926
+ fill: useSolidFill
8927
+ ? { color: bgColorObj.hex, transparency: transparency }
8928
+ : { type: 'none' },
8929
+ line: hasUniformBorder ? borderInfo.options : null,
8930
+ };
8931
+
8932
+ if (hasShadow) shapeOpts.shadow = getVisibleShadow(shadowStr, config.scale);
8933
+
8934
+ const borderRadius = parseFloat(style.borderRadius) || 0;
8935
+ const aspectRatio = Math.max(widthPx, heightPx) / Math.min(widthPx, heightPx);
8936
+ const isCircle = aspectRatio < 1.1 && borderRadius >= Math.min(widthPx, heightPx) / 2 - 1;
8937
+
8938
+ let shapeType = pptx.ShapeType.rect;
8939
+ if (isCircle) shapeType = pptx.ShapeType.ellipse;
8940
+ else if (borderRadius > 0) {
8941
+ shapeType = pptx.ShapeType.roundRect;
8942
+ shapeOpts.rectRadius = Math.min(0.5, borderRadius / Math.min(widthPx, heightPx));
8943
+ }
8944
+
8945
+ if (textPayload) {
8946
+ const textOptions = {
8947
+ shape: shapeType,
8948
+ ...shapeOpts,
8949
+ align: textPayload.align,
8950
+ valign: textPayload.valign,
8951
+ inset: textPayload.inset,
8952
+ margin: 0,
8953
+ wrap: true,
8954
+ autoFit: false,
8955
+ };
8956
+ items.push({
8957
+ type: 'text',
8958
+ zIndex,
8959
+ domOrder,
8960
+ textParts: textPayload.text,
8961
+ options: textOptions,
8962
+ });
8963
+ } else if (!hasPartialBorderRadius) {
8964
+ items.push({
8965
+ type: 'shape',
8966
+ zIndex,
8967
+ domOrder,
8968
+ shapeType,
8969
+ options: shapeOpts,
8970
+ });
8971
+ }
8972
+ }
8973
+
8974
+ if (hasCompositeBorder) {
8975
+ const borderSvgData = generateCompositeBorderSVG(
8976
+ widthPx,
8977
+ heightPx,
8978
+ borderRadiusValue,
8979
+ borderInfo.sides
8980
+ );
8981
+ if (borderSvgData) {
8982
+ items.push({
8983
+ type: 'image',
8984
+ zIndex: zIndex + 1,
8985
+ domOrder,
8986
+ options: { data: borderSvgData, x, y, w, h, rotate: rotation },
8987
+ });
8988
+ }
8989
+ }
8990
+ }
8991
+
8992
+ return { items, stopRecursion: !!textPayload };
8993
+ }
8994
+
8995
+ function createCompositeBorderItems(sides, x, y, w, h, scale, zIndex, domOrder) {
8996
+ const items = [];
8997
+ const pxToInch = 1 / 96;
8998
+ const common = { zIndex: zIndex + 1, domOrder, shapeType: 'rect' };
8999
+
9000
+ if (sides.top.width > 0)
9001
+ items.push({
9002
+ ...common,
9003
+ options: { x, y, w, h: sides.top.width * pxToInch * scale, fill: { color: sides.top.color } },
9004
+ });
9005
+ if (sides.right.width > 0)
9006
+ items.push({
9007
+ ...common,
9008
+ options: {
9009
+ x: x + w - sides.right.width * pxToInch * scale,
9010
+ y,
9011
+ w: sides.right.width * pxToInch * scale,
9012
+ h,
9013
+ fill: { color: sides.right.color },
9014
+ },
9015
+ });
9016
+ if (sides.bottom.width > 0)
9017
+ items.push({
9018
+ ...common,
9019
+ options: {
9020
+ x,
9021
+ y: y + h - sides.bottom.width * pxToInch * scale,
9022
+ w,
9023
+ h: sides.bottom.width * pxToInch * scale,
9024
+ fill: { color: sides.bottom.color },
9025
+ },
9026
+ });
9027
+ if (sides.left.width > 0)
9028
+ items.push({
9029
+ ...common,
9030
+ options: {
9031
+ x,
9032
+ y,
9033
+ w: sides.left.width * pxToInch * scale,
9034
+ h,
9035
+ fill: { color: sides.left.color },
9036
+ },
9037
+ });
9038
+
9039
+ return items;
9019
9040
  }
9020
9041
 
9021
9042
  export { exportToPptx };