Files
FreeCADWasmDev/web/tools/manual/build-manual.mjs

140 lines
8.0 KiB
JavaScript

#!/usr/bin/env node
// Builds the single-page Chinese manual from web/manual/content/*.md plus the
// feature matrix, and copies screenshots to web/teaching/manual-assets/.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { marked } from "marked";
const here = path.dirname(fileURLToPath(import.meta.url));
const webRoot = path.resolve(here, "../..");
const contentDir = path.join(webRoot, "manual", "content");
const assetsDir = path.join(webRoot, "manual", "assets");
const outFile = path.join(webRoot, "teaching", "manual.html");
const outAssets = path.join(webRoot, "teaching", "manual-assets");
const featuresPath = path.join(webRoot, "manual", "data", "manual-features.json");
const features = JSON.parse(fs.readFileSync(featuresPath, "utf8"));
const chapterTitle = new Map(features.chapters.map(chapter => [chapter.id, chapter.title]));
const esc = value => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;")
.replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const parseFrontMatter = text => {
const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text);
if (!match) return { meta: {}, body: text };
const meta = {};
for (const line of match[1].split("\n")) {
const [key, ...rest] = line.split(":");
if (key) meta[key.trim()] = rest.join(":").trim();
}
return { meta, body: match[2] };
};
const slug = text => String(text).toLowerCase().trim()
.replace(/[`*_]/g, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 60);
const chapters = fs.readdirSync(contentDir).filter(name => name.endsWith(".md")).map(name => {
const text = fs.readFileSync(path.join(contentDir, name), "utf8");
const { meta, body } = parseFrontMatter(text);
return { file: name, meta, body, id: meta.id ?? name.replace(/\.md$/, ""), order: Number(meta.order ?? 999) };
}).sort((a, b) => a.order - b.order);
const sidebar = [];
const searchIndex = [];
const sections = [];
for (const chapter of chapters) {
const html = marked.parse(chapter.body);
const withIds = html.replace(/<h([12])>([\s\S]*?)<\/h\1>/g, (whole, level, inner) => {
const text = inner.replace(/<[^>]+>/g, "").trim();
const id = Number(level) === 1 ? chapter.id : `${chapter.id}-${slug(text)}`;
return `<h${level} id="${esc(id)}">${inner}</h${level}>`;
}).replace(/<img([^>]*?)>/g, (whole, attrs) => /loading=/.test(attrs) ? whole : `<img loading="lazy"${attrs}>`)
.replace(/<table>/g, '<div class="table-scroll"><table>')
.replace(/<\/table>/g, '</table></div>');
sections.push({ ...chapter, html: withIds });
const h2s = [...chapter.body.matchAll(/^## (.+)$/gm)].map(match => {
const title = match[1].replace(/[`*_]/g, "").trim();
return { id: `${chapter.id}-${slug(title)}`, title };
});
sidebar.push({ id: chapter.id, title: chapter.meta.title ?? chapter.id, sections: h2s,
done: chapter.meta.level !== "appendix" });
const parts = chapter.body.split(/^## /m);
const chapterMeta = { title: chapter.meta.title ?? chapter.id, chapter: chapter.meta.title ?? chapter.id };
if (parts[0]) searchIndex.push({ id: chapter.id, title: chapterMeta.title, chapter: chapterMeta.chapter,
text: parts[0].replace(/[#>*`|\-]/g, " ").replace(/\s+/g, " ").slice(0, 400), commands: [] });
for (const part of parts.slice(1)) {
const [titleLine, ...rest] = part.split("\n");
const title = titleLine.replace(/[`*_]/g, "").trim();
searchIndex.push({ id: `${chapter.id}-${slug(title)}`, title, chapter: chapterMeta.title,
text: rest.join(" ").replace(/[#>*`|\-]/g, " ").replace(/\s+/g, " ").slice(0, 400), commands: [] });
}
}
const sidebarHtml = `<ol>${sidebar.map(chapter => `<li>
<div class="chapter"><input type="checkbox" data-progress="${esc(chapter.id)}" aria-label="完成 ${esc(chapter.title)}" /><a href="#${esc(chapter.id)}">${esc(chapter.title)}</a></div>
${chapter.sections.map(section => `<a class="sec" href="#${esc(section.id)}">${esc(section.title)}</a>`).join("")}
</li>`).join("")}<li><a href="#ch15">附录:命令索引</a></li></ol>`;
const statusLabel = { detailed: "精讲", overview: "覆盖", boundary: "边界", verified: "已验证", "fix-needed": "待修" };
const moduleOptions = [...new Set(features.commands.map(item => item.module))].sort()
.map(module => `<option value="${esc(module)}">${esc(module)}</option>`).join("");
const indexRows = features.commands.map(item => {
const anchor = `cmd-${slug(item.module)}-${slug(item.command)}`;
return `<tr id="${esc(anchor)}" data-module="${esc(item.module)}" data-status="${esc(item.status)}">
<td>${esc(item.module)}</td><td><code>${esc(item.command)}</code></td><td>${esc(item.kind)}</td>
<td><span class="badge ${esc(item.status)}">${esc(statusLabel[item.status] ?? item.status)}</span></td>
<td>${esc(chapterTitle.get(item.chapterId) ?? item.chapterId ?? "-")}</td><td>${esc(item.ledgerCaseId ?? "-")}</td></tr>`;
}).join("");
const searchCommands = features.commands.map(item => ({
id: `cmd-${slug(item.module)}-${slug(item.command)}`,
title: `${item.module} · ${item.command}`,
chapter: chapterTitle.get(item.chapterId) ?? "附录",
text: `${item.disposition} ${item.kind} ${statusLabel[item.status] ?? item.status}`,
commands: [item.command, item.module],
}));
searchIndex.push(...searchCommands);
const commandIndex = `<section id="command-index-section"><h1 id="ch15">附录:命令索引</h1>
<p>共 ${features.commands.length} 条命令记录,其中 ${features.stats.nativeHandlers} 条 native handler。
状态含义:精讲 = 有分步教程;覆盖 = 有工作流/命令说明;边界 = 当前 Web 端受限并注明原因。</p>
<div class="index-controls">
<select id="filter-module" aria-label="按模块筛选"><option value="">全部模块</option>${moduleOptions}</select>
<select id="filter-status" aria-label="按状态筛选"><option value="">全部状态</option><option value="detailed">精讲</option><option value="overview">覆盖</option><option value="boundary">边界</option></select>
<input id="filter-command" type="search" placeholder="筛选命令…" aria-label="筛选命令" />
</div>
<div class="table-scroll"><table id="command-index"><thead><tr><th>模块</th><th>命令</th><th>类型</th><th>状态</th><th>章节</th><th>案例</th></tr></thead><tbody>${indexRows}</tbody></table></div></section>`;
let content = sections.map(chapter => chapter.html).join("\n");
const pager = chapters.map((chapter, index) => {
const prev = chapters[index - 1]; const next = chapters[index + 1];
return `${prev ? `<a href="#${esc(prev.id)}">← ${esc(prev.meta.title ?? prev.id)}</a>` : "<span></span>"}
${next ? `<a href="#${esc(next.id)}">${esc(next.meta.title ?? next.id)} →</a>` : "<span></span>"}`;
}).join("\n");
content = content.replace(/<h1 id="ch15">/, `<div class="pager">${pager}</div><h1 id="ch15">`);
// Validate referenced screenshots before writing.
const missing = [];
for (const chapter of chapters) {
for (const match of chapter.body.matchAll(/!\[[^\]]*\]\(([^)]+)\)/g)) {
const src = match[1];
if (!src.startsWith("./manual-assets/")) continue;
const file = path.join(assetsDir, src.replace("./manual-assets/", ""));
if (!fs.existsSync(file)) missing.push(src);
}
}
if (missing.length) throw new Error(`missing screenshots: ${missing.slice(0, 5).join(", ")}`);
fs.mkdirSync(outAssets, { recursive: true });
fs.cpSync(assetsDir, outAssets, { recursive: true });
const template = fs.readFileSync(path.join(here, "template.html"), "utf8");
const html = template
.replaceAll("{{TITLE}}", "Web FreeCAD 全功能初学者图文教案")
.replace("{{SIDEBAR}}", sidebarHtml)
.replace("{{CONTENT}}", content)
.replace("{{COMMAND_INDEX}}", commandIndex)
.replace("{{SEARCH_INDEX}}", JSON.stringify(searchIndex).replace(/</g, "\\u003c"))
.replace("{{COMMAND_COUNT}}", String(features.commands.length));
fs.writeFileSync(outFile, html);
console.log(JSON.stringify({ ok: true, outFile, chapters: chapters.length, sections: sections.length,
commands: features.commands.length, searchEntries: searchIndex.length, bytes: fs.statSync(outFile).size }));