Add Web FreeCAD manual matrix, capture harness and chapter 1 pilot

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
2026-11-13 11:13:29 +08:00
parent a10493723b
commit bc40c77153
31 changed files with 36201 additions and 0 deletions

View File

@@ -0,0 +1,137 @@
#!/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}>`);
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("")}</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 }));

View File

@@ -0,0 +1,177 @@
#!/usr/bin/env node
// Runs a manual scenario in the real app, asserts UI state and captures
// full-page / element screenshots. Usage:
// node capture.mjs --scenario ../../manual/scenarios/ch01-ui.json [--headed]
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { listOpfsFiles, readOpfsFile } from "../carrier-course/lib/opfs.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const webRoot = path.resolve(here, "../..");
const require = createRequire(path.join(webRoot, "package.json"));
const { chromium } = require("playwright");
const args = process.argv.slice(2);
const option = (name, fallback = "") => {
const index = args.indexOf(name);
return index < 0 ? fallback : args[index + 1] ?? fallback;
};
const scenarioPath = path.resolve(option("--scenario"));
if (!fs.existsSync(scenarioPath)) throw new Error(`missing scenario ${scenarioPath}`);
const scenario = JSON.parse(fs.readFileSync(scenarioPath, "utf8"));
const origin = option("--origin", "http://127.0.0.1:5181");
const headed = args.includes("--headed");
const chapter = scenario.chapter;
const workflow = scenario.workflow;
const shotDir = path.join(webRoot, "manual", "assets", chapter, workflow);
const reportDir = path.join(webRoot, "manual", "data", "capture");
fs.mkdirSync(shotDir, { recursive: true });
fs.mkdirSync(reportDir, { recursive: true });
const sha256 = file => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
async function runOnce() {
const browser = await chromium.launch({
executablePath: "/usr/bin/google-chrome",
headless: !headed,
args: ["--no-sandbox", "--disable-dev-shm-usage", "--enable-unsafe-swiftshader",
"--use-gl=angle", "--use-angle=swiftshader", "--window-size=1600,900"],
});
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
const pageErrors = [];
const consoleErrors = [];
page.on("pageerror", error => pageErrors.push(String(error)));
page.on("console", message => { if (message.type() === "error") consoleErrors.push(message.text().slice(0, 300)); });
const trace = [];
const shots = [];
const record = entry => trace.push({ at: new Date().toISOString(), ...entry });
const click = async action => {
let locator;
if (action.role) locator = page.getByRole(action.role, { name: action.name, exact: action.exact });
else {
locator = page.locator(action.selector);
if (action.hasText) locator = locator.filter({ hasText: action.hasText });
if (action.target) locator = locator.locator(action.target);
}
if (action.nth !== undefined) locator = locator.nth(action.nth);
else if (!action.all) locator = locator.first();
if (action.all) {
const count = await locator.count();
for (let index = 0; index < count; index++) await locator.nth(index).click();
} else await locator.click({ timeout: action.timeout ?? 30000 });
};
const shot = async action => {
const file = path.join(shotDir, `${action.name}.png`);
if (action.selector) {
const target = page.locator(action.selector).first();
await target.waitFor({ state: "visible", timeout: 30000 });
await target.screenshot({ path: file });
} else {
await page.screenshot({ path: file, fullPage: Boolean(action.fullPage) });
}
const stat = fs.statSync(file);
if (stat.size < 5 * 1024) throw new Error(`screenshot too small: ${file}`);
shots.push({ id: `${chapter}/${workflow}/${action.name}`, file: path.relative(webRoot, file),
bytes: stat.size, sha256: sha256(file), fullPage: Boolean(action.fullPage), selector: action.selector ?? null });
record({ action: "shot", name: action.name, bytes: stat.size });
};
const save = async action => {
await page.evaluate(() => { const details = document.querySelector(".file-tools"); if (details) details.open = true; });
await page.waitForTimeout(400);
const before = await listOpfsFiles(page);
await page.locator('button:has-text("保存 FCStd 到 OPFS")').first().click();
let after = before; let status = "";
for (let attempt = 0; attempt < 40; attempt++) {
await page.waitForTimeout(750);
after = await listOpfsFiles(page);
status = await page.locator("p.status").first().textContent().catch(() => "");
if (after.some(name => !before.includes(name) && /\.FCStd$/i.test(name)) || /Saved\s+\S+\.FCStd\s+to OPFS/i.test(status ?? "")) break;
}
const match = /Saved\s+(\S+\.FCStd)\s+to OPFS/i.exec(status ?? "");
const name = match?.[1] ?? after.find(item => !before.includes(item) && /\.FCStd$/i.test(item));
if (!name) throw new Error(`save produced no FCStd; status=${status}`);
const bytes = (await readOpfsFile(page, name)).bytes;
const fixture = path.join(webRoot, "manual", "fixtures", `${chapter}-${workflow}.FCStd`);
fs.mkdirSync(path.dirname(fixture), { recursive: true });
fs.writeFileSync(fixture, Buffer.from(bytes));
record({ action: "save", name, bytes: bytes.length, status });
};
try {
for (const action of scenario.actions) {
switch (action.type) {
case "goto":
await page.goto(`${origin}${action.url}`, { waitUntil: "domcontentloaded", timeout: 120000 });
record({ action: "goto", url: action.url });
break;
case "waitFor":
if (action.selector) await page.waitForSelector(action.selector, { timeout: action.timeout ?? 120000 });
if (action.text) await page.getByText(action.text, { exact: action.exact ?? false }).first()
.waitFor({ state: "visible", timeout: action.timeout ?? 120000 });
record({ action: "waitFor", selector: action.selector ?? null, text: action.text ?? null });
break;
case "click": await click(action); record({ action: "click", selector: action.selector ?? action.name }); break;
case "fill":
await page.locator(action.selector).first().fill(String(action.value));
record({ action: "fill", selector: action.selector, value: action.value });
break;
case "select":
await page.locator(action.selector).first().selectOption(action.label ? { label: action.label } : action.value);
record({ action: "select", selector: action.selector, label: action.label ?? action.value });
break;
case "press": await page.keyboard.press(action.key); record({ action: "press", key: action.key }); break;
case "drag": {
const box = await page.locator(action.selector).first().boundingBox();
if (!box) throw new Error(`drag target missing: ${action.selector}`);
const x = box.x + box.width / 2; const y = box.y + box.height / 2;
await page.mouse.move(x, y); await page.mouse.down();
await page.mouse.move(x + (action.dx ?? 0), y + (action.dy ?? 0), { steps: 18 });
await page.mouse.up(); await page.waitForTimeout(400);
record({ action: "drag", selector: action.selector, dx: action.dx, dy: action.dy });
break;
}
case "eval":
await page.evaluate(action.script);
record({ action: "eval" });
break;
case "shot": await shot(action); break;
case "save": await save(action); break;
case "assertText": {
const text = await page.locator(action.selector).first().textContent();
if (!String(text ?? "").includes(action.contains)) throw new Error(`assertText failed: ${action.selector} ${text}`);
record({ action: "assertText", selector: action.selector, contains: action.contains });
break;
}
case "assertVisible":
await page.locator(action.selector).first().waitFor({ state: "visible", timeout: 30000 });
record({ action: "assertVisible", selector: action.selector });
break;
case "wait": await page.waitForTimeout(action.ms ?? 500); break;
default: throw new Error(`unknown action ${action.type}`);
}
}
if (pageErrors.length || consoleErrors.length)
throw new Error(`page errors: ${JSON.stringify({ pageErrors, consoleErrors })}`);
const report = {
schema: "freecad-web-manual/capture/v1", generatedAt: new Date().toISOString(),
chapter, workflow, scenario: path.relative(webRoot, scenarioPath), origin,
ok: true, trace, shots, pageErrors, consoleErrors,
};
fs.writeFileSync(path.join(reportDir, `${chapter}-${workflow}.json`), `${JSON.stringify(report, null, 2)}\n`);
return report;
} finally {
await browser.close();
}
}
try {
const report = await runOnce();
console.log(JSON.stringify({ ok: true, chapter, workflow, shots: report.shots.length }));
} catch (error) {
console.error(JSON.stringify({ ok: false, error: String(error?.stack ?? error) }));
process.exitCode = 1;
}

View File

@@ -0,0 +1,50 @@
#!/usr/bin/env node
// Checks the generated manual on desktop and mobile, including images, search
// and the command index. Writes manual/data/page-check.json.
import fs from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const webRoot = path.resolve(here, "../..");
const require = createRequire(path.join(webRoot, "package.json"));
const { chromium } = require("playwright");
const url = process.env.MANUAL_URL || "http://127.0.0.1:5190/manual.html";
const browser = await chromium.launch({ executablePath: "/usr/bin/google-chrome", headless: true,
args: ["--no-sandbox", "--enable-unsafe-swiftshader", "--use-gl=angle", "--use-angle=swiftshader"] });
const report = { schema: "freecad-web-manual/page-check/v1", generatedAt: new Date().toISOString(), url, viewports: [] };
for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) {
const page = await browser.newPage({ viewport });
const errors = []; const failed = [];
page.on("pageerror", error => errors.push(String(error)));
page.on("console", message => { if (message.type() === "error") errors.push(message.text().slice(0, 200)); });
page.on("response", response => { if (response.status() >= 400) failed.push(`${response.status()} ${response.url()}`); });
const response = await page.goto(url, { waitUntil: "load", timeout: 120000 });
await page.waitForTimeout(800);
const metrics = await page.evaluate(() => {
const images = [...document.images];
return {
chapters: document.querySelectorAll('nav.sidebar .chapter').length,
sections: document.querySelectorAll('main h2[id]').length,
images: images.length,
brokenImages: images.filter(image => image.src && (!image.complete || image.naturalWidth === 0)).map(image => image.src),
commandRows: document.querySelectorAll('#command-index tbody tr').length,
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
searchSize: SEARCH_INDEX.length,
};
});
await page.locator('#search').fill('Part_Box');
await page.waitForTimeout(300);
const searchHits = await page.locator('#search-results a').count();
if (viewport.width === 1440) await page.screenshot({ path: path.join(webRoot, "teaching", "manual.png"), fullPage: false });
report.viewports.push({ viewport, status: response?.status(), errors, failed, searchHits, ...metrics });
await page.close();
}
await browser.close();
report.ok = report.viewports.every(item => item.status === 200 && item.errors.length === 0
&& item.failed.length === 0 && item.brokenImages.length === 0 && item.overflow === 0
&& item.commandRows > 1500 && item.searchHits > 0);
fs.writeFileSync(path.join(webRoot, "manual", "data", "page-check.json"), `${JSON.stringify(report, null, 2)}\n`);
console.log(JSON.stringify(report));
process.exitCode = report.ok ? 0 : 1;

View File

@@ -0,0 +1,195 @@
#!/usr/bin/env node
// Builds the authoritative manual feature matrix from the command matrix,
// desktop routes, registry, UI catalogs and the official case ledger.
// Fails when a module has no chapter or a native handler is unmapped.
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const webRoot = path.resolve(here, "../..");
const outDir = path.join(webRoot, "manual", "data");
fs.mkdirSync(outDir, { recursive: true });
const readJson = file => JSON.parse(fs.readFileSync(file, "utf8"));
const sha256 = file => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
const matrixPath = path.join(webRoot, "public/api/workbench-command-matrix.json");
const routesPath = path.join(webRoot, "public/api/desktop-command-routes.json");
const registryPath = path.join(webRoot, "src/module-registry.generated.ts");
const featuresPath = path.join(webRoot, "teaching/data/features.json");
const casesPath = path.join(webRoot, "teaching/data/cases.json");
const ledgerPath = path.join(webRoot, "docs/current/freecad-official-case-ledger.json");
const matrix = readJson(matrixPath);
const routes = readJson(routesPath);
const features = readJson(featuresPath);
const cases = readJson(casesPath);
const ledger = readJson(ledgerPath);
const chapters = [
{ id: "ch00", order: 0, level: "core", title: "导读、启动与 OPFS", moduleIds: ["Start", "Web", "Help"] },
{ id: "ch01", order: 1, level: "core", title: "界面、文档与视图", moduleIds: [] },
{ id: "ch02", order: 2, level: "core", title: "Part 图元与布尔", moduleIds: ["Part"] },
{ id: "ch03", order: 3, level: "core", title: "Sketcher 草图", moduleIds: ["Sketcher"] },
{ id: "ch04", order: 4, level: "core", title: "PartDesign 实体建模", moduleIds: ["PartDesign"] },
{ id: "ch05", order: 5, level: "core", title: "Assembly 装配", moduleIds: ["Assembly"] },
{ id: "ch06", order: 6, level: "core", title: "测量、检查、材质与表格", moduleIds: ["Measure", "Inspection", "Material", "Spreadsheet"] },
{ id: "ch07", order: 7, level: "core", title: "导入导出与 OPFS", moduleIds: ["Import"] },
{ id: "ch08", order: 8, level: "specialist", title: "网格、点、逆向与曲面", moduleIds: ["Mesh", "MeshPart", "Points", "ReverseEngineering", "Surface"] },
{ id: "ch09", order: 9, level: "specialist", title: "BIM 建筑信息模型", moduleIds: ["BIM"] },
{ id: "ch10", order: 10, level: "specialist", title: "CAM 加工", moduleIds: ["CAM"] },
{ id: "ch11", order: 11, level: "specialist", title: "TechDraw 工程图", moduleIds: ["TechDraw"] },
{ id: "ch12", order: 12, level: "specialist", title: "FEM 有限元", moduleIds: ["Fem"] },
{ id: "ch13", order: 13, level: "specialist", title: "Draft、Plot、OpenSCAD 等", moduleIds: ["Draft", "Plot", "OpenSCAD", "Robot", "Cloud", "JtReader", "Sandbox", "Test", "Tux", "TemplatePyMod", "Show"] },
{ id: "ch14", order: 14, level: "case", title: "综合案例:27 件 GLB 产线", moduleIds: [] },
{ id: "ch15", order: 15, level: "appendix", title: "附录:命令索引与缺口", moduleIds: [] },
];
const moduleChapter = new Map();
for (const chapter of chapters) for (const moduleId of chapter.moduleIds) moduleChapter.set(moduleId, chapter.id);
const moduleOfChapter = id => chapters.find(chapter => chapter.id === id);
const boundaries = [
{ id: "b-techdraw-worker", module: "TechDraw", match: ["TechDraw_PageDefault"],
title: "TechDraw 跨 Worker 文档桥", detail: "页面 Worker 未持有目标文档,TechDraw_PageDefault 报 Document does not exist;SVG 回退不是 TechDraw 输出。",
desktopRefs: ["freecad-source/src/Mod/TechDraw/App/DrawPage.cpp", "freecad-source/src/Mod/TechDraw/App/DrawViewPart.cpp"] },
{ id: "b-fem-native", module: "Fem", match: ["FEM_ResultShow", "PostPipelineFromResult"],
title: "FEM 原生结果对象", detail: "FemMeshObject/FemResultObject 未随包发布,结果停留在 Worker;VTK 显示为 three.js 近似。",
desktopRefs: ["freecad-source/src/Mod/Fem/App/FemMeshObject.cpp", "web/docs/current/web-freecad-gaps-fem.md"] },
{ id: "b-cam-opencamlib", module: "CAM", match: ["CAM_Adaptive", "CAM_Surface", "CAM_Waterline"],
title: "CAM OpenCAMLib 路径", detail: "Adaptive/Surface/Waterline 依赖 OpenCAMLib 与完整 ToolBit/G-code 栈,WASM 包未提供。",
desktopRefs: ["freecad-source/src/Mod/CAM/App/AppPath.cpp", "web/docs/current/cam-teaching-gap.md"] },
{ id: "b-gltf-native", module: "Import", match: ["Import_Gltf"],
title: "glTF 原生导入/导出", detail: "OCCT WASM 构建 USE_RAPIDJSON=OFF,RWGltf 无法读写;当前仅 three.js 查看。",
desktopRefs: ["freecad-source/src/Mod/Import/App/ReaderGltf.cpp", "freecad-source/src/Mod/Import/App/WriterGltf.cpp"] },
{ id: "b-cloud-remote", module: "Cloud", match: [],
title: "Cloud 远程存储", detail: "Save/Restore 需要远程 S3 凭据与服务;本地 OPFS 不受影响。",
desktopRefs: ["web/src/cloud.worker.ts"] },
];
const boundaryByKey = new Map();
for (const boundary of boundaries) for (const command of boundary.match) boundaryByKey.set(`${boundary.module}:${command}`, boundary);
// User-facing command catalogs (regex extraction is deliberate: these files are
// the UI source of truth and are validated by capture later).
const uiCommands = new Set();
for (const relative of ["src/part-workbench-ui.tsx", "src/partdesign-desktop-adapter.ts", "src/sketcher-desktop-adapter.ts"]) {
const text = fs.readFileSync(path.join(webRoot, relative), "utf8");
for (const match of text.matchAll(/\b(?:Part|PartDesign|Sketcher)_[A-Za-z0-9_]+/g)) uiCommands.add(match[0]);
}
// Passed cases keyed by desktop command for status hints (capture still decides verified).
const caseByCommand = new Map();
for (const item of cases.cases ?? []) {
if (!item.command) continue;
if (!(item.checks ?? []).find(check => check.flag === "acceptancePassed")?.passed) continue;
caseByCommand.set(item.command, item.caseId);
}
const commands = [];
const moduleSeen = new Set();
for (const record of matrix.records ?? []) {
const chapterId = moduleChapter.get(record.module) ?? null;
moduleSeen.add(record.module);
const boundary = boundaryByKey.get(`${record.module}:${record.command}`) ?? null;
const ui = uiCommands.has(record.command);
const native = record.disposition === "native_handler";
const level = chapterId ? moduleOfChapter(chapterId)?.level : null;
let status = "overview";
if (boundary) status = "boundary";
else if (level === "core" && (native || ui)) status = "detailed";
else if (level === "specialist" && (native || ui)) status = "overview";
commands.push({
key: record.id ?? `${record.module}:desktop:${record.command}`,
module: record.module,
command: record.command,
kind: record.kind ?? "desktop",
disposition: record.disposition ?? "unknown",
route: record.route ?? null,
chapterId,
workflowId: null,
status,
uiSurface: ui,
ledgerCaseId: caseByCommand.get(record.command) ?? null,
boundaryId: boundary?.id ?? null,
screenshotId: null,
sourcePath: record.sourcePath ?? null,
sourceLine: record.sourceLine ?? null,
desktopRef: record.sourcePath ? `${record.sourcePath}:${record.sourceLine ?? ""}` : null,
});
}
// Registry-only routes that do not appear in the desktop matrix still belong in
// the appendix (e.g. assembly.createRecompute).
const matrixKeys = new Set(commands.map(item => `${item.module}:${item.command}`));
for (const module of features.modules ?? []) {
const chapterId = moduleChapter.get(module.module) ?? null;
if (!chapterId) throw new Error(`registry module has no chapter: ${module.module}`);
for (const command of module.commands ?? []) {
if (matrixKeys.has(`${module.module}:${command}`)) continue;
matrixKeys.add(`${module.module}:${command}`);
commands.push({
key: `${module.module}:web:${command}`, module: module.module, command,
kind: "web-route", disposition: "registered", route: null,
chapterId, workflowId: null, status: "overview", uiSurface: false,
ledgerCaseId: null, boundaryId: null, screenshotId: null,
sourcePath: null, sourceLine: null, desktopRef: null,
});
}
}
const unknownModules = [...moduleSeen].filter(module => !moduleChapter.has(module));
if (unknownModules.length) throw new Error(`modules without chapter: ${unknownModules.join(", ")}`);
const nativeUnmapped = commands.filter(item => item.disposition === "native_handler" && !item.chapterId);
if (nativeUnmapped.length) throw new Error(`native handlers without chapter: ${nativeUnmapped.length}`);
const stats = {
modules: moduleSeen.size,
commands: commands.length,
desktopRecords: matrix.records?.length ?? 0,
routes: routes.records?.length ?? 0,
registryCommands: (features.modules ?? []).reduce((sum, module) => sum + (module.commands?.length ?? 0), 0),
nativeHandlers: commands.filter(item => item.disposition === "native_handler").length,
detailed: commands.filter(item => item.status === "detailed").length,
overview: commands.filter(item => item.status === "overview").length,
boundary: commands.filter(item => item.status === "boundary").length,
verifiedCandidates: commands.filter(item => item.ledgerCaseId).length,
screenshots: 0,
workflows: 0,
};
const coverage = {
schema: "freecad-web-manual/coverage/v1",
generatedAt: new Date().toISOString(),
modules: moduleSeen.size,
unknownModules,
nativeHandlers: stats.nativeHandlers,
nativeMapped: stats.nativeHandlers,
desktopRecords: stats.desktopRecords,
registryCommands: stats.registryCommands,
routes: stats.routes,
byChapter: Object.fromEntries(chapters.map(chapter => [chapter.id,
commands.filter(item => item.chapterId === chapter.id).length])),
byStatus: Object.fromEntries(["detailed", "overview", "boundary"].map(status =>
[status, commands.filter(item => item.status === status).length])),
ok: unknownModules.length === 0 && stats.nativeHandlers === stats.nativeHandlers,
};
const sources = [matrixPath, routesPath, registryPath, featuresPath, casesPath, ledgerPath]
.map(file => ({ path: path.relative(webRoot, file), sha256: sha256(file) }));
const output = {
schema: "freecad-web-manual/features/v1",
generatedAt: new Date().toISOString(),
sources,
stats,
chapters,
workflows: [],
commands,
screenshots: [],
boundaries,
};
fs.writeFileSync(path.join(outDir, "manual-features.json"), `${JSON.stringify(output, null, 2)}\n`);
fs.writeFileSync(path.join(outDir, "inventory-snapshot.json"), `${JSON.stringify({
schema: "freecad-web-manual/inventory/v1", generatedAt: output.generatedAt, sources,
}, null, 2)}\n`);
fs.writeFileSync(path.join(outDir, "coverage-audit.json"), `${JSON.stringify(coverage, null, 2)}\n`);
console.log(JSON.stringify({ ok: true, stats, coverage: coverage.byChapter }));

View File

@@ -0,0 +1,177 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="data:," />
<title>{{TITLE}}</title>
<style>
:root { color-scheme: dark; --bg:#0f1419; --panel:#17212b; --line:#2a3a45; --text:#dbe6ee; --muted:#93a6b3; --accent:#73c6d4; --warn:#e0b15c; --ok:#7fc98b; }
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body { margin:0; background:var(--bg); color:var(--text); font:15px/1.7 system-ui,"Noto Sans SC",sans-serif; }
a { color:var(--accent); text-decoration:none; }
header.top { position:sticky; top:0; z-index:30; display:flex; align-items:center; gap:12px; padding:10px 18px; background:#0b1116f2; border-bottom:1px solid var(--line); backdrop-filter:blur(6px); }
header.top h1 { margin:0; font-size:17px; flex:0 0 auto; }
#search { margin-left:auto; width:min(420px,42vw); background:#0b1014; color:var(--text); border:1px solid #3f3f3f; border-radius:6px; padding:6px 10px; }
#search-results { position:fixed; top:52px; right:18px; width:min(520px,90vw); max-height:60vh; overflow:auto; background:#0d1318; border:1px solid var(--line); border-radius:8px; box-shadow:0 12px 32px #0008; z-index:40; display:none; }
#search-results a { display:block; padding:8px 12px; border-bottom:1px solid #1d2a33; color:var(--text); }
#search-results a small { display:block; color:var(--muted); }
#menu-toggle { display:none; background:transparent; color:var(--text); border:1px solid #3f3f3f; border-radius:4px; padding:4px 8px; }
.layout { display:grid; grid-template-columns:290px minmax(0,1fr); gap:0; max-width:1500px; margin:0 auto; }
nav.sidebar { position:sticky; top:53px; height:calc(100vh - 53px); overflow:auto; border-right:1px solid var(--line); padding:14px 12px 40px; }
nav.sidebar .progress { height:8px; background:var(--panel); border-radius:4px; overflow:hidden; margin:6px 0 12px; }
nav.sidebar .progress span { display:block; height:100%; width:0; background:var(--accent); }
nav.sidebar ol { list-style:none; margin:0; padding:0; }
nav.sidebar li { margin:2px 0; }
nav.sidebar a { display:block; padding:4px 6px; border-radius:4px; color:var(--text); font-size:13.5px; }
nav.sidebar a:hover, nav.sidebar a.active { background:#22313b; color:var(--accent); }
nav.sidebar .chapter { display:flex; align-items:center; gap:6px; margin-top:8px; }
nav.sidebar .chapter input { accent-color:var(--accent); }
nav.sidebar .sec { padding-left:16px; color:var(--muted); font-size:12.5px; }
main { padding:24px 30px 80px; min-width:0; }
main h1 { font-size:26px; margin:0 0 14px; }
main h2 { font-size:20px; margin:36px 0 12px; padding-top:8px; border-top:1px solid var(--line); color:var(--accent); }
main h3 { font-size:16px; margin:24px 0 8px; }
main p, main li { max-width:900px; }
main img { display:block; max-width:100%; height:auto; border:1px solid var(--line); border-radius:8px; background:#0d1318; margin:12px 0; cursor:zoom-in; }
main figure { margin:16px 0; }
main figcaption { color:var(--muted); font-size:12.5px; }
.table-scroll { max-width:100%; overflow-x:auto; }
table { width:100%; border-collapse:collapse; font-size:13px; margin:12px 0; }
th, td { border-bottom:1px solid var(--line); padding:5px 7px; text-align:left; vertical-align:top; }
th { color:var(--accent); }
code, pre { background:#0b1014; border:1px solid #22303a; border-radius:5px; }
code { padding:1px 4px; font-size:12.5px; }
pre { padding:10px; overflow:auto; }
blockquote { border-left:3px solid var(--warn); margin:12px 0; padding:4px 12px; color:var(--warn); background:#1d1a1210; }
.cmd { font-family:ui-monospace,monospace; font-size:12px; color:#9fd6de; }
.badge { display:inline-block; border-radius:4px; padding:0 6px; font-size:11px; border:1px solid var(--line); }
.badge.detailed { color:var(--ok); } .badge.overview { color:var(--accent); } .badge.boundary { color:var(--warn); }
.index-controls { display:flex; gap:8px; flex-wrap:wrap; margin:12px 0; }
.index-controls select, .index-controls input { background:#0b1014; color:var(--text); border:1px solid #3f3f3f; border-radius:4px; padding:5px 8px; }
#command-index td { font-size:12px; } #command-index tr.hidden { display:none; }
.pager { display:flex; justify-content:space-between; gap:12px; margin-top:40px; padding-top:14px; border-top:1px solid var(--line); }
#lightbox { position:fixed; inset:0; background:#000d; z-index:60; display:none; align-items:center; justify-content:center; padding:24px; }
#lightbox img { max-width:96vw; max-height:92vh; border-radius:6px; }
#lightbox.open { display:flex; }
@media (max-width:900px) {
.layout { grid-template-columns:1fr; }
nav.sidebar { position:fixed; z-index:35; top:53px; left:0; width:280px; background:#0d1318; transform:translateX(-100%); transition:transform .2s; }
nav.sidebar.open { transform:translateX(0); }
#menu-toggle { display:inline-block; }
main { padding:18px 14px 60px; }
header.top { gap:8px; padding:8px 10px; }
header.top h1 { font-size:14px; max-width:34vw; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
#search { width:auto; flex:1; min-width:0; margin-left:6px; }
}
@media print { header.top, nav.sidebar, #lightbox, .pager { display:none; } .layout { display:block; } main { padding:0; } main img { break-inside:avoid; } }
</style>
</head>
<body>
<header class="top">
<button id="menu-toggle" aria-label="Toggle navigation">☰</button>
<h1>{{TITLE}}</h1>
<input id="search" type="search" placeholder="搜索章节、命令、参数…(/ 聚焦)" aria-label="搜索教案" />
</header>
<div id="search-results" role="listbox" aria-label="搜索结果"></div>
<div class="layout">
<nav class="sidebar" id="sidebar" aria-label="章节目录">
<strong>课程进度</strong>
<div class="progress"><span id="progress-bar"></span></div>
<p id="progress-text" style="color:var(--muted);font-size:12px;margin:0 0 8px"></p>
{{SIDEBAR}}
</nav>
<main id="content">
{{CONTENT}}
{{COMMAND_INDEX}}
<div class="pager" id="pager"></div>
</main>
</div>
<div id="lightbox" role="dialog" aria-label="图片预览"><img alt="" /></div>
<script>
const SEARCH_INDEX = {{SEARCH_INDEX}};
const COMMAND_COUNT = {{COMMAND_COUNT}};
const boxes = [...document.querySelectorAll('input[data-progress]')];
const key = 'web-freecad-manual-progress-v1';
const loadProgress = () => { try { return JSON.parse(localStorage.getItem(key) || '{}'); } catch { return {}; } };
const saveProgress = value => localStorage.setItem(key, JSON.stringify(value));
const renderProgress = () => {
const done = boxes.filter(box => box.checked).length;
document.getElementById('progress-bar').style.width = boxes.length ? (100 * done / boxes.length) + '%' : '0';
document.getElementById('progress-text').textContent = done + ' / ' + boxes.length + ' 章已完成';
};
const state = loadProgress();
for (const box of boxes) {
box.checked = Boolean(state[box.dataset.progress]);
box.addEventListener('change', () => { const value = loadProgress(); value[box.dataset.progress] = box.checked; saveProgress(value); renderProgress(); });
}
renderProgress();
const sidebar = document.getElementById('sidebar');
document.getElementById('menu-toggle').addEventListener('click', () => sidebar.classList.toggle('open'));
for (const link of sidebar.querySelectorAll('a[href^="#"]')) link.addEventListener('click', () => sidebar.classList.remove('open'));
const search = document.getElementById('search');
const results = document.getElementById('search-results');
const normalize = text => String(text || '').toLowerCase().replace(/\s+/g, ' ').trim();
const renderResults = query => {
const q = normalize(query);
results.innerHTML = '';
if (q.length < 1) { results.style.display = 'none'; return; }
const hits = SEARCH_INDEX.filter(item => normalize(item.title + ' ' + item.text + ' ' + (item.commands || []).join(' ')).includes(q)).slice(0, 30);
for (const hit of hits) {
const link = document.createElement('a');
link.href = '#' + hit.id;
link.innerHTML = '<strong>' + hit.title + '</strong><small>' + hit.chapter + ' · ' + hit.text.slice(0, 90).replace(/</g, '&lt;') + '</small>';
results.appendChild(link);
}
if (!hits.length) results.innerHTML = '<p style="padding:10px;color:#93a6b3">没有匹配结果</p>';
results.style.display = 'block';
};
search.addEventListener('input', () => renderResults(search.value));
search.addEventListener('keydown', event => { if (event.key === 'Escape') { results.style.display = 'none'; search.blur(); } });
document.addEventListener('keydown', event => {
if (event.key === '/' && document.activeElement !== search) { event.preventDefault(); search.focus(); }
if (event.key === 'Escape') document.getElementById('lightbox').classList.remove('open');
});
results.addEventListener('click', event => { if (event.target.closest('a')) results.style.display = 'none'; });
const lightbox = document.getElementById('lightbox');
for (const image of document.querySelectorAll('main img')) {
image.addEventListener('click', () => { lightbox.querySelector('img').src = image.src; lightbox.classList.add('open'); });
}
lightbox.addEventListener('click', () => lightbox.classList.remove('open'));
const moduleFilter = document.getElementById('filter-module');
const statusFilter = document.getElementById('filter-status');
const indexSearch = document.getElementById('filter-command');
const rows = [...document.querySelectorAll('#command-index tbody tr')];
const applyFilter = () => {
const module = moduleFilter?.value || '';
const status = statusFilter?.value || '';
const text = normalize(indexSearch?.value || '');
for (const row of rows) {
const ok = (!module || row.dataset.module === module) && (!status || row.dataset.status === status)
&& (!text || normalize(row.textContent).includes(text));
row.classList.toggle('hidden', !ok);
}
};
for (const control of [moduleFilter, statusFilter, indexSearch]) control?.addEventListener('input', applyFilter);
const heads = [...document.querySelectorAll('main h2[id]')];
const links = new Map([...sidebar.querySelectorAll('a[href^="#"]')].map(link => [link.getAttribute('href').slice(1), link]));
const spy = () => {
let current = null;
for (const head of heads) if (head.getBoundingClientRect().top < 120) current = head.id;
for (const [id, link] of links) link.classList.toggle('active', id === current);
};
document.addEventListener('scroll', spy, { passive: true }); spy();
const chapters = [...document.querySelectorAll('main h1[id]')];
const pager = document.getElementById('pager');
if (chapters.length > 1) {
// Multi-chapter pages are not used; the pager stays empty for now.
}
</script>
</body>
</html>