Files
FreeCADWasmDev/web/tools/manual/build-reducer-manual.mjs
wangdequan facbb196d8 feat(web): panel scroll contract, layout probe and functional suite
- lock the three-column height chain on workbench/PartDesign pages so each
  side panel scrolls independently and the centre stage keeps its size
- dock module task panels above the layout with their own scrollbar instead
  of letting them push the stage out of the viewport
- add tools/layout-probe.mjs (page scroll, aside bounds, pane scrolling,
  stage stability) and CLI mode for tools/static-host.mjs with relative
  --root support
- add the P0-P4 browser functional suite, manual scenarios and capture
  tooling; document it under docs/current/web-functional-suite

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 22:09:42 +08:00

181 lines
11 KiB
JavaScript

#!/usr/bin/env node
// Builds the reducer-specific single-page Chinese manual.
//
// This is deliberately a separate builder rather than a flag on build-manual.mjs:
// the generic manual is the full-app reference (16 chapters, 400+ commands) and
// the reducer manual is a 12-chapter beginner walkthrough of ONE artifact. They
// share the template and the markdown pipeline so the reading experience is
// identical, but neither owns the other's content directory or command index.
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", "reducer", "content");
const assetsDir = path.join(webRoot, "manual", "reducer", "assets");
const outFile = path.join(webRoot, "teaching", "reducer-manual.html");
const outAssets = path.join(webRoot, "teaching", "reducer-manual-assets");
// The reducer manual has no command index of its own: it indexes the case's
// real build steps instead, built from the trace and evidence files.
const caseDir = path.join(webRoot, "teaching", "cases", "secondary-reducer-pro");
const readCase = name => {
const file = path.join(caseDir, name);
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
};
const spec = readCase("reducer-spec.json");
const strength = readCase("out/strength.json");
const assembly = readCase("out/assembly.json");
const parts = readCase("parts/evidence.json");
const gapDoc = path.join(webRoot, "docs", "current", "web-freecad-gaps-secondary-reducer-pro.md");
const gaps = fs.existsSync(gapDoc)
? [...fs.readFileSync(gapDoc, "utf8").matchAll(/^## (GAP-RP-\d+) · (.+)$/gm)].map(m => ({ id: m[1], title: m[2] }))
: [];
const trace = readCase("out/traces/SecondaryReducer.json");
const features = { commands: [], stats: { nativeHandlers: 0 }, chapters: [] };
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],
}));
// Appendix: the build record, the gap log and the acceptance numbers. These
// replace the generic command index -- a beginner following the reducer does
// not need 400 command rows, they need "what did this build actually do".
const traceRows = (trace?.events ?? []).map(event =>
`<tr><td>${event.step}</td><td>${esc(event.label)}</td><td><code>${esc(event.action)}</code></td><td>${event.seconds}</td></tr>`).join("");
const gapRows = gaps.map(gap => `<tr><td><code>${esc(gap.id)}</code></td><td>${esc(gap.title)}</td></tr>`).join("");
const partRows = (parts?.items ?? []).map(item => {
const volume = item.volume?.finalVolume ?? item.volume?.volume ?? "";
return `<tr><td>${esc(item.document)}</td><td>${esc(item.role ?? "-")}</td><td>${item.faceCount ?? "-"}</td>
<td>${typeof volume === "number" ? volume.toFixed(1) : ""}</td><td>${item.seconds}</td>
<td>${item.underSixtySeconds ? "通过" : "超时"}</td></tr>`;
}).join("");
const commandIndex = `<section id="command-index-section"><h1 id="ch15">附录:构建记录、缺口清单与验收数字</h1>
<h2 id="ch15-parts">A. 零件实测(${(parts?.items ?? []).length} 件)</h2>
<div class="table-scroll"><table><thead><tr><th>文档</th><th>角色</th><th>面数</th><th>体积 mm³</th><th>构建 s</th><th>60 s 门槛</th></tr></thead><tbody>${partRows}</tbody></table></div>
<h2 id="ch15-steps">B. 装配构建记录(${(trace?.events ?? []).length} 步)</h2>
<p>每一步都是真实的内核调用,含耗时。教学播放器按这份记录回放。</p>
<div class="table-scroll"><table><thead><tr><th>#</th><th>步骤</th><th>命令</th><th>秒</th></tr></thead><tbody>${traceRows}</tbody></table></div>
<h2 id="ch15-gaps">C. 缺口清单(${gaps.length} 条)</h2>
<p>每条缺口都有桌面源程序依据;修复情况见缺口台账原文。</p>
<div class="table-scroll"><table><thead><tr><th>编号</th><th>标题</th></tr></thead><tbody>${gapRows}</tbody></table></div>
<h2 id="ch15-numbers">D. 验收数字</h2>
<div class="table-scroll"><table><thead><tr><th>项</th><th>值</th></tr></thead><tbody>
<tr><td>传动比</td><td>${spec ? spec.transmission.ratio : "-"}</td></tr>
<tr><td>模数 / 压力角</td><td>${spec ? `${spec.transmission.moduleMm} mm / ${spec.transmission.pressureAngleDeg}°` : "-"}</td></tr>
<tr><td>中心距</td><td>${strength ? strength.stages.map(s => s.centreDistanceMm + " mm").join(" / ") : "-"}</td></tr>
<tr><td>安全系数(接触 / 弯曲)</td><td>${strength ? strength.stages.map(s => `${s.contactSafety.toFixed(2)} / ${s.bendingSafety.toFixed(2)}`).join(" · ") : "-"}</td></tr>
<tr><td>装配组件 / 关节 / BOM 行</td><td>${assembly ? `${assembly.components} / ${assembly.joints.length} / ${assembly.bom.rows}` : "-"}</td></tr>
<tr><td>求解最大位移</td><td>${assembly ? (assembly.displacement.maxMm < 1e-6 ? "< 1e-6 mm" : assembly.displacement.maxMm.toFixed(2) + " mm") : "-"}</td></tr>
<tr><td>页面错误</td><td>${assembly ? (assembly.pageErrors ?? []).length : "-"}</td></tr>
</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 }));