--mode editable
*
- * 特点:
+ * --mode image 特点:
* - 每张 slide 截图成 PNG,满铺一张 PPTX 页面
* - 视觉 100% 保真(因为就是图片)
- * - ⚠️ 文字不可编辑(文字变成了图片)
+ * - 文字不可编辑
+ * - HTML 随便写,不挑格式
*
- * 如果用户需要「可编辑文字」的 PPTX:
- * ❌ 不要在 claude-design 的 HTML 上硬上 html2pptx——claude-design 的 HTML 视觉自由度高,
- * 很少能满足 html2pptx 的严格约束(p 标签语法、无 ::before、无 span margin 等)。
- * 实测 32 页里能 pass 的不到 30%,剩下的要逐页改造 + 逐页修字体溢出——工时失控。
- * ✅ 正确做法:切换到 **huashu-slides** skill 的 Path A,按它的 HTML 格式**从头重构**
- * 每一页。huashu-slides 的 HTML 从一开始就符合 html2pptx 约束,可 100% 导出可编辑 PPTX。
+ * --mode editable 特点:
+ * - 调用 scripts/html2pptx.js 把 HTML DOM 逐元素翻译成 PowerPoint 对象
+ * - 文字是真文本框,PPT 里直接双击能编辑
+ * - ⚠️ HTML 必须符合 4 条硬约束(见 references/editable-pptx.md):
+ * 1. 文字包在 /
- 里(div 不能直接放文字)
+ * 2. 不用 CSS 渐变
+ * 3.
/ 不能有 background/border/shadow(放外层 div)
+ * 4. div 不能 background-image(用
)
+ * - body 尺寸默认 960pt × 540pt(LAYOUT_WIDE,13.333″ × 7.5″)
+ * - 视觉驱动的 HTML 几乎无法 pass —— 必须从写 HTML 的第一行就按约束写
*
- * 依赖:playwright pptxgenjs
- * npm install playwright pptxgenjs
+ * 依赖:
+ * --mode image: npm install playwright pptxgenjs
+ * --mode editable: npm install playwright pptxgenjs sharp
*
- * 会按文件名排序(01-xxx.html → 02-xxx.html → ...)
+ * 按文件名排序(01-xxx.html → 02-xxx.html → ...)。
*/
import { chromium } from 'playwright';
@@ -28,36 +41,32 @@ import pptxgen from 'pptxgenjs';
import fs from 'fs/promises';
import path from 'path';
import os from 'os';
+import { fileURLToPath } from 'url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
function parseArgs() {
- const args = { width: 1920, height: 1080 };
+ const args = { width: 1920, height: 1080, mode: 'image' };
const a = process.argv.slice(2);
for (let i = 0; i < a.length; i += 2) {
const k = a[i].replace(/^--/, '');
args[k] = a[i + 1];
}
if (!args.slides || !args.out) {
- console.error('用法: node export_deck_pptx.mjs --slides --out [--width 1920] [--height 1080]');
+ console.error('用法: node export_deck_pptx.mjs --slides --out [--mode image|editable] [--width 1920] [--height 1080]');
process.exit(1);
}
args.width = parseInt(args.width);
args.height = parseInt(args.height);
+ if (!['image', 'editable'].includes(args.mode)) {
+ console.error(`未知 --mode: ${args.mode}。支持: image, editable`);
+ process.exit(1);
+ }
return args;
}
-async function main() {
- const { slides, out, width, height } = parseArgs();
- const slidesDir = path.resolve(slides);
- const outFile = path.resolve(out);
-
- const files = (await fs.readdir(slidesDir))
- .filter(f => f.endsWith('.html'))
- .sort();
- if (!files.length) {
- console.error(`No .html files found in ${slidesDir}`);
- process.exit(1);
- }
- console.log(`Found ${files.length} slides, rendering to PNG...`);
+async function exportImage({ slidesDir, outFile, files, width, height }) {
+ console.log(`[image mode] Rendering ${files.length} slides as PNG...`);
const browser = await chromium.launch();
const ctx = await browser.newContext({ viewport: { width, height } });
@@ -76,7 +85,6 @@ async function main() {
}
await browser.close();
- // Build PPTX
const pres = new pptxgen();
pres.defineLayout({ name: 'DECK', width: width / 96, height: height / 96 });
pres.layout = 'DECK';
@@ -86,12 +94,74 @@ async function main() {
}
await pres.writeFile({ fileName: outFile });
- // cleanup
for (const p of pngs) await fs.unlink(p).catch(() => {});
await fs.rmdir(tmpDir).catch(() => {});
- console.log(`\n✓ Wrote ${outFile} (${files.length} slides, image mode)`);
- console.log(` 要可编辑?改走 huashu-slides 的 Path A 从头重构 HTML。`);
+ console.log(`\n✓ Wrote ${outFile} (${files.length} slides, image mode, 文字不可编辑)`);
+}
+
+async function exportEditable({ slidesDir, outFile, files }) {
+ console.log(`[editable mode] Converting ${files.length} slides via html2pptx...`);
+
+ // 动态 require html2pptx.js(CommonJS 模块)
+ const { createRequire } = await import('module');
+ const require = createRequire(import.meta.url);
+ let html2pptx;
+ try {
+ html2pptx = require(path.join(__dirname, 'html2pptx.js'));
+ } catch (e) {
+ console.error(`✗ 加载 html2pptx.js 失败:${e.message}`);
+ console.error(` 该模块依赖 sharp —— 请跑 npm install sharp 后重试。`);
+ process.exit(1);
+ }
+
+ const pres = new pptxgen();
+ pres.layout = 'LAYOUT_WIDE'; // 13.333 × 7.5 inch,对应 HTML body 960 × 540 pt
+
+ const errors = [];
+ for (let i = 0; i < files.length; i++) {
+ const f = files[i];
+ const fullPath = path.join(slidesDir, f);
+ try {
+ await html2pptx(fullPath, pres);
+ console.log(` [${i + 1}/${files.length}] ${f} ✓`);
+ } catch (e) {
+ console.error(` [${i + 1}/${files.length}] ${f} ✗ ${e.message}`);
+ errors.push({ file: f, error: e.message });
+ }
+ }
+
+ if (errors.length) {
+ console.error(`\n⚠️ ${errors.length} 张 slide 转换失败。常见原因:HTML 不符合 4 条硬约束。`);
+ console.error(` 详见 references/editable-pptx.md 的「常见错误速查」。`);
+ if (errors.length === files.length) {
+ console.error(`✗ 全部失败,不生成 PPTX。`);
+ process.exit(1);
+ }
+ }
+
+ await pres.writeFile({ fileName: outFile });
+ console.log(`\n✓ Wrote ${outFile} (${files.length - errors.length}/${files.length} slides, editable mode, 文字可在 PPT 中直接编辑)`);
+}
+
+async function main() {
+ const { slides, out, width, height, mode } = parseArgs();
+ const slidesDir = path.resolve(slides);
+ const outFile = path.resolve(out);
+
+ const files = (await fs.readdir(slidesDir))
+ .filter(f => f.endsWith('.html'))
+ .sort();
+ if (!files.length) {
+ console.error(`No .html files found in ${slidesDir}`);
+ process.exit(1);
+ }
+
+ if (mode === 'image') {
+ await exportImage({ slidesDir, outFile, files, width, height });
+ } else {
+ await exportEditable({ slidesDir, outFile, files });
+ }
}
main().catch(e => { console.error(e); process.exit(1); });
diff --git a/scripts/export_deck_stage_pdf.mjs b/scripts/export_deck_stage_pdf.mjs
new file mode 100644
index 0000000..a5526b8
--- /dev/null
+++ b/scripts/export_deck_stage_pdf.mjs
@@ -0,0 +1,130 @@
+#!/usr/bin/env node
+/**
+ * export_deck_stage_pdf.mjs — 单文件 架构专用 PDF 导出
+ *
+ * 用法:
+ * node export_deck_stage_pdf.mjs --html --out [--width 1920] [--height 1080]
+ *
+ * 什么时候用这个脚本?
+ * - 你的 deck 是**单 HTML 文件**,所有 slide 是 ``,外层用 `` 包裹
+ * - 此时 `export_deck_pdf.mjs`(多文件专用)用不上
+ *
+ * 为什么不能直接 `page.pdf()`(2026-04-20 踩坑记录):
+ * 1. deck-stage 的 shadow CSS `::slotted(section) { display: none }` 让只有 active slide 可见
+ * 2. print 媒体下外层 `!important` 压不住 shadow DOM 规则
+ * 3. 结果:PDF 永远只有 1 页(active 那张)
+ *
+ * 解决方案:
+ * 打开 HTML 后,用 page.evaluate 把所有 section 从 deck-stage slot 拔出来,
+ * 挂到 body 下一个普通 div,内联 style 强制 position:relative + 固定尺寸,
+ * 每个 section 加 page-break-after: always,最后一个改 auto 避免尾部空白页。
+ *
+ * 依赖:playwright
+ * npm install playwright
+ *
+ * 输出特点:
+ * - 文字保留矢量(可复制、可搜索)
+ * - 视觉 1:1 保真
+ * - 字体必须能被 Chromium 加载(本地字体或 Google Fonts)
+ */
+
+import { chromium } from 'playwright';
+import fs from 'fs/promises';
+import path from 'path';
+
+function parseArgs() {
+ const args = { width: 1920, height: 1080 };
+ const a = process.argv.slice(2);
+ for (let i = 0; i < a.length; i += 2) {
+ const k = a[i].replace(/^--/, '');
+ args[k] = a[i + 1];
+ }
+ if (!args.html || !args.out) {
+ console.error('用法: node export_deck_stage_pdf.mjs --html --out [--width 1920] [--height 1080]');
+ process.exit(1);
+ }
+ args.width = parseInt(args.width);
+ args.height = parseInt(args.height);
+ return args;
+}
+
+async function main() {
+ const { html, out, width, height } = parseArgs();
+ const htmlAbs = path.resolve(html);
+ const outFile = path.resolve(out);
+
+ await fs.access(htmlAbs).catch(() => {
+ console.error(`HTML file not found: ${htmlAbs}`);
+ process.exit(1);
+ });
+
+ console.log(`Rendering ${path.basename(htmlAbs)} → ${path.basename(outFile)}`);
+
+ const browser = await chromium.launch();
+ const ctx = await browser.newContext({ viewport: { width, height } });
+ const page = await ctx.newPage();
+
+ await page.goto('file://' + htmlAbs, { waitUntil: 'networkidle' });
+ await page.waitForTimeout(2500); // 等 Google Fonts + deck-stage init
+
+ // 核心修复:把 section 从 shadow DOM slot 拔出来摊平
+ const sectionCount = await page.evaluate(({ W, H }) => {
+ const stage = document.querySelector('deck-stage');
+ if (!stage) throw new Error(' not found — 这个脚本只适用于单文件 deck-stage 架构');
+ const sections = Array.from(stage.querySelectorAll(':scope > section'));
+ if (!sections.length) throw new Error('No found inside ');
+
+ // 注入打印样式
+ const style = document.createElement('style');
+ style.textContent = `
+ @page { size: ${W}px ${H}px; margin: 0; }
+ html, body { margin: 0 !important; padding: 0 !important; background: #fff; }
+ deck-stage { display: none !important; }
+ `;
+ document.head.appendChild(style);
+
+ // 摊平到 body 下
+ const container = document.createElement('div');
+ container.id = 'print-container';
+ sections.forEach(s => {
+ // 内联 style 拿到最高优先级;确保 position:relative 让 absolute 子元素正确约束
+ s.style.cssText = `
+ width: ${W}px !important;
+ height: ${H}px !important;
+ display: block !important;
+ position: relative !important;
+ overflow: hidden !important;
+ page-break-after: always !important;
+ break-after: page !important;
+ margin: 0 !important;
+ padding: 0 !important;
+ `;
+ container.appendChild(s);
+ });
+ // 最后一页不分页,避免尾部空白页
+ const last = sections[sections.length - 1];
+ last.style.pageBreakAfter = 'auto';
+ last.style.breakAfter = 'auto';
+ document.body.appendChild(container);
+ return sections.length;
+ }, { W: width, H: height });
+
+ await page.waitForTimeout(800);
+
+ await page.pdf({
+ path: outFile,
+ width: `${width}px`,
+ height: `${height}px`,
+ printBackground: true,
+ preferCSSPageSize: true,
+ });
+
+ await browser.close();
+
+ const stat = await fs.stat(outFile);
+ const kb = (stat.size / 1024).toFixed(0);
+ console.log(`\n✓ Wrote ${outFile} (${kb} KB, ${sectionCount} pages, vector)`);
+ console.log(` 验证页数:mdimport "${outFile}" && pdfinfo "${outFile}" | grep Pages`);
+}
+
+main().catch(e => { console.error(e); process.exit(1); });
diff --git a/scripts/render-video.js b/scripts/render-video.js
index 5115590..36ea381 100755
--- a/scripts/render-video.js
+++ b/scripts/render-video.js
@@ -103,7 +103,10 @@ console.log(` output: ${MP4_OUT}`);
viewport: { width: WIDTH, height: HEIGHT },
});
const warmupPage = await warmupCtx.newPage();
- await warmupPage.goto(url, { waitUntil: 'networkidle' });
+ // 'load' not 'networkidle' — unpkg/Google Fonts can keep connections alive
+ // past our 30s budget even after all critical resources are in. __ready
+ // flag + FONT_WAIT handle animation-readiness properly.
+ await warmupPage.goto(url, { waitUntil: 'load', timeout: 60000 });
await warmupPage.waitForTimeout(FONT_WAIT * 1000);
await warmupCtx.close();
@@ -118,6 +121,12 @@ console.log(` output: ${MP4_OUT}`);
},
});
+ // Tell the page it's being recorded — animations.jsx Stage reads this
+ // and forces loop=false so the export ends on the final frame instead of
+ // capturing the start of the next cycle. Hand-written Stage components
+ // should also honor this signal (see animation-pitfalls.md §13).
+ await recordCtx.addInitScript(() => { window.__recording = true; });
+
// Inject CSS + JS heuristic to hide "chrome" elements.
// Two layers:
// A. CSS selectors for common class-name conventions (cheap)
@@ -183,7 +192,7 @@ console.log(` output: ${MP4_OUT}`);
// mount + fonts.ready). That elapsed time = exact trim offset.
const T0 = Date.now();
const page = await recordCtx.newPage();
- await page.goto(url, { waitUntil: 'networkidle' });
+ await page.goto(url, { waitUntil: 'load', timeout: 60000 });
// Wait for animation ready signal. Stage component (animations.jsx) sets
// window.__ready = true on its first rAF after mount + fonts.ready.
@@ -195,14 +204,38 @@ console.log(` output: ${MP4_OUT}`);
).then(() => true).catch(() => false);
if (hasReady) {
+ // 第二道防线:主动把动画 time 归零——对付 HTML 不严格遵守 starter tick 模板
+ // 的情况(例如 lastTick 用 performance.now() 导致字体加载时间被算进首帧 dt)
+ // 详见 references/animation-pitfalls.md §12
+ const seekCorrected = await page.evaluate(() => {
+ if (typeof window.__seek === 'function') {
+ window.__seek(0);
+ return true;
+ }
+ return false;
+ });
+ if (seekCorrected) {
+ // 等两个 rAF 让 seek 生效并渲染出 t=0 的画面
+ await page.evaluate(() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))));
+ }
animationStartSec = (Date.now() - T0) / 1000;
- console.log(`▸ Ready at ${animationStartSec.toFixed(2)}s (from window.__ready)`);
+ console.log(`▸ Ready at ${animationStartSec.toFixed(2)}s (from window.__ready${seekCorrected ? ' + __seek(0) correction' : ''})`);
} else {
await page.waitForTimeout(FONT_WAIT * 1000);
animationStartSec = (Date.now() - T0) / 1000;
- console.log(`▸ No window.__ready signal; using fallback wait (${animationStartSec.toFixed(2)}s)`);
- console.log(` tip: in animations.jsx-based HTML this is automatic;`);
- console.log(` otherwise set window.__ready=true after your first paint.`);
+ // Fallback offset is unreliable: animation may have started in raf loop
+ // already, so trim could land mid-cycle. Add 0.5s safety margin (see
+ // animation-pitfalls.md §13). Loud warning so user knows to fix the HTML.
+ console.log('');
+ console.log(` ⚠️ WARNING: window.__ready signal not detected within ${READY_TIMEOUT}s`);
+ console.log(` Recording will use fallback trim of ${animationStartSec.toFixed(2)}s + 0.5s safety margin.`);
+ console.log(` This is UNRELIABLE — your video may start mid-animation or skip frames.`);
+ console.log('');
+ console.log(` FIX: in your HTML's animation tick (or rAF first frame), add:`);
+ console.log(` window.__ready = true;`);
+ console.log(` animations.jsx-based HTML does this automatically. If you wrote your`);
+ console.log(` own Stage, see references/animation-pitfalls.md §12 for the pattern.`);
+ console.log('');
}
// Now let the animation play out its full duration
@@ -221,12 +254,14 @@ console.log(` output: ${MP4_OUT}`);
console.log(`▸ WebM: ${(fs.statSync(webmPath).size / 1024 / 1024).toFixed(1)} MB`);
// Resolve final trim offset:
- // - manual --trim=X → use X (explicit user override)
- // - otherwise → use animationStartSec (measured), with a tiny
- // +0.05s nudge to clear the first Babel-commit frame
+ // - manual --trim=X → use X (explicit user override)
+ // - hasReady → animationStartSec + 0.05s (Babel-commit nudge)
+ // - fallback (no __ready) → animationStartSec + 0.5s safety margin (raf
+ // loop may have started running already; without
+ // this we'd capture mid-cycle frames)
const resolvedTrim = TRIM_OVERRIDE !== null
? parseFloat(TRIM_OVERRIDE)
- : animationStartSec + 0.05;
+ : animationStartSec + (hasReady ? 0.05 : 0.5);
console.log(`▸ ffmpeg: trim=${resolvedTrim.toFixed(2)}s${TRIM_OVERRIDE !== null ? ' (manual)' : ' (auto)'}, encode H.264…`);
const ffmpeg = spawnSync('ffmpeg', [