// Vẽ mọi khối mermaid và công thức $$...$$ trong cic.md thành PNG. import fs from "node:fs"; import path from "node:path"; import { execFileSync } from "node:child_process"; import puppeteer from "puppeteer"; import katex from "katex"; const SRC = process.argv[2]; const OUT = path.resolve("assets"); fs.mkdirSync(OUT, { recursive: true }); const md = fs.readFileSync(SRC, "utf8"); // --- mermaid --- const mer = [...md.matchAll(/```mermaid\n([\s\S]*?)```/g)].map((m) => m[1]); const cfg = (wrap) => JSON.stringify({ theme: "default", themeVariables: { fontFamily: "Arial, sans-serif", fontSize: "15px", xyChart: { plotColorPalette: "#3b6fb6, #e07b24" } }, flowchart: { htmlLabels: true, useMaxWidth: false, wrappingWidth: wrap, rankSpacing: 38, nodeSpacing: 30 }, xyChart: { width: 900, height: 480 }, }); fs.writeFileSync("mmd-tb.json", cfg(420)); fs.writeFileSync("mmd-lr.json", cfg(220)); fs.writeFileSync("pptr.json", JSON.stringify({ args: ["--no-sandbox"] })); // Tỉ lệ co khi đặt vào trang A4 (642 x 900 px). const fit = (png) => { const b = fs.readFileSync(png); return Math.min(1, 642 / (b.readUInt32BE(16) / 3), 900 / (b.readUInt32BE(20) / 3)); }; const draw = (code, png, conf) => { const f = png.replace(".png", ".mmd"); fs.writeFileSync(f, code); execFileSync("npx", ["mmdc", "-i", f, "-o", png, "-s", "3", "-b", "white", "-c", conf, "-p", "pptr.json", "-q"], { stdio: "inherit" }); return fit(png); }; mer.forEach((code, i) => { const png = path.join(OUT, `mermaid-${i + 1}.png`); const lr = /^\s*flowchart LR/.test(code); const k = draw(code, png, lr ? "mmd-lr.json" : "mmd-tb.json"); let note = ""; if (lr && k < 0.55) { // Sơ đồ ngang quá rộng cho trang dọc: thử vẽ theo chiều dọc, giữ bản ít phải co hơn. const alt = png.replace(".png", "-tb.png"); const k2 = draw(code.replace(/^(\s*)flowchart LR/, "$1flowchart TB"), alt, "mmd-tb.json"); if (k2 > k) { fs.renameSync(alt, png); note = ` -> TB ${k2.toFixed(2)}`; } } process.stdout.write(`mermaid ${i + 1}/${mer.length} scale ${k.toFixed(2)}${note}\n`); }); // --- công thức hiển thị --- const disp = [...md.matchAll(/^\$\$([\s\S]*?)\$\$\s*$/gm)].map((m) => m[1].trim()); const css = fs.readFileSync("node_modules/katex/dist/katex.min.css", "utf8") .replace(/url\(fonts\//g, `url(file://${path.resolve("node_modules/katex/dist/fonts")}/`); const browser = await puppeteer.launch({ args: ["--no-sandbox"] }); const page = await browser.newPage(); await page.setViewport({ width: 1400, height: 400, deviceScaleFactor: 3 }); for (let i = 0; i < disp.length; i++) { const html = katex.renderToString(disp[i], { displayMode: true, throwOnError: true }); const hf = path.join(OUT, `math-${i + 1}.html`); fs.writeFileSync(hf, `