@ohos-ports/slides-grab 1.5.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/LICENSE +21 -0
  2. package/README-ko.md +292 -0
  3. package/README.md +301 -0
  4. package/bin/ohos-postinstall.cjs +118 -0
  5. package/bin/ppt-agent.js +620 -0
  6. package/convert.cjs +20 -0
  7. package/native/@img/sharp-libvips-openharmony-arm64/lib/glib-2.0/include/glibconfig.h +220 -0
  8. package/native/@img/sharp-libvips-openharmony-arm64/lib/index.js +1 -0
  9. package/native/@img/sharp-libvips-openharmony-arm64/lib/libexpat.so +0 -0
  10. package/native/@img/sharp-libvips-openharmony-arm64/lib/libffi.so +0 -0
  11. package/native/@img/sharp-libvips-openharmony-arm64/lib/libjpeg.so +0 -0
  12. package/native/@img/sharp-libvips-openharmony-arm64/lib/libpcre2-8.so.0 +0 -0
  13. package/native/@img/sharp-libvips-openharmony-arm64/lib/libvips-cpp.so.42.20.3 +0 -0
  14. package/native/@img/sharp-libvips-openharmony-arm64/lib/libvips.so.42.20.3 +0 -0
  15. package/native/@img/sharp-libvips-openharmony-arm64/package.json +13 -0
  16. package/native/@img/sharp-openharmony-arm64/lib/sharp-openharmony-arm64.node +0 -0
  17. package/native/@img/sharp-openharmony-arm64/package.json +16 -0
  18. package/package.json +95 -0
  19. package/runtimes/claude-code/agents/design-critic-agent.md +23 -0
  20. package/runtimes/codex/agents/slides-grab-design-critic.md +22 -0
  21. package/scripts/build-viewer.js +444 -0
  22. package/scripts/design-gate.js +258 -0
  23. package/scripts/download-video.js +213 -0
  24. package/scripts/editor-server.js +1167 -0
  25. package/scripts/figma-export.js +169 -0
  26. package/scripts/generate-image.js +116 -0
  27. package/scripts/generate-images.js +164 -0
  28. package/scripts/html2pdf.js +822 -0
  29. package/scripts/html2png.js +246 -0
  30. package/scripts/html2pptx.js +162 -0
  31. package/scripts/import-template.js +86 -0
  32. package/scripts/install-runtime.js +216 -0
  33. package/scripts/render-tldraw.js +44 -0
  34. package/scripts/validate-slides.js +221 -0
  35. package/skills/slides-grab/SKILL.md +65 -0
  36. package/skills/slides-grab/references/presentation-workflow-reference.md +61 -0
  37. package/skills/slides-grab-card-news/SKILL.md +35 -0
  38. package/skills/slides-grab-design/SKILL.md +88 -0
  39. package/skills/slides-grab-design/references/beautiful-slide-defaults.md +88 -0
  40. package/skills/slides-grab-design/references/design-gate.md +349 -0
  41. package/skills/slides-grab-design/references/design-rules.md +76 -0
  42. package/skills/slides-grab-design/references/design-system-full.md +568 -0
  43. package/skills/slides-grab-design/references/detailed-design-rules.md +70 -0
  44. package/skills/slides-grab-export/SKILL.md +55 -0
  45. package/skills/slides-grab-export/references/export-rules.md +27 -0
  46. package/skills/slides-grab-export/references/html2pptx.md +627 -0
  47. package/skills/slides-grab-export/references/ooxml.md +427 -0
  48. package/skills/slides-grab-export/references/pptx-skill-reference.md +189 -0
  49. package/skills/slides-grab-html/SKILL.md +67 -0
  50. package/skills/slides-grab-image/SKILL.md +82 -0
  51. package/skills/slides-grab-plan/SKILL.md +68 -0
  52. package/skills/slides-grab-plan/references/design-md-to-slides-conversion.md +135 -0
  53. package/skills/slides-grab-plan/references/outline-format.md +47 -0
  54. package/skills/slides-grab-plan/references/plan-workflow-reference.md +140 -0
  55. package/src/codex-imagen.js +182 -0
  56. package/src/design-diversity-data.js +6932 -0
  57. package/src/design-gate-report.js +244 -0
  58. package/src/design-gate-state.js +329 -0
  59. package/src/design-import.js +164 -0
  60. package/src/design-md-parser.js +415 -0
  61. package/src/design-styles-data.js +1928 -0
  62. package/src/design-styles.js +209 -0
  63. package/src/editor/codex-edit.js +584 -0
  64. package/src/editor/edit-subprocess.js +170 -0
  65. package/src/editor/editor-codex-prompt.md +50 -0
  66. package/src/editor/editor.html +1785 -0
  67. package/src/editor/js/editor-bbox.js +332 -0
  68. package/src/editor/js/editor-chat.js +56 -0
  69. package/src/editor/js/editor-direct-edit.js +238 -0
  70. package/src/editor/js/editor-dom.js +59 -0
  71. package/src/editor/js/editor-init.js +405 -0
  72. package/src/editor/js/editor-navigation.js +54 -0
  73. package/src/editor/js/editor-select.js +558 -0
  74. package/src/editor/js/editor-send.js +175 -0
  75. package/src/editor/js/editor-sse.js +163 -0
  76. package/src/editor/js/editor-state.js +41 -0
  77. package/src/editor/js/editor-type.js +71 -0
  78. package/src/editor/js/editor-utils.js +167 -0
  79. package/src/editor/js/model-registry.js +37 -0
  80. package/src/editor/screenshot.js +82 -0
  81. package/src/export-resolution.cjs +68 -0
  82. package/src/figma.js +71 -0
  83. package/src/html2pptx-scale.cjs +120 -0
  84. package/src/html2pptx.cjs +1262 -0
  85. package/src/image-contract.js +329 -0
  86. package/src/image-native.js +468 -0
  87. package/src/nano-banana.js +841 -0
  88. package/src/ohos-browser-bridge.cjs +272 -0
  89. package/src/pptx-raster-export.cjs +299 -0
  90. package/src/resolve.js +110 -0
  91. package/src/slide-mode.cjs +72 -0
  92. package/src/template-fidelity.js +267 -0
  93. package/src/template-import.js +505 -0
  94. package/src/template-layout.js +261 -0
  95. package/src/template-pack.js +255 -0
  96. package/src/tldraw/render.js +473 -0
  97. package/src/validation/cli.js +120 -0
  98. package/src/validation/core.js +1023 -0
  99. package/templates/chart.html +121 -0
  100. package/templates/closing.html +54 -0
  101. package/templates/content.html +50 -0
  102. package/templates/contents.html +60 -0
  103. package/templates/cover.html +64 -0
  104. package/templates/custom/.gitkeep +0 -0
  105. package/templates/custom/README.md +7 -0
  106. package/templates/design-styles/README.md +20 -0
  107. package/templates/design-styles/preview.html +4438 -0
  108. package/templates/diagram-tldraw.html +56 -0
  109. package/templates/diagram.html +98 -0
  110. package/templates/quote.html +31 -0
  111. package/templates/section-divider.html +43 -0
  112. package/templates/split-layout.html +43 -0
  113. package/templates/statistics.html +55 -0
  114. package/templates/team.html +49 -0
  115. package/templates/timeline.html +59 -0
@@ -0,0 +1,1262 @@
1
+ /**
2
+ * html2pptx - Experimental / unstable HTML-to-pptxgenjs conversion for slide exports
3
+ *
4
+ * USAGE:
5
+ * const pptx = new pptxgen();
6
+ * pptx.layout = 'LAYOUT_16x9'; // Must match HTML body dimensions
7
+ *
8
+ * const { slide, placeholders } = await html2pptx('slide.html', pptx);
9
+ * slide.addChart(pptx.charts.LINE, data, placeholders[0]);
10
+ *
11
+ * await pptx.writeFile('output.pptx');
12
+ *
13
+ * FEATURES:
14
+ * - Best-effort conversion from HTML to PowerPoint
15
+ * - Supports text, images, shapes, and bullet lists
16
+ * - Extracts placeholder elements (class="placeholder") with positions
17
+ * - Handles CSS gradients, borders, and margins
18
+ *
19
+ * VALIDATION:
20
+ * - Uses body width/height from HTML for viewport sizing
21
+ * - Throws if HTML dimensions don't match the layout, or scales same-ratio content with fitToLayout
22
+ * - Throws error if content overflows body (with overflow details)
23
+ *
24
+ * RETURNS:
25
+ * { slide, placeholders } where placeholders is an array of { id, x, y, w, h }
26
+ */
27
+
28
+ // OHOS: Use system Haitai browser via CDP bridge instead of standalone Chromium
29
+ const { launchBrowserViaCdp, loadPageUrl } = require('./ohos-browser-bridge.cjs');
30
+ const path = require('path');
31
+ const sharp = require('sharp');
32
+ const {
33
+ getLayoutScale,
34
+ scaleSlideData,
35
+ validateDimensions,
36
+ } = require('./html2pptx-scale.cjs');
37
+
38
+ const PT_PER_PX = 0.75;
39
+ const PX_PER_IN = 96;
40
+
41
+ async function launchBrowser(tmpDir) {
42
+ if (process.platform === 'openharmony') {
43
+ return launchBrowserViaCdp();
44
+ }
45
+
46
+ const { chromium } = require('playwright');
47
+ const launchOptions = { env: { TMPDIR: tmpDir } };
48
+
49
+ if (process.platform !== 'darwin') {
50
+ return chromium.launch(launchOptions);
51
+ }
52
+
53
+ try {
54
+ return await chromium.launch({ ...launchOptions, channel: 'chrome' });
55
+ } catch (error) {
56
+ if (error && typeof error.message === 'string' && error.message.includes("Chromium distribution 'chrome' is not found")) {
57
+ return chromium.launch(launchOptions);
58
+ }
59
+ throw error;
60
+ }
61
+ }
62
+
63
+ async function waitForDynamicLibraryRender(page, timeout = 5000) {
64
+ await page.evaluate(async () => {
65
+ if (document.fonts?.ready) {
66
+ await document.fonts.ready;
67
+ }
68
+ });
69
+
70
+ const hasCanvas = await page.evaluate(() => document.querySelector('canvas') !== null);
71
+ if (hasCanvas) {
72
+ await page.evaluate(() => {
73
+ if (!window.Chart || !window.Chart.instances) return;
74
+ const instances = Array.isArray(window.Chart.instances)
75
+ ? window.Chart.instances
76
+ : Object.values(window.Chart.instances);
77
+
78
+ for (const chart of instances) {
79
+ if (!chart) continue;
80
+ if (chart.options) chart.options.animation = false;
81
+ if (typeof chart.update === 'function') {
82
+ try {
83
+ chart.update('none');
84
+ } catch (_) {
85
+ // noop
86
+ }
87
+ }
88
+ }
89
+ });
90
+
91
+ try {
92
+ await page.waitForFunction(() => {
93
+ const canvases = Array.from(document.querySelectorAll('canvas'));
94
+ if (canvases.length === 0) return true;
95
+
96
+ const instances = (window.Chart && window.Chart.instances)
97
+ ? (Array.isArray(window.Chart.instances) ? window.Chart.instances : Object.values(window.Chart.instances))
98
+ : [];
99
+
100
+ return canvases.every((canvas) => {
101
+ const rect = canvas.getBoundingClientRect();
102
+ if (rect.width === 0 || rect.height === 0) return false;
103
+
104
+ const matchedChart = instances.find((instance) => instance && instance.canvas === canvas);
105
+ if (!matchedChart) return true;
106
+ return matchedChart.animating === false;
107
+ });
108
+ }, null, { timeout });
109
+ } catch (_) {
110
+ // Keep conversion resilient even when chart animation state is unavailable.
111
+ }
112
+ }
113
+
114
+ const hasMermaid = await page.evaluate(() => document.querySelector('.mermaid') !== null);
115
+ if (hasMermaid) {
116
+ await page.evaluate(async () => {
117
+ if (!window.mermaid) return;
118
+
119
+ try {
120
+ if (typeof window.mermaid.run === 'function') {
121
+ await window.mermaid.run({ querySelector: '.mermaid' });
122
+ return;
123
+ }
124
+
125
+ if (typeof window.mermaid.init === 'function') {
126
+ await window.mermaid.init(undefined, document.querySelectorAll('.mermaid'));
127
+ }
128
+ } catch (_) {
129
+ // noop
130
+ }
131
+ });
132
+
133
+ try {
134
+ await page.waitForFunction(() => {
135
+ const blocks = Array.from(document.querySelectorAll('.mermaid'));
136
+ if (blocks.length === 0) return true;
137
+ return blocks.every((block) => block.querySelector('svg') !== null);
138
+ }, null, { timeout });
139
+ } catch (_) {
140
+ // Keep conversion resilient when Mermaid CDN/script is unavailable.
141
+ }
142
+ }
143
+ }
144
+
145
+ async function rasterizeDynamicVisuals(page) {
146
+ await page.evaluate(async () => {
147
+ const isVisuallyHidden = (element) => {
148
+ const elementComputed = window.getComputedStyle(element);
149
+ if (elementComputed.visibility === 'hidden' || elementComputed.visibility === 'collapse') {
150
+ return true;
151
+ }
152
+ for (let current = element; current; current = current.parentElement) {
153
+ const computed = window.getComputedStyle(current);
154
+ if (computed.display === 'none') return true;
155
+ if (Number.parseFloat(computed.opacity) <= 0) return true;
156
+ }
157
+ return false;
158
+ };
159
+
160
+ const hasVisibleDescendant = (element) => Array.from(element.children).some(
161
+ (child) => !isVisuallyHidden(child) || hasVisibleDescendant(child),
162
+ );
163
+
164
+ const waitForImageLoad = (img) => new Promise((resolve) => {
165
+ if (img.complete) {
166
+ resolve();
167
+ return;
168
+ }
169
+
170
+ const done = () => resolve();
171
+ img.addEventListener('load', done, { once: true });
172
+ img.addEventListener('error', done, { once: true });
173
+ });
174
+
175
+ const canvasList = Array.from(document.querySelectorAll('canvas'));
176
+ for (const canvas of canvasList) {
177
+ try {
178
+ if (isVisuallyHidden(canvas)) continue;
179
+ const rect = canvas.getBoundingClientRect();
180
+ if (rect.width === 0 || rect.height === 0) continue;
181
+
182
+ const dataUrl = canvas.toDataURL('image/png');
183
+ if (!dataUrl || dataUrl === 'data:,') continue;
184
+
185
+ const computed = window.getComputedStyle(canvas);
186
+ const img = document.createElement('img');
187
+ img.src = dataUrl;
188
+ img.alt = canvas.getAttribute('aria-label') || 'chart';
189
+ img.style.width = `${rect.width}px`;
190
+ img.style.height = `${rect.height}px`;
191
+ img.style.display = computed.display === 'inline' ? 'inline-block' : computed.display;
192
+ img.style.visibility = computed.visibility;
193
+ img.style.objectFit = 'contain';
194
+ if (canvas.className) img.className = canvas.className;
195
+ if (canvas.id) img.id = `${canvas.id}-rendered`;
196
+
197
+ canvas.replaceWith(img);
198
+ await waitForImageLoad(img);
199
+ } catch (_) {
200
+ // noop
201
+ }
202
+ }
203
+
204
+ const svgList = Array.from(document.querySelectorAll('svg'));
205
+ for (const svg of svgList) {
206
+ try {
207
+ const svgIsHidden = isVisuallyHidden(svg);
208
+ const hasVisibilityOverride = svgIsHidden && hasVisibleDescendant(svg);
209
+ if (svgIsHidden && !hasVisibilityOverride) continue;
210
+ const rect = svg.getBoundingClientRect();
211
+ if (rect.width === 0 || rect.height === 0) continue;
212
+
213
+ const clone = svg.cloneNode(true);
214
+ if (!clone.getAttribute('xmlns')) {
215
+ clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
216
+ }
217
+ if (!clone.getAttribute('xmlns:xlink')) {
218
+ clone.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
219
+ }
220
+ if (!clone.getAttribute('width')) {
221
+ clone.setAttribute('width', `${Math.max(1, Math.round(rect.width))}`);
222
+ }
223
+ if (!clone.getAttribute('height')) {
224
+ clone.setAttribute('height', `${Math.max(1, Math.round(rect.height))}`);
225
+ }
226
+
227
+ const serialized = new XMLSerializer().serializeToString(clone);
228
+ const base64Svg = btoa(unescape(encodeURIComponent(serialized)));
229
+ const dataUrl = `data:image/svg+xml;base64,${base64Svg}`;
230
+
231
+ const computed = window.getComputedStyle(svg);
232
+ const img = document.createElement('img');
233
+ img.src = dataUrl;
234
+ img.alt = 'diagram';
235
+ img.style.width = `${rect.width}px`;
236
+ img.style.height = `${rect.height}px`;
237
+ img.style.display = computed.display === 'inline' ? 'inline-block' : computed.display;
238
+ img.style.visibility = hasVisibilityOverride ? 'visible' : computed.visibility;
239
+ img.style.objectFit = 'contain';
240
+ if (svg.className && typeof svg.className.baseVal === 'string') img.className = svg.className.baseVal;
241
+ if (svg.id) img.id = `${svg.id}-rendered`;
242
+
243
+ svg.replaceWith(img);
244
+ await waitForImageLoad(img);
245
+ } catch (_) {
246
+ // noop
247
+ }
248
+ }
249
+ });
250
+ }
251
+
252
+ // Helper: Get body dimensions and check for overflow
253
+ async function getBodyDimensions(page) {
254
+ const bodyDimensions = await page.evaluate(() => {
255
+ const body = document.body;
256
+ const style = window.getComputedStyle(body);
257
+
258
+ return {
259
+ width: parseFloat(style.width),
260
+ height: parseFloat(style.height),
261
+ scrollWidth: body.scrollWidth,
262
+ scrollHeight: body.scrollHeight
263
+ };
264
+ });
265
+
266
+ const errors = [];
267
+ const widthOverflowPx = Math.max(0, bodyDimensions.scrollWidth - bodyDimensions.width - 1);
268
+ const heightOverflowPx = Math.max(0, bodyDimensions.scrollHeight - bodyDimensions.height - 1);
269
+
270
+ const widthOverflowPt = widthOverflowPx * PT_PER_PX;
271
+ const heightOverflowPt = heightOverflowPx * PT_PER_PX;
272
+
273
+ if (widthOverflowPt > 0 || heightOverflowPt > 0) {
274
+ const directions = [];
275
+ if (widthOverflowPt > 0) directions.push(`${widthOverflowPt.toFixed(1)}pt horizontally`);
276
+ if (heightOverflowPt > 0) directions.push(`${heightOverflowPt.toFixed(1)}pt vertically`);
277
+ const reminder = heightOverflowPt > 0 ? ' (Remember: leave 0.5" margin at bottom of slide)' : '';
278
+ errors.push(`HTML content overflows body by ${directions.join(' and ')}${reminder}`);
279
+ }
280
+
281
+ return { ...bodyDimensions, errors };
282
+ }
283
+
284
+ function validateTextBoxPosition(slideData, bodyDimensions) {
285
+ const errors = [];
286
+ const slideHeightInches = bodyDimensions.height / PX_PER_IN;
287
+ const minBottomMargin = 0.5; // 0.5 inches from bottom
288
+
289
+ for (const el of slideData.elements) {
290
+ // Check text elements (p, h1-h6, list)
291
+ if (['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'list'].includes(el.type)) {
292
+ const fontSize = el.style?.fontSize || 0;
293
+ const bottomEdge = el.position.y + el.position.h;
294
+ const distanceFromBottom = slideHeightInches - bottomEdge;
295
+
296
+ if (fontSize > 12 && distanceFromBottom < minBottomMargin) {
297
+ const getText = () => {
298
+ if (typeof el.text === 'string') return el.text;
299
+ if (Array.isArray(el.text)) return el.text.find(t => t.text)?.text || '';
300
+ if (Array.isArray(el.items)) return el.items.find(item => item.text)?.text || '';
301
+ return '';
302
+ };
303
+ const textPrefix = getText().substring(0, 50) + (getText().length > 50 ? '...' : '');
304
+
305
+ errors.push(
306
+ `Text box "${textPrefix}" ends too close to bottom edge ` +
307
+ `(${distanceFromBottom.toFixed(2)}" from bottom, minimum ${minBottomMargin}" required)`
308
+ );
309
+ }
310
+ }
311
+ }
312
+
313
+ return errors;
314
+ }
315
+
316
+ // Helper: Add background to slide
317
+ async function addBackground(slideData, targetSlide, tmpDir) {
318
+ if (slideData.background.type === 'image' && slideData.background.path) {
319
+ let imagePath = slideData.background.path.startsWith('file://')
320
+ ? slideData.background.path.replace('file://', '')
321
+ : slideData.background.path;
322
+ targetSlide.background = { path: imagePath };
323
+ } else if (slideData.background.type === 'color' && slideData.background.value) {
324
+ targetSlide.background = { color: slideData.background.value };
325
+ }
326
+ }
327
+
328
+ // Helper: Add elements to slide
329
+ function addElements(slideData, targetSlide, pres) {
330
+ for (const el of slideData.elements) {
331
+ if (el.type === 'image') {
332
+ if (el.src.startsWith('data:')) {
333
+ targetSlide.addImage({
334
+ data: el.src.replace(/^data:/, ''),
335
+ x: el.position.x,
336
+ y: el.position.y,
337
+ w: el.position.w,
338
+ h: el.position.h
339
+ });
340
+ } else {
341
+ let imagePath = el.src.startsWith('file://') ? el.src.replace('file://', '') : el.src;
342
+ targetSlide.addImage({
343
+ path: imagePath,
344
+ x: el.position.x,
345
+ y: el.position.y,
346
+ w: el.position.w,
347
+ h: el.position.h
348
+ });
349
+ }
350
+ } else if (el.type === 'line') {
351
+ targetSlide.addShape(pres.ShapeType.line, {
352
+ x: el.x1,
353
+ y: el.y1,
354
+ w: el.x2 - el.x1,
355
+ h: el.y2 - el.y1,
356
+ line: { color: el.color, width: el.width }
357
+ });
358
+ } else if (el.type === 'shape') {
359
+ const shapeOptions = {
360
+ x: el.position.x,
361
+ y: el.position.y,
362
+ w: el.position.w,
363
+ h: el.position.h,
364
+ shape: el.shape.rectRadius > 0 ? pres.ShapeType.roundRect : pres.ShapeType.rect
365
+ };
366
+
367
+ if (el.shape.fill) {
368
+ shapeOptions.fill = { color: el.shape.fill };
369
+ if (el.shape.transparency != null) shapeOptions.fill.transparency = el.shape.transparency;
370
+ }
371
+ if (el.shape.line) shapeOptions.line = el.shape.line;
372
+ if (el.shape.rectRadius > 0) shapeOptions.rectRadius = el.shape.rectRadius;
373
+ if (el.shape.shadow) shapeOptions.shadow = el.shape.shadow;
374
+
375
+ targetSlide.addText(el.text || '', shapeOptions);
376
+ } else if (el.type === 'list') {
377
+ const listOptions = {
378
+ x: el.position.x,
379
+ y: el.position.y,
380
+ w: el.position.w,
381
+ h: el.position.h,
382
+ fontSize: el.style.fontSize,
383
+ fontFace: el.style.fontFace,
384
+ color: el.style.color,
385
+ align: el.style.align,
386
+ valign: 'top',
387
+ lineSpacing: el.style.lineSpacing,
388
+ paraSpaceBefore: el.style.paraSpaceBefore,
389
+ paraSpaceAfter: el.style.paraSpaceAfter,
390
+ margin: el.style.margin
391
+ };
392
+ if (el.style.margin) listOptions.margin = el.style.margin;
393
+ targetSlide.addText(el.items, listOptions);
394
+ } else {
395
+ // Check if text is single-line (height suggests one line)
396
+ const lineHeight = el.style.lineSpacing || el.style.fontSize * 1.2;
397
+ const isSingleLine = el.position.h <= lineHeight * 1.5;
398
+
399
+ let adjustedX = el.position.x;
400
+ let adjustedW = el.position.w;
401
+
402
+ // Make single-line text 2% wider to account for underestimate
403
+ if (isSingleLine) {
404
+ const widthIncrease = el.position.w * 0.02;
405
+ const align = el.style.align;
406
+
407
+ if (align === 'center') {
408
+ // Center: expand both sides
409
+ adjustedX = el.position.x - (widthIncrease / 2);
410
+ adjustedW = el.position.w + widthIncrease;
411
+ } else if (align === 'right') {
412
+ // Right: expand to the left
413
+ adjustedX = el.position.x - widthIncrease;
414
+ adjustedW = el.position.w + widthIncrease;
415
+ } else {
416
+ // Left (default): expand to the right
417
+ adjustedW = el.position.w + widthIncrease;
418
+ }
419
+ }
420
+
421
+ const textOptions = {
422
+ x: adjustedX,
423
+ y: el.position.y,
424
+ w: adjustedW,
425
+ h: el.position.h,
426
+ fontSize: el.style.fontSize,
427
+ fontFace: el.style.fontFace,
428
+ color: el.style.color,
429
+ bold: el.style.bold,
430
+ italic: el.style.italic,
431
+ underline: el.style.underline,
432
+ valign: 'top',
433
+ lineSpacing: el.style.lineSpacing,
434
+ paraSpaceBefore: el.style.paraSpaceBefore,
435
+ paraSpaceAfter: el.style.paraSpaceAfter,
436
+ inset: 0 // Remove default PowerPoint internal padding
437
+ };
438
+
439
+ if (el.style.align) textOptions.align = el.style.align;
440
+ if (el.style.margin) textOptions.margin = el.style.margin;
441
+ if (el.style.rotate !== undefined) textOptions.rotate = el.style.rotate;
442
+ if (el.style.transparency !== null && el.style.transparency !== undefined) textOptions.transparency = el.style.transparency;
443
+
444
+ targetSlide.addText(el.text, textOptions);
445
+ }
446
+ }
447
+ }
448
+
449
+ // Helper: Extract slide data from HTML page
450
+ async function extractSlideData(page) {
451
+ return await page.evaluate(() => {
452
+ const PT_PER_PX = 0.75;
453
+ const PX_PER_IN = 96;
454
+
455
+ // Fonts that are single-weight and should not have bold applied
456
+ // (applying bold causes PowerPoint to use faux bold which makes text wider)
457
+ const SINGLE_WEIGHT_FONTS = ['impact'];
458
+
459
+ // Helper: Check if a font should skip bold formatting
460
+ const shouldSkipBold = (fontFamily) => {
461
+ if (!fontFamily) return false;
462
+ const normalizedFont = fontFamily.toLowerCase().replace(/['"]/g, '').split(',')[0].trim();
463
+ return SINGLE_WEIGHT_FONTS.includes(normalizedFont);
464
+ };
465
+
466
+ // Unit conversion helpers
467
+ const pxToInch = (px) => px / PX_PER_IN;
468
+ const pxToPoints = (pxStr) => parseFloat(pxStr) * PT_PER_PX;
469
+ const rgbToHex = (rgbStr) => {
470
+ // Handle transparent backgrounds by defaulting to white
471
+ if (rgbStr === 'rgba(0, 0, 0, 0)' || rgbStr === 'transparent') return 'FFFFFF';
472
+
473
+ const match = rgbStr.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
474
+ if (!match) return 'FFFFFF';
475
+ return match.slice(1).map(n => parseInt(n).toString(16).padStart(2, '0')).join('');
476
+ };
477
+
478
+ const extractAlpha = (rgbStr) => {
479
+ const match = rgbStr.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)/);
480
+ if (!match || !match[4]) return null;
481
+ const alpha = parseFloat(match[4]);
482
+ return Math.round((1 - alpha) * 100);
483
+ };
484
+
485
+ const isVisuallyHidden = (element) => {
486
+ const elementComputed = window.getComputedStyle(element);
487
+ if (elementComputed.visibility === 'hidden' || elementComputed.visibility === 'collapse') {
488
+ return true;
489
+ }
490
+ for (let current = element; current; current = current.parentElement) {
491
+ const computed = window.getComputedStyle(current);
492
+ if (computed.display === 'none') return true;
493
+ if (Number.parseFloat(computed.opacity) <= 0) return true;
494
+ }
495
+ return false;
496
+ };
497
+
498
+ const hasVisibleDescendant = (element) => Array.from(element.children).some(
499
+ (child) => !isVisuallyHidden(child) || hasVisibleDescendant(child),
500
+ );
501
+
502
+ const hasFullyTransparentText = (computed) => {
503
+ if (computed.color === 'transparent') return true;
504
+ return extractAlpha(computed.color) === 100;
505
+ };
506
+
507
+ const applyTextTransform = (text, textTransform) => {
508
+ if (textTransform === 'uppercase') return text.toUpperCase();
509
+ if (textTransform === 'lowercase') return text.toLowerCase();
510
+ if (textTransform === 'capitalize') {
511
+ return text.replace(/\b\w/g, c => c.toUpperCase());
512
+ }
513
+ return text;
514
+ };
515
+
516
+ // Extract rotation angle from CSS transform and writing-mode
517
+ const getRotation = (transform, writingMode) => {
518
+ let angle = 0;
519
+
520
+ // Handle writing-mode first
521
+ // PowerPoint: 90° = text rotated 90° clockwise (reads top to bottom, letters upright)
522
+ // PowerPoint: 270° = text rotated 270° clockwise (reads bottom to top, letters upright)
523
+ if (writingMode === 'vertical-rl') {
524
+ // vertical-rl alone = text reads top to bottom = 90° in PowerPoint
525
+ angle = 90;
526
+ } else if (writingMode === 'vertical-lr') {
527
+ // vertical-lr alone = text reads bottom to top = 270° in PowerPoint
528
+ angle = 270;
529
+ }
530
+
531
+ // Then add any transform rotation
532
+ if (transform && transform !== 'none') {
533
+ // Try to match rotate() function
534
+ const rotateMatch = transform.match(/rotate\((-?\d+(?:\.\d+)?)deg\)/);
535
+ if (rotateMatch) {
536
+ angle += parseFloat(rotateMatch[1]);
537
+ } else {
538
+ // Browser may compute as matrix - extract rotation from matrix
539
+ const matrixMatch = transform.match(/matrix\(([^)]+)\)/);
540
+ if (matrixMatch) {
541
+ const values = matrixMatch[1].split(',').map(parseFloat);
542
+ // matrix(a, b, c, d, e, f) where rotation = atan2(b, a)
543
+ const matrixAngle = Math.atan2(values[1], values[0]) * (180 / Math.PI);
544
+ angle += Math.round(matrixAngle);
545
+ }
546
+ }
547
+ }
548
+
549
+ // Normalize to 0-359 range
550
+ angle = angle % 360;
551
+ if (angle < 0) angle += 360;
552
+
553
+ return angle === 0 ? null : angle;
554
+ };
555
+
556
+ // Get position/dimensions accounting for rotation
557
+ const getPositionAndSize = (el, rect, rotation) => {
558
+ if (rotation === null) {
559
+ return { x: rect.left, y: rect.top, w: rect.width, h: rect.height };
560
+ }
561
+
562
+ // For 90° or 270° rotations, swap width and height
563
+ // because PowerPoint applies rotation to the original (unrotated) box
564
+ const isVertical = rotation === 90 || rotation === 270;
565
+
566
+ if (isVertical) {
567
+ // The browser shows us the rotated dimensions (tall box for vertical text)
568
+ // But PowerPoint needs the pre-rotation dimensions (wide box that will be rotated)
569
+ // So we swap: browser's height becomes PPT's width, browser's width becomes PPT's height
570
+ const centerX = rect.left + rect.width / 2;
571
+ const centerY = rect.top + rect.height / 2;
572
+
573
+ return {
574
+ x: centerX - rect.height / 2,
575
+ y: centerY - rect.width / 2,
576
+ w: rect.height,
577
+ h: rect.width
578
+ };
579
+ }
580
+
581
+ // For other rotations, use element's offset dimensions
582
+ const centerX = rect.left + rect.width / 2;
583
+ const centerY = rect.top + rect.height / 2;
584
+ return {
585
+ x: centerX - el.offsetWidth / 2,
586
+ y: centerY - el.offsetHeight / 2,
587
+ w: el.offsetWidth,
588
+ h: el.offsetHeight
589
+ };
590
+ };
591
+
592
+ // Parse CSS box-shadow into PptxGenJS shadow properties
593
+ const parseBoxShadow = (boxShadow) => {
594
+ if (!boxShadow || boxShadow === 'none') return null;
595
+
596
+ // Browser computed style format: "rgba(0, 0, 0, 0.3) 2px 2px 8px 0px [inset]"
597
+ // CSS format: "[inset] 2px 2px 8px 0px rgba(0, 0, 0, 0.3)"
598
+
599
+ const insetMatch = boxShadow.match(/inset/);
600
+
601
+ // IMPORTANT: PptxGenJS/PowerPoint doesn't properly support inset shadows
602
+ // Only process outer shadows to avoid file corruption
603
+ if (insetMatch) return null;
604
+
605
+ // Extract color first (rgba or rgb at start)
606
+ const colorMatch = boxShadow.match(/rgba?\([^)]+\)/);
607
+
608
+ // Extract numeric values (handles both px and pt units)
609
+ const parts = boxShadow.match(/([-\d.]+)(px|pt)/g);
610
+
611
+ if (!parts || parts.length < 2) return null;
612
+
613
+ const offsetX = parseFloat(parts[0]);
614
+ const offsetY = parseFloat(parts[1]);
615
+ const blur = parts.length > 2 ? parseFloat(parts[2]) : 0;
616
+
617
+ // Calculate angle from offsets (in degrees, 0 = right, 90 = down)
618
+ let angle = 0;
619
+ if (offsetX !== 0 || offsetY !== 0) {
620
+ angle = Math.atan2(offsetY, offsetX) * (180 / Math.PI);
621
+ if (angle < 0) angle += 360;
622
+ }
623
+
624
+ // Calculate offset distance (hypotenuse)
625
+ const offset = Math.sqrt(offsetX * offsetX + offsetY * offsetY) * PT_PER_PX;
626
+
627
+ // Extract opacity from rgba
628
+ let opacity = 0.5;
629
+ if (colorMatch) {
630
+ const opacityMatch = colorMatch[0].match(/[\d.]+\)$/);
631
+ if (opacityMatch) {
632
+ opacity = parseFloat(opacityMatch[0].replace(')', ''));
633
+ }
634
+ }
635
+
636
+ return {
637
+ type: 'outer',
638
+ angle: Math.round(angle),
639
+ blur: blur * 0.75, // Convert to points
640
+ color: colorMatch ? rgbToHex(colorMatch[0]) : '000000',
641
+ offset: offset,
642
+ opacity
643
+ };
644
+ };
645
+
646
+ // Parse inline formatting tags (<b>, <i>, <u>, <strong>, <em>, <span>) into text runs
647
+ const parseInlineFormatting = (element, baseOptions = {}, runs = [], baseTextTransform = (x) => x) => {
648
+ let prevNodeIsText = false;
649
+ const elementComputed = window.getComputedStyle(element);
650
+ const hidesDirectText = isVisuallyHidden(element) || hasFullyTransparentText(elementComputed);
651
+
652
+ element.childNodes.forEach((node) => {
653
+ let textTransform = baseTextTransform;
654
+
655
+ const isText = node.nodeType === Node.TEXT_NODE || node.tagName === 'BR';
656
+ if (isText) {
657
+ if (hidesDirectText) {
658
+ prevNodeIsText = false;
659
+ return;
660
+ }
661
+ const text = node.tagName === 'BR' ? '\n' : textTransform(node.textContent.replace(/\s+/g, ' '));
662
+ const prevRun = runs[runs.length - 1];
663
+ if (prevNodeIsText && prevRun) {
664
+ prevRun.text += text;
665
+ } else {
666
+ runs.push({ text, options: { ...baseOptions } });
667
+ }
668
+
669
+ } else if (node.nodeType === Node.ELEMENT_NODE && node.textContent.trim()) {
670
+ const options = { ...baseOptions };
671
+ const computed = window.getComputedStyle(node);
672
+ if (isVisuallyHidden(node)) {
673
+ prevNodeIsText = false;
674
+ if (hasVisibleDescendant(node)) {
675
+ parseInlineFormatting(node, options, runs, textTransform);
676
+ }
677
+ return;
678
+ }
679
+
680
+ if (computed.color) {
681
+ options.color = rgbToHex(computed.color);
682
+ const transparency = extractAlpha(computed.color);
683
+ if (transparency === null) delete options.transparency;
684
+ else options.transparency = transparency;
685
+ }
686
+
687
+ // Handle inline elements with computed styles
688
+ if (node.tagName === 'SPAN' || node.tagName === 'B' || node.tagName === 'STRONG' || node.tagName === 'I' || node.tagName === 'EM' || node.tagName === 'U') {
689
+ const isBold = computed.fontWeight === 'bold' || parseInt(computed.fontWeight) >= 600;
690
+ if (isBold && !shouldSkipBold(computed.fontFamily)) options.bold = true;
691
+ if (computed.fontStyle === 'italic') options.italic = true;
692
+ if (computed.textDecoration && computed.textDecoration.includes('underline')) options.underline = true;
693
+ if (computed.fontSize) options.fontSize = pxToPoints(computed.fontSize);
694
+
695
+ // Apply text-transform on the span element itself
696
+ if (computed.textTransform && computed.textTransform !== 'none') {
697
+ const transformStr = computed.textTransform;
698
+ textTransform = (text) => applyTextTransform(text, transformStr);
699
+ }
700
+
701
+ // Validate: Check for margins on inline elements
702
+ if (computed.marginLeft && parseFloat(computed.marginLeft) > 0) {
703
+ errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-left which is not supported in PowerPoint. Remove margin from inline elements.`);
704
+ }
705
+ if (computed.marginRight && parseFloat(computed.marginRight) > 0) {
706
+ errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-right which is not supported in PowerPoint. Remove margin from inline elements.`);
707
+ }
708
+ if (computed.marginTop && parseFloat(computed.marginTop) > 0) {
709
+ errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-top which is not supported in PowerPoint. Remove margin from inline elements.`);
710
+ }
711
+ if (computed.marginBottom && parseFloat(computed.marginBottom) > 0) {
712
+ errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-bottom which is not supported in PowerPoint. Remove margin from inline elements.`);
713
+ }
714
+
715
+ }
716
+
717
+ // Recursively process any visible child element so hidden or unsupported tags cannot leak through parent textContent.
718
+ parseInlineFormatting(node, options, runs, textTransform);
719
+ }
720
+
721
+ prevNodeIsText = isText;
722
+ });
723
+
724
+ // Trim leading space from first run and trailing space from last run
725
+ if (runs.length > 0) {
726
+ runs[0].text = runs[0].text.replace(/^\s+/, '');
727
+ runs[runs.length - 1].text = runs[runs.length - 1].text.replace(/\s+$/, '');
728
+ }
729
+
730
+ return runs.filter(r => r.text.length > 0);
731
+ };
732
+
733
+ // Extract background from body (image or color)
734
+ const body = document.body;
735
+ const bodyStyle = window.getComputedStyle(body);
736
+ const bgImage = bodyStyle.backgroundImage;
737
+ const bgColor = bodyStyle.backgroundColor;
738
+
739
+ // Collect validation errors
740
+ const errors = [];
741
+
742
+ // Validate: Check for CSS gradients
743
+ if (bgImage && (bgImage.includes('linear-gradient') || bgImage.includes('radial-gradient'))) {
744
+ errors.push(
745
+ 'CSS gradients are not supported. Use Sharp to rasterize gradients as PNG images first, ' +
746
+ 'then reference with background-image: url(\'gradient.png\')'
747
+ );
748
+ }
749
+
750
+ let background;
751
+ if (bgImage && bgImage !== 'none') {
752
+ // Extract URL from url("...") or url(...)
753
+ const urlMatch = bgImage.match(/url\(["']?([^"')]+)["']?\)/);
754
+ if (urlMatch) {
755
+ background = {
756
+ type: 'image',
757
+ path: urlMatch[1]
758
+ };
759
+ } else {
760
+ background = {
761
+ type: 'color',
762
+ value: rgbToHex(bgColor)
763
+ };
764
+ }
765
+ } else {
766
+ background = {
767
+ type: 'color',
768
+ value: rgbToHex(bgColor)
769
+ };
770
+ }
771
+
772
+ // Process all elements
773
+ const elements = [];
774
+ const placeholders = [];
775
+ const textTags = ['P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'UL', 'OL', 'LI'];
776
+ const processed = new Set();
777
+
778
+ document.querySelectorAll('*').forEach((el) => {
779
+ if (processed.has(el)) return;
780
+ if (isVisuallyHidden(el)) {
781
+ if (textTags.includes(el.tagName) && hasVisibleDescendant(el)) {
782
+ // Keep the text container so visible descendants can be extracted.
783
+ } else {
784
+ processed.add(el);
785
+ return;
786
+ }
787
+ }
788
+
789
+ // Validate text elements don't have backgrounds, borders, or shadows
790
+ if (textTags.includes(el.tagName)) {
791
+ const computed = window.getComputedStyle(el);
792
+ const hasBg = computed.backgroundColor && computed.backgroundColor !== 'rgba(0, 0, 0, 0)';
793
+ const hasBorder = (computed.borderWidth && parseFloat(computed.borderWidth) > 0) ||
794
+ (computed.borderTopWidth && parseFloat(computed.borderTopWidth) > 0) ||
795
+ (computed.borderRightWidth && parseFloat(computed.borderRightWidth) > 0) ||
796
+ (computed.borderBottomWidth && parseFloat(computed.borderBottomWidth) > 0) ||
797
+ (computed.borderLeftWidth && parseFloat(computed.borderLeftWidth) > 0);
798
+ const hasShadow = computed.boxShadow && computed.boxShadow !== 'none';
799
+
800
+ if (hasBg || hasBorder || hasShadow) {
801
+ errors.push(
802
+ `Text element <${el.tagName.toLowerCase()}> has ${hasBg ? 'background' : hasBorder ? 'border' : 'shadow'}. ` +
803
+ 'Backgrounds, borders, and shadows are only supported on <div> elements, not text elements.'
804
+ );
805
+ return;
806
+ }
807
+ }
808
+
809
+ // Extract placeholder elements (for charts, etc.)
810
+ if (el.className && el.className.includes('placeholder')) {
811
+ const rect = el.getBoundingClientRect();
812
+ if (rect.width === 0 || rect.height === 0) {
813
+ errors.push(
814
+ `Placeholder "${el.id || 'unnamed'}" has ${rect.width === 0 ? 'width: 0' : 'height: 0'}. Check the layout CSS.`
815
+ );
816
+ } else {
817
+ placeholders.push({
818
+ id: el.id || `placeholder-${placeholders.length}`,
819
+ x: pxToInch(rect.left),
820
+ y: pxToInch(rect.top),
821
+ w: pxToInch(rect.width),
822
+ h: pxToInch(rect.height)
823
+ });
824
+ }
825
+ processed.add(el);
826
+ return;
827
+ }
828
+
829
+ // Extract images
830
+ if (el.tagName === 'IMG') {
831
+ const rect = el.getBoundingClientRect();
832
+ if (rect.width > 0 && rect.height > 0) {
833
+ elements.push({
834
+ type: 'image',
835
+ src: el.src,
836
+ position: {
837
+ x: pxToInch(rect.left),
838
+ y: pxToInch(rect.top),
839
+ w: pxToInch(rect.width),
840
+ h: pxToInch(rect.height)
841
+ }
842
+ });
843
+ processed.add(el);
844
+ return;
845
+ }
846
+ }
847
+
848
+ // Extract DIVs with backgrounds/borders as shapes
849
+ const isContainer = el.tagName === 'DIV' && !textTags.includes(el.tagName);
850
+ if (isContainer) {
851
+ const computed = window.getComputedStyle(el);
852
+ const hasBg = computed.backgroundColor && computed.backgroundColor !== 'rgba(0, 0, 0, 0)';
853
+
854
+ // Validate: Check for unwrapped text content in DIV
855
+ for (const node of el.childNodes) {
856
+ if (node.nodeType === Node.TEXT_NODE) {
857
+ const text = node.textContent.trim();
858
+ if (text) {
859
+ errors.push(
860
+ `DIV element contains unwrapped text "${text.substring(0, 50)}${text.length > 50 ? '...' : ''}". ` +
861
+ 'All text must be wrapped in <p>, <h1>-<h6>, <ul>, or <ol> tags to appear in PowerPoint.'
862
+ );
863
+ }
864
+ }
865
+ }
866
+
867
+ // Check for background images on shapes
868
+ const bgImage = computed.backgroundImage;
869
+ if (bgImage && bgImage !== 'none') {
870
+ errors.push(
871
+ 'Background images on DIV elements are not supported. ' +
872
+ 'Use solid colors or borders for shapes, or use slide.addImage() in PptxGenJS to layer images.'
873
+ );
874
+ return;
875
+ }
876
+
877
+ // Check for borders - both uniform and partial
878
+ const borderTop = computed.borderTopWidth;
879
+ const borderRight = computed.borderRightWidth;
880
+ const borderBottom = computed.borderBottomWidth;
881
+ const borderLeft = computed.borderLeftWidth;
882
+ const borders = [borderTop, borderRight, borderBottom, borderLeft].map(b => parseFloat(b) || 0);
883
+ const hasBorder = borders.some(b => b > 0);
884
+ const hasUniformBorder = hasBorder && borders.every(b => b === borders[0]);
885
+ const borderLines = [];
886
+
887
+ if (hasBorder && !hasUniformBorder) {
888
+ const rect = el.getBoundingClientRect();
889
+ const x = pxToInch(rect.left);
890
+ const y = pxToInch(rect.top);
891
+ const w = pxToInch(rect.width);
892
+ const h = pxToInch(rect.height);
893
+
894
+ // Collect lines to add after shape (inset by half the line width to center on edge)
895
+ if (parseFloat(borderTop) > 0) {
896
+ const widthPt = pxToPoints(borderTop);
897
+ const inset = (widthPt / 72) / 2; // Convert points to inches, then half
898
+ borderLines.push({
899
+ type: 'line',
900
+ x1: x, y1: y + inset, x2: x + w, y2: y + inset,
901
+ width: widthPt,
902
+ color: rgbToHex(computed.borderTopColor)
903
+ });
904
+ }
905
+ if (parseFloat(borderRight) > 0) {
906
+ const widthPt = pxToPoints(borderRight);
907
+ const inset = (widthPt / 72) / 2;
908
+ borderLines.push({
909
+ type: 'line',
910
+ x1: x + w - inset, y1: y, x2: x + w - inset, y2: y + h,
911
+ width: widthPt,
912
+ color: rgbToHex(computed.borderRightColor)
913
+ });
914
+ }
915
+ if (parseFloat(borderBottom) > 0) {
916
+ const widthPt = pxToPoints(borderBottom);
917
+ const inset = (widthPt / 72) / 2;
918
+ borderLines.push({
919
+ type: 'line',
920
+ x1: x, y1: y + h - inset, x2: x + w, y2: y + h - inset,
921
+ width: widthPt,
922
+ color: rgbToHex(computed.borderBottomColor)
923
+ });
924
+ }
925
+ if (parseFloat(borderLeft) > 0) {
926
+ const widthPt = pxToPoints(borderLeft);
927
+ const inset = (widthPt / 72) / 2;
928
+ borderLines.push({
929
+ type: 'line',
930
+ x1: x + inset, y1: y, x2: x + inset, y2: y + h,
931
+ width: widthPt,
932
+ color: rgbToHex(computed.borderLeftColor)
933
+ });
934
+ }
935
+ }
936
+
937
+ if (hasBg || hasBorder) {
938
+ const rect = el.getBoundingClientRect();
939
+ if (rect.width > 0 && rect.height > 0) {
940
+ const shadow = parseBoxShadow(computed.boxShadow);
941
+
942
+ // Only add shape if there's background or uniform border
943
+ if (hasBg || hasUniformBorder) {
944
+ elements.push({
945
+ type: 'shape',
946
+ text: '', // Shape only - child text elements render on top
947
+ position: {
948
+ x: pxToInch(rect.left),
949
+ y: pxToInch(rect.top),
950
+ w: pxToInch(rect.width),
951
+ h: pxToInch(rect.height)
952
+ },
953
+ shape: {
954
+ fill: hasBg ? rgbToHex(computed.backgroundColor) : null,
955
+ transparency: hasBg ? extractAlpha(computed.backgroundColor) : null,
956
+ line: hasUniformBorder ? {
957
+ color: rgbToHex(computed.borderColor),
958
+ width: pxToPoints(computed.borderWidth)
959
+ } : null,
960
+ // Convert border-radius to rectRadius (in inches)
961
+ // % values: 50%+ = circle (1), <50% = percentage of min dimension
962
+ // pt values: divide by 72 (72pt = 1 inch)
963
+ // px values: divide by 96 (96px = 1 inch)
964
+ rectRadius: (() => {
965
+ const radius = computed.borderRadius;
966
+ const radiusValue = parseFloat(radius);
967
+ if (radiusValue === 0) return 0;
968
+
969
+ if (radius.includes('%')) {
970
+ if (radiusValue >= 50) return 1;
971
+ // Calculate percentage of smaller dimension
972
+ const minDim = Math.min(rect.width, rect.height);
973
+ return (radiusValue / 100) * pxToInch(minDim);
974
+ }
975
+
976
+ if (radius.includes('pt')) return radiusValue / 72;
977
+ return radiusValue / PX_PER_IN;
978
+ })(),
979
+ shadow: shadow
980
+ }
981
+ });
982
+ }
983
+
984
+ // Add partial border lines
985
+ elements.push(...borderLines);
986
+
987
+ processed.add(el);
988
+ return;
989
+ }
990
+ }
991
+ }
992
+
993
+ // Extract bullet lists as single text block
994
+ if (el.tagName === 'UL' || el.tagName === 'OL') {
995
+ const rect = el.getBoundingClientRect();
996
+ if (rect.width === 0 || rect.height === 0) return;
997
+
998
+ const liElements = Array.from(el.querySelectorAll('li')).filter((li) => !isVisuallyHidden(li));
999
+ if (liElements.length === 0) {
1000
+ processed.add(el);
1001
+ return;
1002
+ }
1003
+ const items = [];
1004
+ const ulComputed = window.getComputedStyle(el);
1005
+ const ulPaddingLeftPt = pxToPoints(ulComputed.paddingLeft);
1006
+
1007
+ // Split: margin-left for bullet position, indent for text position
1008
+ // margin-left + indent = ul padding-left
1009
+ const marginLeft = ulPaddingLeftPt * 0.5;
1010
+ const textIndent = ulPaddingLeftPt * 0.5;
1011
+
1012
+ liElements.forEach((li, idx) => {
1013
+ const isLast = idx === liElements.length - 1;
1014
+ const runs = parseInlineFormatting(li, { breakLine: false });
1015
+ // Clean manual bullets from first run
1016
+ if (runs.length > 0) {
1017
+ runs[0].text = runs[0].text.replace(/^[•\-\*▪▸]\s*/, '');
1018
+ runs[0].options.bullet = { indent: textIndent };
1019
+ }
1020
+ // Set breakLine on last run
1021
+ if (runs.length > 0 && !isLast) {
1022
+ runs[runs.length - 1].options.breakLine = true;
1023
+ }
1024
+ items.push(...runs);
1025
+ });
1026
+
1027
+ if (items.length === 0) {
1028
+ liElements.forEach((li) => {
1029
+ processed.add(li);
1030
+ });
1031
+ processed.add(el);
1032
+ return;
1033
+ }
1034
+
1035
+ const computed = window.getComputedStyle(liElements[0] || el);
1036
+
1037
+ elements.push({
1038
+ type: 'list',
1039
+ items: items,
1040
+ position: {
1041
+ x: pxToInch(rect.left),
1042
+ y: pxToInch(rect.top),
1043
+ w: pxToInch(rect.width),
1044
+ h: pxToInch(rect.height)
1045
+ },
1046
+ style: {
1047
+ fontSize: pxToPoints(computed.fontSize),
1048
+ fontFace: computed.fontFamily.split(',')[0].replace(/['"]/g, '').trim(),
1049
+ color: rgbToHex(computed.color),
1050
+ transparency: extractAlpha(computed.color),
1051
+ align: computed.textAlign === 'start' ? 'left' : computed.textAlign,
1052
+ lineSpacing: computed.lineHeight && computed.lineHeight !== 'normal' ? pxToPoints(computed.lineHeight) : null,
1053
+ paraSpaceBefore: 0,
1054
+ paraSpaceAfter: pxToPoints(computed.marginBottom),
1055
+ // PptxGenJS margin array is [left, right, bottom, top]
1056
+ margin: [marginLeft, 0, 0, 0]
1057
+ }
1058
+ });
1059
+
1060
+ liElements.forEach((li) => {
1061
+ processed.add(li);
1062
+ });
1063
+ processed.add(el);
1064
+ return;
1065
+ }
1066
+
1067
+ // Extract text elements (P, H1, H2, etc.)
1068
+ if (!textTags.includes(el.tagName)) return;
1069
+
1070
+ const rect = el.getBoundingClientRect();
1071
+ const text = el.textContent.trim();
1072
+ if (rect.width === 0 || rect.height === 0 || !text) return;
1073
+
1074
+ const computed = window.getComputedStyle(el);
1075
+ const hasFormatting = Array.from(el.childNodes).some((node) => node.nodeType === Node.ELEMENT_NODE);
1076
+ if (hasFullyTransparentText(computed) && !hasFormatting) return;
1077
+
1078
+ // Validate: Check for manual bullet symbols in text elements (not in lists)
1079
+ if (el.tagName !== 'LI' && /^[•\-\*▪▸○●◆◇■□]\s/.test(text.trimStart())) {
1080
+ errors.push(
1081
+ `Text element <${el.tagName.toLowerCase()}> starts with bullet symbol "${text.substring(0, 20)}...". ` +
1082
+ 'Use <ul> or <ol> lists instead of manual bullet symbols.'
1083
+ );
1084
+ return;
1085
+ }
1086
+
1087
+ const rotation = getRotation(computed.transform, computed.writingMode);
1088
+ const { x, y, w, h } = getPositionAndSize(el, rect, rotation);
1089
+
1090
+ const baseStyle = {
1091
+ fontSize: pxToPoints(computed.fontSize),
1092
+ fontFace: computed.fontFamily.split(',')[0].replace(/['"]/g, '').trim(),
1093
+ color: rgbToHex(computed.color),
1094
+ align: computed.textAlign === 'start' ? 'left' : computed.textAlign,
1095
+ lineSpacing: pxToPoints(computed.lineHeight),
1096
+ paraSpaceBefore: pxToPoints(computed.marginTop),
1097
+ paraSpaceAfter: pxToPoints(computed.marginBottom),
1098
+ // PptxGenJS margin array is [left, right, bottom, top] (not [top, right, bottom, left] as documented)
1099
+ margin: [
1100
+ pxToPoints(computed.paddingLeft),
1101
+ pxToPoints(computed.paddingRight),
1102
+ pxToPoints(computed.paddingBottom),
1103
+ pxToPoints(computed.paddingTop)
1104
+ ]
1105
+ };
1106
+
1107
+ const transparency = extractAlpha(computed.color);
1108
+ if (transparency !== null) baseStyle.transparency = transparency;
1109
+
1110
+ if (rotation !== null) baseStyle.rotate = rotation;
1111
+
1112
+ if (hasFormatting) {
1113
+ // Text with inline formatting
1114
+ const transformStr = computed.textTransform;
1115
+ const runs = parseInlineFormatting(el, {}, [], (str) => applyTextTransform(str, transformStr));
1116
+ if (runs.length === 0) return;
1117
+
1118
+ // Adjust lineSpacing based on largest fontSize in runs
1119
+ const adjustedStyle = { ...baseStyle };
1120
+ if (runs.some((run) => run.options?.transparency !== 100)) {
1121
+ delete adjustedStyle.transparency;
1122
+ }
1123
+ if (adjustedStyle.lineSpacing) {
1124
+ const maxFontSize = Math.max(
1125
+ adjustedStyle.fontSize,
1126
+ ...runs.map(r => r.options?.fontSize || 0)
1127
+ );
1128
+ if (maxFontSize > adjustedStyle.fontSize) {
1129
+ const lineHeightMultiplier = adjustedStyle.lineSpacing / adjustedStyle.fontSize;
1130
+ adjustedStyle.lineSpacing = maxFontSize * lineHeightMultiplier;
1131
+ }
1132
+ }
1133
+
1134
+ elements.push({
1135
+ type: el.tagName.toLowerCase(),
1136
+ text: runs,
1137
+ position: { x: pxToInch(x), y: pxToInch(y), w: pxToInch(w), h: pxToInch(h) },
1138
+ style: adjustedStyle
1139
+ });
1140
+ } else {
1141
+ // Plain text - inherit CSS formatting
1142
+ const textTransform = computed.textTransform;
1143
+ const transformedText = applyTextTransform(text, textTransform);
1144
+
1145
+ const isBold = computed.fontWeight === 'bold' || parseInt(computed.fontWeight) >= 600;
1146
+
1147
+ elements.push({
1148
+ type: el.tagName.toLowerCase(),
1149
+ text: transformedText,
1150
+ position: { x: pxToInch(x), y: pxToInch(y), w: pxToInch(w), h: pxToInch(h) },
1151
+ style: {
1152
+ ...baseStyle,
1153
+ bold: isBold && !shouldSkipBold(computed.fontFamily),
1154
+ italic: computed.fontStyle === 'italic',
1155
+ underline: computed.textDecoration.includes('underline')
1156
+ }
1157
+ });
1158
+ }
1159
+
1160
+ processed.add(el);
1161
+ });
1162
+
1163
+ return { background, elements, placeholders, errors };
1164
+ });
1165
+ }
1166
+
1167
+ async function html2pptx(htmlFile, pres, options = {}) {
1168
+ const {
1169
+ tmpDir = process.env.TMPDIR || '/tmp',
1170
+ slide = null,
1171
+ fitToLayout = false,
1172
+ browser = null
1173
+ } = options;
1174
+
1175
+ try {
1176
+ const activeBrowser = browser || await launchBrowser(tmpDir);
1177
+ const ownsBrowser = browser === null;
1178
+
1179
+ let bodyDimensions;
1180
+ let slideData;
1181
+
1182
+ const filePath = path.isAbsolute(htmlFile) ? htmlFile : path.join(process.cwd(), htmlFile);
1183
+ const validationErrors = [];
1184
+ let page;
1185
+
1186
+ try {
1187
+ page = await activeBrowser.newPage();
1188
+
1189
+ await loadPageUrl(page, `file://${filePath}`);
1190
+ await waitForDynamicLibraryRender(page);
1191
+ await rasterizeDynamicVisuals(page);
1192
+
1193
+ bodyDimensions = await getBodyDimensions(page);
1194
+
1195
+ await page.setViewportSize({
1196
+ width: Math.round(bodyDimensions.width),
1197
+ height: Math.round(bodyDimensions.height)
1198
+ });
1199
+
1200
+ slideData = await extractSlideData(page);
1201
+ } finally {
1202
+ try {
1203
+ if (page) await page.close();
1204
+ } finally {
1205
+ if (ownsBrowser) await activeBrowser.close();
1206
+ }
1207
+ }
1208
+
1209
+ // Collect all validation errors
1210
+ if (bodyDimensions.errors && bodyDimensions.errors.length > 0) {
1211
+ validationErrors.push(...bodyDimensions.errors);
1212
+ }
1213
+
1214
+ const dimensionErrors = validateDimensions(bodyDimensions, pres, { fitToLayout });
1215
+ if (dimensionErrors.length > 0) {
1216
+ validationErrors.push(...dimensionErrors);
1217
+ }
1218
+
1219
+ let effectiveBodyDimensions = bodyDimensions;
1220
+ if (fitToLayout) {
1221
+ const scale = getLayoutScale(bodyDimensions, pres);
1222
+ scaleSlideData(slideData, scale);
1223
+ effectiveBodyDimensions = {
1224
+ ...bodyDimensions,
1225
+ width: bodyDimensions.width * scale.x,
1226
+ height: bodyDimensions.height * scale.y,
1227
+ };
1228
+ }
1229
+
1230
+ const textBoxPositionErrors = validateTextBoxPosition(slideData, effectiveBodyDimensions);
1231
+ if (textBoxPositionErrors.length > 0) {
1232
+ validationErrors.push(...textBoxPositionErrors);
1233
+ }
1234
+
1235
+ if (slideData.errors && slideData.errors.length > 0) {
1236
+ validationErrors.push(...slideData.errors);
1237
+ }
1238
+
1239
+ // Throw all errors at once if any exist
1240
+ if (validationErrors.length > 0) {
1241
+ const errorMessage = validationErrors.length === 1
1242
+ ? validationErrors[0]
1243
+ : `Multiple validation errors found:\n${validationErrors.map((e, i) => ` ${i + 1}. ${e}`).join('\n')}`;
1244
+ throw new Error(errorMessage);
1245
+ }
1246
+
1247
+ const targetSlide = slide || pres.addSlide();
1248
+
1249
+ await addBackground(slideData, targetSlide, tmpDir);
1250
+ addElements(slideData, targetSlide, pres);
1251
+
1252
+ return { slide: targetSlide, placeholders: slideData.placeholders };
1253
+ } catch (error) {
1254
+ if (!error.message.startsWith(htmlFile)) {
1255
+ throw new Error(`${htmlFile}: ${error.message}`);
1256
+ }
1257
+ throw error;
1258
+ }
1259
+ }
1260
+
1261
+ module.exports = html2pptx;
1262
+ module.exports.launchBrowser = launchBrowser;