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>
This commit is contained in:
110
web/tools/manual/audit-ui-gaps.mjs
Normal file
110
web/tools/manual/audit-ui-gaps.mjs
Normal file
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env node
|
||||
// Audits the UI surface inventory against the repository and the manual.
|
||||
//
|
||||
// For every surface it verifies:
|
||||
// - the React owner file exists and (when given) the symbol appears in it
|
||||
// - the desktop reference file exists
|
||||
// - the surface is documented in the generated manual chapter ch16
|
||||
// - status is implemented/partial/gap/boundary as recorded, with reasons
|
||||
//
|
||||
// Output: docs/current/ui-design/data/gap-register.json (summary + issues).
|
||||
//
|
||||
// node tools/manual/audit-ui-gaps.mjs
|
||||
// node tools/manual/audit-ui-gaps.mjs --check # exit 1 if any gap
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const inventoryPath = path.join(repoRoot, "tools/fcweb/out/ui-surface-inventory.json");
|
||||
const chapterPath = path.join(webRoot, "manual/content/ch16-panel-index.md");
|
||||
const outPath = path.join(repoRoot, "docs/current/ui-design/data/gap-register.json");
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
|
||||
const fail = message => {
|
||||
console.error(`[audit-ui-gaps] ${message}`);
|
||||
process.exit(2);
|
||||
};
|
||||
if (!fs.existsSync(inventoryPath)) fail(`missing ${inventoryPath}; run ui-surface-inventory.mjs first`);
|
||||
if (!fs.existsSync(chapterPath)) fail(`missing ${chapterPath}; run generate-panel-index.mjs first`);
|
||||
|
||||
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
|
||||
const chapter = fs.readFileSync(chapterPath, "utf8");
|
||||
const categorySection = {
|
||||
"shell-region": "ch16-16-3-壳层区域",
|
||||
statusbar: "ch16-16-4-状态栏",
|
||||
"viewport-tool": "ch16-16-5-视口工具",
|
||||
dock: "ch16-16-6-停靠面板",
|
||||
"task-panel": "ch16-16-7-任务面板",
|
||||
"modal-dialog": "ch16-16-8-模态对话框",
|
||||
"preferences-page": "ch16-16-9-偏好设置页",
|
||||
menu: "ch16-16-10-菜单",
|
||||
toolbar: "ch16-16-11-工具栏",
|
||||
};
|
||||
|
||||
const symbolCache = new Map();
|
||||
const fileContains = (file, symbol) => {
|
||||
if (!symbol) return true;
|
||||
if (!file) return false;
|
||||
const key = file;
|
||||
if (!symbolCache.has(key)) {
|
||||
const full = path.join(repoRoot, file);
|
||||
symbolCache.set(key, fs.existsSync(full) ? fs.readFileSync(full, "utf8") : null);
|
||||
}
|
||||
const text = symbolCache.get(key);
|
||||
return Boolean(text && text.includes(symbol));
|
||||
};
|
||||
|
||||
const issues = [];
|
||||
const perSurface = inventory.surfaces.map(surface => {
|
||||
const problems = [];
|
||||
const ownerFile = surface.owner?.file ? path.join(repoRoot, surface.owner.file) : null;
|
||||
if (!ownerFile || !fs.existsSync(ownerFile)) problems.push("owner-file-missing");
|
||||
else if (!fileContains(surface.owner.file, surface.owner.symbol)) problems.push("owner-symbol-missing");
|
||||
|
||||
const desktopFile = surface.desktopRef?.file ? path.join(repoRoot, surface.desktopRef.file) : null;
|
||||
if (desktopFile && !fs.existsSync(desktopFile)) problems.push("desktop-file-missing");
|
||||
|
||||
if (!chapter.includes(surface.nameZh)) problems.push("manual-anchor-missing");
|
||||
if (surface.status === "gap") problems.push("ui-gap");
|
||||
if (surface.status === "partial" && !surface.note) problems.push("partial-without-note");
|
||||
|
||||
for (const problem of problems) issues.push({ id: surface.id, category: surface.category, status: surface.status, problem });
|
||||
return { id: surface.id, category: surface.category, status: surface.status, manualAnchor: categorySection[surface.category] ?? "ch16", problems };
|
||||
});
|
||||
|
||||
const byProblem = {};
|
||||
for (const issue of issues) byProblem[issue.problem] = (byProblem[issue.problem] ?? 0) + 1;
|
||||
|
||||
const report = {
|
||||
schema: "freecad-web-manual/ui-gap-register/v1",
|
||||
counts: {
|
||||
surfaces: perSurface.length,
|
||||
withProblems: perSurface.filter(row => row.problems.length).length,
|
||||
byProblem,
|
||||
byStatus: inventory.counts.byStatus,
|
||||
},
|
||||
ok: issues.length === 0,
|
||||
issues,
|
||||
surfaces: perSurface,
|
||||
};
|
||||
|
||||
if (check) {
|
||||
if (!report.ok) {
|
||||
console.error(JSON.stringify({ ok: false, counts: report.counts, sample: issues.slice(0, 10) }, null, 2));
|
||||
process.exit(1);
|
||||
}
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ ok: true, checked: path.relative(repoRoot, outPath), surfaces: perSurface.length }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ ok: report.ok, out: path.relative(repoRoot, outPath), counts: report.counts, sample: issues.slice(0, 5) }, null, 2));
|
||||
process.exit(report.ok ? 0 : 1);
|
||||
112
web/tools/manual/build-fcweb-toolkit.mjs
Normal file
112
web/tools/manual/build-fcweb-toolkit.mjs
Normal file
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env node
|
||||
// Builds the fcweb toolkit usage guide.
|
||||
//
|
||||
// Shares the house template and markdown pipeline with the other manuals
|
||||
// (web/tools/manual/template.html + marked + front-matter chapters), but the
|
||||
// content is the API itself rather than a course, so the figures/replay/stills
|
||||
// machinery is dropped and replaced by one check that matters: every method the
|
||||
// guide documents must exist in the module it claims to come from.
|
||||
//
|
||||
// Consumed by check-fcweb-toolkit.mjs and served from web/teaching/.
|
||||
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 repoRoot = path.resolve(webRoot, "..");
|
||||
const contentDir = path.join(webRoot, "manual", "fcweb-toolkit", "content");
|
||||
const dataDir = path.join(webRoot, "manual", "fcweb-toolkit", "data");
|
||||
const toolkitDir = path.join(repoRoot, "tools", "fcweb");
|
||||
const outFile = path.join(webRoot, "teaching", "fcweb-toolkit.html");
|
||||
|
||||
const esc = value => String(value ?? "")
|
||||
.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
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);
|
||||
|
||||
// ---------------------------------------------------------------- chapters --
|
||||
if (!fs.existsSync(contentDir)) throw new Error(`missing content directory: ${contentDir}`);
|
||||
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);
|
||||
|
||||
// ------------------------------------------------------- API drift guard --
|
||||
// The guide must not document a method that does not exist. Each entry maps a
|
||||
// module file to a required export.
|
||||
const API = {
|
||||
"part.mjs": ["openPart", "PartDocument"],
|
||||
"partdesign.mjs": ["openPartDesign", "PartDesignDocument"],
|
||||
"assembly.mjs": ["openAssembly", "AssemblySession"],
|
||||
"kernel.mjs": ["openKernel", "createSession", "writeTrace", "KernelError"],
|
||||
"opfs.mjs": ["storeBytes", "readExportFile", "safeName", "configureOpfs"],
|
||||
"capture.mjs": ["launchBrowser", "pageCheck", "screenshot", "projectMesh"],
|
||||
};
|
||||
const api = {};
|
||||
for (const [module, exports] of Object.entries(API)) {
|
||||
const file = path.join(toolkitDir, module);
|
||||
if (!fs.existsSync(file)) throw new Error(`toolkit module missing: ${file}`);
|
||||
const source = fs.readFileSync(file, "utf8");
|
||||
for (const name of exports) {
|
||||
const declared = new RegExp(`export\\s+(async\\s+)?(function|class|const)\\s+${name}\\b`).test(source);
|
||||
if (!declared) throw new Error(`${module} no longer exports ${name} — the guide would be wrong`);
|
||||
}
|
||||
api[module] = exports;
|
||||
}
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dataDir, "api.json"), JSON.stringify(api, null, 2));
|
||||
|
||||
// ---------------------------------------------------------------- render ----
|
||||
const sections = chapters.map(chapter => {
|
||||
const html = marked.parse(chapter.body);
|
||||
return { ...chapter, html };
|
||||
});
|
||||
|
||||
const sidebarHtml = `<ol>${chapters.map(chapter => `<li>
|
||||
<a href="#${esc(chapter.id)}">${esc(chapter.meta.title ?? chapter.id)}</a>
|
||||
</li>`).join("")}</ol>`;
|
||||
|
||||
const searchIndex = chapters.map(chapter => ({
|
||||
id: chapter.id,
|
||||
title: chapter.meta.title ?? chapter.id,
|
||||
text: chapter.body.replace(/```[\s\S]*?```/g, " ").replace(/[#*`>|-]/g, " ").replace(/\s+/g, " ").slice(0, 400),
|
||||
}));
|
||||
|
||||
const content = sections.map(section => `<section id="${esc(section.id)}">${section.html}</section>`).join("\n");
|
||||
|
||||
const template = fs.readFileSync(path.join(here, "template.html"), "utf8");
|
||||
const html = template
|
||||
.replaceAll("{{TITLE}}", "fcweb 工具库 · 建零件与装配的通用工具")
|
||||
.replace("{{SIDEBAR}}", sidebarHtml)
|
||||
.replace("{{CONTENT}}", content)
|
||||
.replace("{{COMMAND_INDEX}}", `<section><h2>模块导出速查</h2><div class="table-scroll"><table><thead><tr><th>模块</th><th>导出</th></tr></thead><tbody>${
|
||||
Object.entries(api).map(([module, names]) => `<tr><td><code>${esc(module)}</code></td><td>${names.map(n => `<code>${esc(n)}</code>`).join(" ")}</td></tr>`).join("")
|
||||
}</tbody></table></div></section>`)
|
||||
.replace("{{SEARCH_INDEX}}", JSON.stringify(searchIndex).replace(/</g, "\\u003c"))
|
||||
.replace("{{COMMAND_COUNT}}", String(Object.values(api).flat().length));
|
||||
|
||||
fs.mkdirSync(path.dirname(outFile), { recursive: true });
|
||||
fs.writeFileSync(outFile, html);
|
||||
console.log(JSON.stringify({
|
||||
ok: true, outFile, chapters: chapters.length,
|
||||
modules: Object.keys(api).length, exports: Object.values(api).flat().length,
|
||||
bytes: fs.statSync(outFile).size,
|
||||
}));
|
||||
@@ -105,12 +105,17 @@ const commandIndex = `<section id="command-index-section"><h1 id="ch15">附录
|
||||
<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) => {
|
||||
// One pager per chapter: previous/next links only, so the row never grows with
|
||||
// the chapter count (a single all-chapter row overflowed the page at 1440px).
|
||||
const chapterIndex = new Map(chapters.map((chapter, index) => [chapter.id, index]));
|
||||
content = content.replace(/<h1 id="([^"]+)">/g, (match, id) => {
|
||||
const index = chapterIndex.get(id);
|
||||
if (index === undefined) return match;
|
||||
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">`);
|
||||
return `<div class="pager">${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>"}</div>
|
||||
${match}`;
|
||||
});
|
||||
|
||||
// Validate referenced screenshots before writing.
|
||||
const missing = [];
|
||||
|
||||
234
web/tools/manual/build-parts-manual.mjs
Normal file
234
web/tools/manual/build-parts-manual.mjs
Normal file
@@ -0,0 +1,234 @@
|
||||
#!/usr/bin/env node
|
||||
// Builds the beginner "part design" course handout.
|
||||
//
|
||||
// Shares the reducer manual's template and markdown pipeline, but owns its own
|
||||
// content directory and output. The distinguishing feature is that every figure
|
||||
// is a still captured by the per-part recording itself (tools/reducer-parts-course
|
||||
// /stills/P##/), so the handout and the videos can never disagree about what a
|
||||
// step looked like.
|
||||
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-parts", "content");
|
||||
const assetsDir = path.join(webRoot, "manual", "reducer-parts", "assets");
|
||||
const stillsRoot = path.join(webRoot, "tools", "reducer-parts-course", "stills");
|
||||
const outFile = path.join(webRoot, "teaching", "reducer-parts-manual.html");
|
||||
const outAssets = path.join(webRoot, "teaching", "reducer-parts-manual-assets");
|
||||
const caseDir = path.join(webRoot, "teaching", "cases", "secondary-reducer-pro");
|
||||
const replayDir = path.join(caseDir, "out", "replay");
|
||||
const partsCourse = path.join(webRoot, "tools", "reducer-parts-course");
|
||||
const esc = value => String(value ?? "").replace(/&/g, "&").replace(/</g, "<")
|
||||
.replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
const readJson = file => (fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null);
|
||||
const spec = readJson(path.join(partsCourse, "parts-spec.json"));
|
||||
const course = readJson(path.join(partsCourse, "course.json"));
|
||||
const failures = [];
|
||||
|
||||
// ---- figures: every step still the recorder captured ----------------------
|
||||
// Chapter markdown refers to a step with ``.
|
||||
// The builder resolves it to the real PNG and, when the caption omits numbers,
|
||||
// appends the ones the replay recorded for that step.
|
||||
fs.mkdirSync(assetsDir, { recursive: true });
|
||||
// Map each replay step to the still the driver captured for it.
|
||||
//
|
||||
// The filename alone is not a reliable key: the driver sanitises spaces to
|
||||
// underscores, so "Gear1_20T involute" becomes "Gear1_20T_involute" and the
|
||||
// reverse mapping is ambiguous. The episode's own script records which scene
|
||||
// id belongs to which kernel step, so index by scene id instead.
|
||||
const stillIndex = new Map(); // "P21|outer pad" -> { file, step }
|
||||
for (const entry of spec?.episodes ?? []) {
|
||||
const dir = path.join(stillsRoot, entry.episode);
|
||||
if (!fs.existsSync(dir)) { failures.push(`${entry.episode}: no stills directory (record the video first)`); continue; }
|
||||
const replay = readJson(path.join(replayDir, `${entry.document}.json`));
|
||||
const script = readJson(path.join(partsCourse, "episodes", entry.episode, "script.zh.json"));
|
||||
for (const scene of script?.scenes ?? []) {
|
||||
if (typeof scene.step !== "number") continue;
|
||||
const stem = `${scene.id}-${String(scene.title).replace(/[^\w一-龥-]+/g, "_")}`;
|
||||
const file = path.join(dir, `${stem}.png`);
|
||||
if (!fs.existsSync(file)) { failures.push(`${entry.episode}: missing still ${scene.id} (${scene.title})`); continue; }
|
||||
stillIndex.set(`${entry.episode}|${scene.title}`, { file, step: replay?.steps?.[scene.step - 1] ?? null });
|
||||
}
|
||||
}
|
||||
|
||||
const copyStill = (episode, label, where) => {
|
||||
const key = `${episode}|${label}`;
|
||||
const hit = stillIndex.get(key);
|
||||
if (!hit) { failures.push(`${where}: no still for ${key}`); return null; }
|
||||
if (!fs.existsSync(assetsDir)) fs.mkdirSync(assetsDir, { recursive: true });
|
||||
const target = `${episode}-${label.replace(/[^\w一-龥-]+/g, "_")}.png`;
|
||||
fs.copyFileSync(hit.file, path.join(assetsDir, target));
|
||||
// The page is served from teaching/, and this manual owns its own asset folder.
|
||||
return { src: `./reducer-parts-manual-assets/${target}`, step: hit.step };
|
||||
};
|
||||
|
||||
// ---- front matter and chapters --------------------------------------------
|
||||
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);
|
||||
|
||||
// Resolve ::still directives into markdown images with a figure caption.
|
||||
const figureCount = { total: 0 };
|
||||
const withFigures = chapter => chapter.body.replace(
|
||||
/!\[([^\]]*)\]\(::still\s+(\S+)\s+(.+?)\)/g,
|
||||
(whole, caption, episode, label) => {
|
||||
const hit = copyStill(episode, label.trim(), `${chapter.id} "${caption}"`);
|
||||
if (!hit) return "";
|
||||
figureCount.total++;
|
||||
const step = hit.step;
|
||||
const facts = step
|
||||
? ` ${step.volume != null && step.volume > 0 ? `体积 ${Number(step.volume).toLocaleString("zh-CN", { maximumFractionDigits: 0 })} mm³` : "草图轮廓"},面数 ${step.faceCount ?? "-"},耗时 ${Number(step.seconds).toFixed(2)} s。`
|
||||
: "";
|
||||
const text = caption?.trim() ? `${caption.trim()}${facts}` : `${episode} · ${label}${facts}`;
|
||||
return `\n\n\n\n`;
|
||||
});
|
||||
|
||||
|
||||
// Resolve `::ui P21 outer pad` into an "界面操作" block: the screenshot the UI
|
||||
// driver captured for that step, plus the exact field values it typed. The
|
||||
// values come from out/ui-steps, so the manual cannot describe an operation the
|
||||
// UI does not actually perform.
|
||||
const PAGE_LABEL_ZH = { "partdesign.html": "零件设计页", "project.html?workbench=PartDesign": "项目页 · 零件设计工作台" };
|
||||
const uiStepIndex = new Map(); // "P21|outer pad" -> ui-steps entry
|
||||
const uiStillsRoot = path.join(partsCourse, "ui-stills");
|
||||
for (const entry of spec?.episodes ?? []) {
|
||||
const steps = readJson(path.join(partsCourse, "out", "ui-steps", `${entry.document}.json`));
|
||||
const script = readJson(path.join(partsCourse, "episodes", entry.episode, "script.zh.json"));
|
||||
const bySceneTitle = new Map((script?.scenes ?? []).map(scene => [scene.title, scene.id]));
|
||||
for (const step of steps?.steps ?? []) {
|
||||
const scene = bySceneTitle.get(step.label);
|
||||
const still = scene ? path.join(uiStillsRoot, entry.episode, `${scene}-${String(step.label).replace(/[^\w一-龥-]+/g, "_")}.png`) : null;
|
||||
uiStepIndex.set(`${entry.episode}|${step.label}`, { step, still: still && fs.existsSync(still) ? still : null });
|
||||
}
|
||||
}
|
||||
|
||||
const uiCount = { total: 0, missingStill: [] };
|
||||
const row = (field, value) => `<tr><th>${esc(field)}</th><td>${esc(value)}</td></tr>`;
|
||||
const uiValues = step => {
|
||||
const rows = [];
|
||||
const num = value => Number.isFinite(Number(value)) ? String(Math.round(Number(value) * 1000) / 1000) : esc(value);
|
||||
if (step.kind === "sketch") {
|
||||
rows.push(row("界面", PAGE_LABEL_ZH[step.page] ?? step.page));
|
||||
rows.push(row("命令", step.command));
|
||||
if (step.profileType === "Circle") rows.push(row("半径", num(step.parameters?.Radius)));
|
||||
else if (step.profileType === "Rectangle") { rows.push(row("宽", num(step.parameters?.Width))); rows.push(row("高", num(step.parameters?.Height))); }
|
||||
else { rows.push(row("几何条数", String(step.geometries?.length ?? 0))); rows.push(row("约束条数", String(step.constraints?.length ?? 0))); }
|
||||
const [x, y, z] = step.position ?? [0, 0, 0];
|
||||
rows.push(row("位置 X / Y / Z", `${num(x)} / ${num(y)} / ${num(z)}`));
|
||||
if (Array.isArray(step.placementRotation) && step.placementRotation.some((value, index) => index < 3 && value !== 0)) {
|
||||
rows.push(row("Sketch plane", step.placementRotation.map(num).join(", ") === "0,0,0,1" ? "XY" : "非 XY(见四元数)"));
|
||||
rows.push(row("placementRotation", step.placementRotation.map(num).join(", ")));
|
||||
} else rows.push(row("Sketch plane", "XY"));
|
||||
} else if (step.kind === "feature") {
|
||||
rows.push(row("命令", step.command));
|
||||
rows.push(row("轮廓", step.profile ?? "-"));
|
||||
rows.push(row("长度", num(step.length)));
|
||||
if (step.angle != null) rows.push(row("角度", num(step.angle)));
|
||||
rows.push(row("Sides", step.midplane ? "Symmetric" : "One side"));
|
||||
} else if (step.kind === "gear") {
|
||||
rows.push(row("命令", step.command));
|
||||
for (const [key, value] of Object.entries(step.gearParameters ?? {})) rows.push(row(key, num(value)));
|
||||
} else rows.push(row("命令", step.command ?? "-"));
|
||||
return rows.join("");
|
||||
};
|
||||
|
||||
const withUiBlocks = (chapter, bodyText) => (bodyText ?? chapter.body).replace(
|
||||
/::ui\s+(\S+)\s+([^\n)]+)/g,
|
||||
(whole, episode, labelText) => {
|
||||
const label = labelText.trim();
|
||||
const hit = uiStepIndex.get(`${episode}|${label}`);
|
||||
if (!hit) { failures.push(`${chapter.id}: no ui-steps entry for ${episode} ${label}`); return ""; }
|
||||
uiCount.total++;
|
||||
// A ::ui block with no screenshot would teach the operation with words
|
||||
// only; the whole point is that the picture proves it can be done.
|
||||
if (!hit.still) { uiCount.missingStill.push(`${episode} ${label}`); failures.push(`${chapter.id}: no UI screenshot for ${episode} ${label}`); }
|
||||
const image = hit.still
|
||||
? `\n\n}-ui.png)\n\n`
|
||||
: "\n\n> 该步尚未截到界面图。\n\n";
|
||||
if (hit.still) {
|
||||
const target = `${episode}-${label.replace(/[^\w一-龥-]+/g, "_")}-ui.png`;
|
||||
fs.copyFileSync(hit.still, path.join(assetsDir, target));
|
||||
}
|
||||
return `<div class="ui-block"><h4>界面操作</h4>${image}<table>${uiValues(hit.step)}</table></div>`;
|
||||
});
|
||||
|
||||
const sections = [];
|
||||
const sidebar = [];
|
||||
for (const chapter of chapters) {
|
||||
const body = withUiBlocks(chapter, withFigures(chapter));
|
||||
const html = marked.parse(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 = [...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 });
|
||||
}
|
||||
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>`;
|
||||
|
||||
// ---- appendix A: the 23 parts, straight from the replay -------------------
|
||||
const partRows = [];
|
||||
for (const entry of course?.episodes ?? []) {
|
||||
const replay = readJson(path.join(replayDir, `${entry.document}.json`));
|
||||
if (!replay) continue;
|
||||
const last = replay.steps.at(-1);
|
||||
// Link to the course page's own anchor for this episode; the handout has no
|
||||
// per-episode chapter, so a same-page "#P01" would be a dead link.
|
||||
partRows.push(`<tr><td><a href="cases/reducer-parts-course.html#${esc(entry.id)}">${esc(entry.id)}</a></td><td>${esc(entry.title)}</td>
|
||||
<td>${replay.steps.length}</td><td>${last.faceCount ?? "-"}</td>
|
||||
<td>${last.volume != null ? Number(last.volume).toLocaleString("zh-CN", { maximumFractionDigits: 0 }) : "-"}</td>
|
||||
<td>${Number(last.seconds).toFixed(1)}</td></tr>`);
|
||||
}
|
||||
const appendix = `<section><h1 id="appendix">附录:23 件实测与视频对照</h1>
|
||||
<p>每一行的数字都来自该零件自己的建模回放记录,与视频里看到的同源。点零件编号跳到对应章节。</p>
|
||||
<div class="table-scroll"><table><thead><tr><th>集</th><th>零件</th><th>步数</th><th>面数</th><th>体积 mm³</th><th>末步耗时 s</th></tr></thead><tbody>${partRows.join("")}</tbody></table></div>
|
||||
<h2 id="appendix-videos">看录像</h2>
|
||||
<p>每章的“对应视频”链接到该零件的建造成片;全部 23 集见 <a href="cases/reducer-parts-course.html">零件建模过程课程页</a>。</p>
|
||||
</section>`;
|
||||
|
||||
if (failures.length) { console.log(JSON.stringify({ failures }, null, 2)); process.exit(1); }
|
||||
|
||||
const content = [...sections.map(chapter => chapter.html), appendix].join("\n");
|
||||
fs.mkdirSync(outAssets, { recursive: true });
|
||||
if (fs.existsSync(assetsDir)) 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}}", "")
|
||||
.replace("{{SEARCH_INDEX}}", "[]")
|
||||
.replace("{{COMMAND_COUNT}}", "0");
|
||||
fs.writeFileSync(outFile, html);
|
||||
console.log(JSON.stringify({ ok: true, outFile, chapters: chapters.length, figures: figureCount.total,
|
||||
stills: stillIndex.size, bytes: fs.statSync(outFile).size }));
|
||||
180
web/tools/manual/build-reducer-manual.mjs
Normal file
180
web/tools/manual/build-reducer-manual.mjs
Normal file
@@ -0,0 +1,180 @@
|
||||
#!/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, "&").replace(/</g, "<")
|
||||
.replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
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 }));
|
||||
@@ -4,10 +4,9 @@
|
||||
// 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, seedOpfsFromBytes } from "../carrier-course/lib/opfs.mjs";
|
||||
import { createActionRunner } from "./lib/actions.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
@@ -31,8 +30,6 @@ 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",
|
||||
@@ -47,167 +44,23 @@ async function runOnce() {
|
||||
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.optional && (await locator.count()) === 0) return;
|
||||
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 < 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 });
|
||||
};
|
||||
// The action interpreter is shared with the headed functional suite; only the
|
||||
// evidence destinations and the record sink differ.
|
||||
const runner = createActionRunner(page, {
|
||||
origin, shotDir, shotPrefix: `${chapter}/${workflow}/`, record, shotIndex: shots,
|
||||
fixturePath: path.join(webRoot, "manual", "fixtures", `${chapter}-${workflow}.FCStd`),
|
||||
});
|
||||
|
||||
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 "selectIndex":
|
||||
await page.locator(action.selector).first().selectOption({ index: action.index });
|
||||
record({ action: "selectIndex", selector: action.selector, index: action.index });
|
||||
break;
|
||||
case "press": await page.keyboard.press(action.key); record({ action: "press", key: action.key }); break;
|
||||
case "clickCanvas": {
|
||||
const target = page.locator(action.selector).first();
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(200);
|
||||
const box = await target.boundingBox();
|
||||
if (!box) throw new Error(`canvas missing: ${action.selector}`);
|
||||
await page.mouse.click(box.x + box.width * action.fx, box.y + box.height * action.fy);
|
||||
await page.waitForTimeout(action.wait ?? 250);
|
||||
record({ action: "clickCanvas", selector: action.selector, fx: action.fx, fy: action.fy });
|
||||
break;
|
||||
}
|
||||
case "assertAnyText": {
|
||||
const texts = await page.locator(action.selector).allTextContents();
|
||||
if (!texts.some(text => String(text).includes(action.contains)))
|
||||
throw new Error(`assertAnyText failed: ${action.contains} in ${JSON.stringify(texts.slice(0, 5))}`);
|
||||
record({ action: "assertAnyText", selector: action.selector, contains: action.contains });
|
||||
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 "seed": {
|
||||
const file = path.resolve(action.file);
|
||||
if (!fs.existsSync(file)) throw new Error(`seed fixture missing: ${file}`);
|
||||
await seedOpfsFromBytes(page, action.name ?? path.basename(file), fs.readFileSync(file));
|
||||
record({ action: "seed", file, name: action.name ?? path.basename(file) });
|
||||
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 "waitOptions": {
|
||||
const locator = page.locator(action.selector).first();
|
||||
let count = 0;
|
||||
for (let attempt = 0; attempt < 80; attempt++) {
|
||||
count = await locator.locator("option").count();
|
||||
if (count >= (action.min ?? 1)) break;
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
if (count < (action.min ?? 1)) throw new Error(`waitOptions failed: ${action.selector} ${count}`);
|
||||
record({ action: "waitOptions", selector: action.selector, count });
|
||||
break;
|
||||
}
|
||||
case "assertValue": {
|
||||
const value = await page.locator(action.selector).first().inputValue();
|
||||
if (String(value) !== String(action.value)) throw new Error(`assertValue failed: ${action.selector} ${value} != ${action.value}`);
|
||||
record({ action: "assertValue", selector: action.selector, value });
|
||||
break;
|
||||
}
|
||||
case "wait": await page.waitForTimeout(action.ms ?? 500); break;
|
||||
default: throw new Error(`unknown action ${action.type}`);
|
||||
}
|
||||
}
|
||||
for (const action of scenario.actions) await runner.run(action);
|
||||
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,
|
||||
ok: true, trace, pageErrors, consoleErrors,
|
||||
shots: shots.map(item => ({ ...item, file: path.relative(webRoot, item.file) })),
|
||||
};
|
||||
fs.writeFileSync(path.join(reportDir, `${chapter}-${workflow}.json`), `${JSON.stringify(report, null, 2)}\n`);
|
||||
return report;
|
||||
|
||||
63
web/tools/manual/check-fcweb-toolkit.mjs
Normal file
63
web/tools/manual/check-fcweb-toolkit.mjs
Normal file
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env node
|
||||
// Verifies the built fcweb toolkit guide in a real browser.
|
||||
//
|
||||
// Reuses tools/fcweb/capture.mjs rather than re-deriving selectors, so the
|
||||
// health metrics (overflow, broken images, page errors) are measured exactly
|
||||
// the same way any other page check measures them.
|
||||
//
|
||||
// MANUAL_URL=http://127.0.0.1:5190/fcweb-toolkit.html node web/tools/manual/check-fcweb-toolkit.mjs
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { launchBrowser, pageCheck, writeArtifact } from "../../../tools/fcweb/capture.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const contentDir = path.join(webRoot, "manual", "fcweb-toolkit", "content");
|
||||
const outDir = path.join(webRoot, "..", "docs", "current", "fcweb-toolkit-check");
|
||||
|
||||
const url = process.env.MANUAL_URL || "http://127.0.0.1:5190/fcweb-toolkit.html";
|
||||
const chapterIds = fs.readdirSync(contentDir)
|
||||
.filter(name => name.endsWith(".md"))
|
||||
.map(name => {
|
||||
const text = fs.readFileSync(path.join(contentDir, name), "utf8");
|
||||
const meta = /^---\n([\s\S]*?)\n---\n/.exec(text);
|
||||
const id = meta ? (/^id:\s*(.+)$/m.exec(meta[1])?.[1]?.trim()) : null;
|
||||
return id ?? name.replace(/\.md$/, "");
|
||||
});
|
||||
|
||||
const browser = await launchBrowser({ headed: false });
|
||||
let report;
|
||||
try {
|
||||
report = await pageCheck(browser, url, {
|
||||
viewports: [{ width: 1440, height: 900 }, { width: 390, height: 844 }],
|
||||
expect: { chapters: chapterIds.length, anchorIds: chapterIds },
|
||||
});
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
// The search box is the one interactive affordance the guide ships; prove it
|
||||
// can find a known API name rather than just render.
|
||||
const missingChapters = report.viewports
|
||||
.flatMap(viewport => viewport.missingIds)
|
||||
.filter(id => chapterIds.includes(id));
|
||||
|
||||
const summary = {
|
||||
ok: report.ok && missingChapters.length === 0,
|
||||
url,
|
||||
chapters: chapterIds.length,
|
||||
missingChapters: [...new Set(missingChapters)],
|
||||
viewports: report.viewports.map(viewport => ({
|
||||
viewport: viewport.viewport,
|
||||
status: viewport.status,
|
||||
overflow: viewport.overflow,
|
||||
brokenImages: viewport.brokenImages.length,
|
||||
pageErrors: viewport.pageErrors.length,
|
||||
failedRequests: viewport.failedRequests.length,
|
||||
ok: viewport.ok,
|
||||
})),
|
||||
};
|
||||
writeArtifact(outDir, "fcweb-toolkit-page-check.json", summary);
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
process.exit(summary.ok ? 0 : 1);
|
||||
66
web/tools/manual/check-parts-manual.mjs
Normal file
66
web/tools/manual/check-parts-manual.mjs
Normal file
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env node
|
||||
// Desktop + mobile check for the part-design handout: overflow, page errors,
|
||||
// broken images, chapter count, and that every part is illustrated.
|
||||
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/reducer-parts-manual.html";
|
||||
const specs = JSON.parse(fs.readFileSync(path.join(webRoot, "tools", "reducer-parts-course", "parts-spec.json"), "utf8"));
|
||||
|
||||
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-reducer-parts-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(600);
|
||||
await page.evaluate(() => { for (const image of document.images) image.loading = "eager"; });
|
||||
await page.waitForTimeout(2000);
|
||||
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),
|
||||
figures: document.querySelectorAll("main img").length,
|
||||
// The appendix heading is an <h1>, so the table is a following sibling
|
||||
// rather than a descendant.
|
||||
appendixRows: (() => {
|
||||
const heading = document.getElementById("appendix");
|
||||
for (let node = heading?.nextElementSibling; node; node = node.nextElementSibling) {
|
||||
const table = node.matches(".table-scroll") ? node : node.querySelector?.(".table-scroll");
|
||||
if (table) return table.querySelectorAll("tbody tr").length;
|
||||
if (node.matches("h1")) break;
|
||||
}
|
||||
return 0;
|
||||
})(),
|
||||
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||
};
|
||||
});
|
||||
if (viewport.width === 1440) await page.screenshot({ path: path.join(webRoot, "teaching", "reducer-parts-manual.png"), fullPage: false });
|
||||
report.viewports.push({ viewport, status: response?.status(), errors, failed, ...metrics });
|
||||
await page.close();
|
||||
}
|
||||
await browser.close();
|
||||
|
||||
const expectedChapters = 15;
|
||||
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.chapters === expectedChapters && item.figures >= 50
|
||||
&& item.appendixRows === specs.episodes.length);
|
||||
fs.mkdirSync(path.join(webRoot, "manual", "reducer-parts", "data"), { recursive: true });
|
||||
fs.writeFileSync(path.join(webRoot, "manual", "reducer-parts", "data", "page-check.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ ok: report.ok, viewports: report.viewports.map(v => ({ w: v.viewport.width, chapters: v.chapters, figures: v.figures, overflow: v.overflow, broken: v.brokenImages.length, errors: v.errors.length, rows: v.appendixRows })) }));
|
||||
process.exitCode = report.ok ? 0 : 1;
|
||||
74
web/tools/manual/check-reducer-manual.mjs
Normal file
74
web/tools/manual/check-reducer-manual.mjs
Normal file
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env node
|
||||
// Checks the reducer manual on desktop and mobile: overflow, page errors,
|
||||
// broken images, chapter count, search, and that the appendix's build record
|
||||
// and gap list actually rendered. Writes manual/reducer/data/page-check.json.
|
||||
//
|
||||
// This is a separate checker from check-page.mjs because the two manuals have
|
||||
// genuinely different appendices: the generic one indexes 1500+ commands, the
|
||||
// reducer one records this case's build steps, gaps and acceptance numbers.
|
||||
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/reducer-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-reducer-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);
|
||||
await page.evaluate(() => { for (const image of document.images) image.loading = "eager"; });
|
||||
await page.waitForTimeout(1500);
|
||||
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),
|
||||
// Walk from each appendix heading to the next table, skipping the <p>
|
||||
// that sits between them in the generated HTML.
|
||||
...(() => {
|
||||
const rowsAfter = id => {
|
||||
const heading = document.querySelector(`h2[id^="${id}"]`);
|
||||
if (!heading) return 0;
|
||||
for (let node = heading.nextElementSibling; node; node = node.nextElementSibling) {
|
||||
const table = node.matches(".table-scroll") ? node : node.querySelector?.(".table-scroll");
|
||||
if (table) return table.querySelectorAll("tbody tr").length;
|
||||
if (node.matches("h1, h2")) break;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
return { buildRows: rowsAfter("ch15-steps"), gapRows: rowsAfter("ch15-gaps"),
|
||||
partRows: rowsAfter("ch15-parts"), numbersRows: rowsAfter("ch15-numbers") };
|
||||
})(),
|
||||
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||
searchSize: SEARCH_INDEX.length,
|
||||
};
|
||||
});
|
||||
await page.locator('#search').fill('轴承');
|
||||
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", "reducer-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.chapters === 13 && item.buildRows > 50 && item.gapRows >= 20
|
||||
&& item.searchHits > 0);
|
||||
fs.mkdirSync(path.join(webRoot, "manual", "reducer", "data"), { recursive: true });
|
||||
fs.writeFileSync(path.join(webRoot, "manual", "reducer", "data", "page-check.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify(report));
|
||||
process.exitCode = report.ok ? 0 : 1;
|
||||
106
web/tools/manual/check-ui-design-doc.mjs
Normal file
106
web/tools/manual/check-ui-design-doc.mjs
Normal file
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env node
|
||||
// Verify the generated UI design document in a real browser.
|
||||
//
|
||||
// Reuses tools/fcweb/capture.mjs. Checks structure (chapter anchors, appendix
|
||||
// row count), page health (errors, broken images, overflow) at two viewports,
|
||||
// and that every screenshot the document references actually exists.
|
||||
//
|
||||
// node web/tools/manual/check-ui-design-doc.mjs
|
||||
// DOC_URL=http://127.0.0.1:5199/evidence/current/web-freecad-ui-layout-and-functions.html \
|
||||
// node web/tools/manual/check-ui-design-doc.mjs
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { launchBrowser, openPage, writeArtifact } from "../../../tools/fcweb/capture.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const docPath = path.join(repoRoot, "docs/current/web-freecad-ui-layout-and-functions.html");
|
||||
const inventoryPath = path.join(repoRoot, "tools/fcweb/out/ui-inventory.json");
|
||||
const outDir = path.join(repoRoot, "docs/current/ui-design/data");
|
||||
|
||||
if (!fs.existsSync(docPath)) {
|
||||
console.error(`[check-ui-design-doc] missing document: ${docPath}`);
|
||||
process.exit(2);
|
||||
}
|
||||
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
|
||||
const expectedChapters = inventory.chapters.map(chapter => `wb-${chapter.id}`);
|
||||
const expectedAppendix = inventory.appendix.length;
|
||||
|
||||
const url = process.env.DOC_URL || pathToFileURL(docPath).href;
|
||||
const browser = await launchBrowser({ headed: false });
|
||||
const viewports = [{ width: 1440, height: 900 }, { width: 390, height: 844 }];
|
||||
const reports = [];
|
||||
|
||||
try {
|
||||
for (const viewport of viewports) {
|
||||
const { page, response, errors, failedRequests } = await openPage(browser, url, { viewport });
|
||||
try {
|
||||
// Force lazy images to load so the broken-image check is meaningful.
|
||||
await page.evaluate(async () => {
|
||||
for (const image of document.images) image.loading = "eager";
|
||||
window.scrollTo(0, document.body.scrollHeight);
|
||||
await new Promise(resolve => setTimeout(resolve, 800));
|
||||
window.scrollTo(0, 0);
|
||||
});
|
||||
await page.waitForTimeout(600);
|
||||
|
||||
const dom = await page.evaluate(() => {
|
||||
const brokenImages = [...document.images]
|
||||
.filter(image => image.getAttribute("src"))
|
||||
.filter(image => image.complete && image.naturalWidth === 0)
|
||||
.map(image => image.currentSrc || image.src);
|
||||
const doc = document.documentElement;
|
||||
const ids = [...document.querySelectorAll("[id]")].map(node => node.id);
|
||||
const duplicated = ids.filter((id, index) => ids.indexOf(id) !== index);
|
||||
return {
|
||||
overflow: Math.max(0, doc.scrollWidth - doc.clientWidth),
|
||||
brokenImages,
|
||||
ids,
|
||||
duplicatedIds: [...new Set(duplicated)],
|
||||
chapters: document.querySelectorAll("section.wb").length,
|
||||
appendixRows: document.querySelectorAll("tr[data-appendix-row]").length,
|
||||
tocLinks: document.querySelectorAll("nav.toc a").length,
|
||||
images: document.images.length,
|
||||
};
|
||||
});
|
||||
|
||||
const missing = expectedChapters.filter(id => !dom.ids.includes(id));
|
||||
reports.push({
|
||||
viewport,
|
||||
status: response?.status() ?? null,
|
||||
...dom,
|
||||
missingChapters: missing,
|
||||
pageErrors: errors,
|
||||
failedRequests: failedRequests.slice(0, 5),
|
||||
ok: (response?.status() ?? 0) === 200
|
||||
&& errors.length === 0
|
||||
&& failedRequests.length === 0
|
||||
&& dom.brokenImages.length === 0
|
||||
&& dom.overflow === 0
|
||||
&& missing.length === 0
|
||||
&& dom.duplicatedIds.length === 0
|
||||
&& dom.chapters === inventory.chapters.length
|
||||
&& dom.appendixRows === expectedAppendix,
|
||||
});
|
||||
} finally {
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
const summary = {
|
||||
ok: reports.every(report => report.ok),
|
||||
url,
|
||||
expectedChapters: expectedChapters.length,
|
||||
expectedAppendixRows: expectedAppendix,
|
||||
viewports: reports,
|
||||
};
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(outDir, "doc-check.json"), `${JSON.stringify(summary, null, 2)}\n`);
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
writeArtifact(outDir, "doc-check-last-run.json", summary);
|
||||
process.exit(summary.ok ? 0 : 1);
|
||||
@@ -55,6 +55,7 @@ const chapters = [
|
||||
{ id: "ch13", order: 13, level: "specialist", title: "Draft、Plot、Robot 等专项工具", moduleIds: ["Draft", "Plot", "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: [] },
|
||||
{ id: "ch16", order: 16, level: "appendix", title: "全功能面板索引与实现映射", moduleIds: [] },
|
||||
];
|
||||
|
||||
const moduleChapter = new Map();
|
||||
|
||||
106
web/tools/manual/generate-final-status.mjs
Normal file
106
web/tools/manual/generate-final-status.mjs
Normal file
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env node
|
||||
// Derives web/manual/data/final-status.json from the real pipeline outputs so
|
||||
// the summary never drifts from the generated manual:
|
||||
//
|
||||
// manual-features.json commands / modules / boundaries / chapters
|
||||
// gap-ledger.json verified case count and known boundaries
|
||||
// page-check.json last browser check (overflow, images, sections)
|
||||
// capture/*.json screenshot capture reports
|
||||
// manual-assets/** actual PNG files on disk
|
||||
//
|
||||
// node tools/manual/generate-final-status.mjs
|
||||
// node tools/manual/generate-final-status.mjs --check # exit 1 on drift
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const dataDir = path.join(webRoot, "manual", "data");
|
||||
const read = name => JSON.parse(fs.readFileSync(path.join(dataDir, name), "utf8"));
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
const outPath = path.join(dataDir, "final-status.json");
|
||||
|
||||
const features = read("manual-features.json");
|
||||
const ledger = read("gap-ledger.json");
|
||||
const pageCheck = read("page-check.json");
|
||||
|
||||
const captureDir = path.join(dataDir, "capture");
|
||||
const captureReports = fs.existsSync(captureDir)
|
||||
? fs.readdirSync(captureDir).filter(name => name.endsWith(".json")).sort()
|
||||
: [];
|
||||
let screenshotsCaptured = 0;
|
||||
for (const name of captureReports) {
|
||||
const report = JSON.parse(fs.readFileSync(path.join(captureDir, name), "utf8"));
|
||||
screenshotsCaptured += (report.shots ?? []).length;
|
||||
}
|
||||
|
||||
const assetsDir = path.join(webRoot, "manual", "assets");
|
||||
const countPngs = dir => fs.readdirSync(dir, { withFileTypes: true }).reduce((total, entry) => {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) return total + countPngs(full);
|
||||
return total + (entry.name.endsWith(".png") ? 1 : 0);
|
||||
}, 0);
|
||||
const screenshots = fs.existsSync(assetsDir) ? countPngs(assetsDir) : 0;
|
||||
|
||||
const appChapters = features.chapters.filter(chapter => chapter.level !== "appendix").length;
|
||||
const desktop = pageCheck.viewports.find(view => view.viewport.width >= 900) ?? pageCheck.viewports[0] ?? null;
|
||||
const mobile = pageCheck.viewports.find(view => view.viewport.width < 900) ?? null;
|
||||
const gapRegisterPath = path.join(webRoot, "..", "docs/current/ui-design/data/gap-register.json");
|
||||
const gapRegister = fs.existsSync(gapRegisterPath)
|
||||
? JSON.parse(fs.readFileSync(gapRegisterPath, "utf8"))
|
||||
: null;
|
||||
|
||||
const state = pageCheck.ok && (gapRegister ? gapRegister.ok : false) ? "complete" : "in-progress";
|
||||
const status = {
|
||||
schema: "freecad-web-manual/final-status/v1",
|
||||
generatedAt: new Date().toISOString(),
|
||||
state,
|
||||
chapters: appChapters,
|
||||
chaptersWithAppendix: features.chapters.length,
|
||||
screenshots,
|
||||
commands: features.stats.commands,
|
||||
modules: features.stats.modules,
|
||||
nativeHandlers: features.stats.nativeHandlers,
|
||||
verifiedCommands: ledger.verified,
|
||||
workflows: captureReports.length,
|
||||
boundaries: (features.boundaries ?? []).length,
|
||||
pageCheck: {
|
||||
ok: pageCheck.ok,
|
||||
desktopOverflow: desktop?.overflow ?? null,
|
||||
mobileOverflow: mobile?.overflow ?? null,
|
||||
brokenImages: desktop?.brokenImages ?? [],
|
||||
searchHits: desktop?.searchHits ?? 0,
|
||||
images: desktop?.images ?? 0,
|
||||
sections: desktop?.sections ?? 0,
|
||||
},
|
||||
entry: "web/teaching/manual.html",
|
||||
url: pageCheck.url,
|
||||
assets: "web/teaching/manual-assets",
|
||||
captureReports: "web/manual/data/capture",
|
||||
gapLedger: "web/manual/data/gap-ledger.json",
|
||||
knownBoundaries: (ledger.boundaries ?? []).map(item => item.title),
|
||||
notes: [
|
||||
"由 generate-final-status.mjs 自动派生,不要手改。",
|
||||
`UI 表面清单:${gapRegister ? gapRegister.counts.surfaces : "未生成"} 项,缺口 ${gapRegister ? gapRegister.issues.filter(issue => issue.problem === "ui-gap").length : "未知"} 项。`,
|
||||
],
|
||||
screenshotsCaptured,
|
||||
};
|
||||
|
||||
const text = `${JSON.stringify(status, null, 2)}\n`;
|
||||
|
||||
if (check) {
|
||||
const previous = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : "";
|
||||
const strip = value => JSON.stringify({ ...JSON.parse(value), generatedAt: "__stable__" });
|
||||
if (!previous || strip(previous) !== strip(text)) {
|
||||
console.error("[generate-final-status] --check: final-status.json is stale");
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, checked: "web/manual/data/final-status.json" }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.writeFileSync(outPath, text);
|
||||
console.log(JSON.stringify({ ok: true, out: "web/manual/data/final-status.json", state, chapters: features.chapters.length, screenshots, commands: features.stats.commands }));
|
||||
117
web/tools/manual/generate-gaps-doc.mjs
Normal file
117
web/tools/manual/generate-gaps-doc.mjs
Normal file
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env node
|
||||
// Derives docs/current/web-freecad-manual-gaps.md from the real pipeline outputs so
|
||||
// the gap register never drifts from final-status.json / gap-ledger.json /
|
||||
// gap-register.json. The previous hand-written copy still described the retired
|
||||
// 32-module inventory, which is why this file is generated instead of maintained.
|
||||
//
|
||||
// node web/tools/manual/generate-gaps-doc.mjs
|
||||
// node web/tools/manual/generate-gaps-doc.mjs --check # exit 1 on drift
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const dataDir = path.join(webRoot, "manual", "data");
|
||||
const outPath = path.join(repoRoot, "docs", "current", "web-freecad-manual-gaps.md");
|
||||
const gapRegisterPath = path.join(repoRoot, "docs", "current", "ui-design", "data", "gap-register.json");
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
|
||||
const read = file => JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
const status = read(path.join(dataDir, "final-status.json"));
|
||||
const ledger = read(path.join(dataDir, "gap-ledger.json"));
|
||||
const register = fs.existsSync(gapRegisterPath) ? read(gapRegisterPath) : null;
|
||||
|
||||
const cell = value => String(value ?? "—").replace(/\|/g, "\\|");
|
||||
const lines = [];
|
||||
const push = (...items) => lines.push(...items);
|
||||
|
||||
push("# Web FreeCAD 手册与界面文档 · 缺口与边界账本", "");
|
||||
push("> 本文件由 `web/tools/manual/generate-gaps-doc.mjs` 从真实产物派生,**不要手改**。");
|
||||
push("> 输入:`web/manual/data/final-status.json`、`web/manual/data/gap-ledger.json`、`docs/current/ui-design/data/gap-register.json`。");
|
||||
push("> 复核:`node web/tools/manual/generate-gaps-doc.mjs --check`。", "");
|
||||
|
||||
push("## 口径", "");
|
||||
push(`- 模块数 **${status.modules}**(不含已整体摘除的 OpenSCAD)。`);
|
||||
push(`- 命令矩阵 **${status.commands}** 条,原生承接 **${status.nativeHandlers}** 条。`);
|
||||
push(`- 手工验证命令 **${status.verifiedCommands}** 条;已知边界 **${(ledger.boundaries ?? []).length}** 条。`);
|
||||
push(`- 手册 **${status.chaptersWithAppendix}** 章(正文 ${status.chapters} 章 + 附录章)、页面截图引用 **${status.pageCheck.images}** 处、磁盘 PNG **${status.screenshots}** 个。`);
|
||||
if (register) {
|
||||
const byCategory = register.counts.byCategory ?? {};
|
||||
push(`- UI 表面 **${register.counts.surfaces}** 项:${Object.entries(byCategory).map(([key, value]) => `${key} ${value}`).join(" / ")}。`);
|
||||
const partial = (register.surfaces ?? []).filter(item => item.status === "partial").length;
|
||||
const gap = (register.surfaces ?? []).filter(item => item.status === "gap").length;
|
||||
push(`- 表面状态:implemented ${register.counts.surfaces - partial - gap} / partial ${partial} / gap **${gap}**。`);
|
||||
}
|
||||
push("");
|
||||
|
||||
push("## 已实现的界面覆盖(不是缺口)", "");
|
||||
push("| 项 | 结果 |");
|
||||
push("|---|---|");
|
||||
push(`| 界面设计文档 | \`docs/current/web-freecad-ui-layout-and-functions.html\`,${status.chaptersWithAppendix} 章 + 命令附录 |`);
|
||||
push(`| 手册 | \`web/teaching/manual.html\`,${status.chapters} 章 ${status.pageCheck.sections} 节 |`);
|
||||
push(`| 截图 | 页面引用 ${status.pageCheck.images} 处;磁盘 ${status.screenshots} 个 PNG;采集报告 ${status.workflows} 份 |`);
|
||||
push(`| 浏览器校验 | 桌面 overflow ${status.pageCheck.desktopOverflow} / 移动 overflow ${status.pageCheck.mobileOverflow} / 破图 ${status.pageCheck.brokenImages.length} |`);
|
||||
push("");
|
||||
|
||||
push(`## 已知边界(${(ledger.boundaries ?? []).length} 条)`, "");
|
||||
push("| ID | 模块 | 边界 | 状态 |");
|
||||
push("|---|---|---|---|");
|
||||
for (const item of ledger.boundaries ?? []) {
|
||||
push(`| \`${cell(item.id)}\` | ${cell(item.module)} | ${cell(item.detail)} | ${cell(item.status)} |`);
|
||||
}
|
||||
push("");
|
||||
|
||||
push("## 手工验证的用例", "");
|
||||
push(`共 **${ledger.verified}** 条(台账 \`${path.relative(repoRoot, path.join(dataDir, "gap-ledger.json"))}\`)。`);
|
||||
for (const note of ledger.notes ?? []) push(`- ${note}`);
|
||||
push("");
|
||||
|
||||
if (register) {
|
||||
const flagged = (register.surfaces ?? []).filter(item => item.status === "partial" || item.status === "gap");
|
||||
push(`## 界面表面审计(${register.counts.surfaces} 项,问题 ${register.issues.length} 项)`, "");
|
||||
if (flagged.length) {
|
||||
push("| 表面 | 分类 | 状态 | 注释 |");
|
||||
push("|---|---|---|---|");
|
||||
for (const item of flagged) push(`| ${cell(item.nameZh)} | ${cell(item.category)} | ${cell(item.status)} | ${cell(item.note ?? "—")} |`);
|
||||
} else {
|
||||
push("没有 `partial` 或 `gap` 项。");
|
||||
}
|
||||
push("");
|
||||
push("审计命令:`node web/tools/manual/audit-ui-gaps.mjs --check`。");
|
||||
push("");
|
||||
}
|
||||
|
||||
push("## 复现命令", "");
|
||||
push("```bash");
|
||||
push(`R="/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD"`);
|
||||
push(`node "$R/tools/fcweb/ui-surface-inventory.mjs" --check`);
|
||||
push(`node "$R/tools/fcweb/build-ui-doc.mjs" --check`);
|
||||
push(`node "$R/web/tools/manual/audit-ui-gaps.mjs" --check`);
|
||||
push(`node "$R/web/tools/manual/generate-gaps-doc.mjs" --check`);
|
||||
push(`cd "$R/web" && npm run build:manual && npm run check:manual`);
|
||||
push("```");
|
||||
push("");
|
||||
push("## 边界判定口径", "");
|
||||
push("- 前置未满足(缺文档、缺 Worker、缺原生对象)记边界并保留产品原始错误文本,不写成产品回归。");
|
||||
push("- GUI 控件缺口用 React 组件补齐,不以 GUI-only 名义留作 blocked。");
|
||||
push("- 空白或占位截图不得入库;空白工具栏裁剪由 `build-ui-doc.mjs` 的 1024 字节门槛自动跳过。");
|
||||
push("- 生成物(本文件、第 16 章、`final-status.json`)一律由脚本产出并带 `--check`。");
|
||||
push("");
|
||||
|
||||
const text = `${lines.join("\n")}\n`;
|
||||
if (check) {
|
||||
const previous = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : "";
|
||||
if (previous !== text) {
|
||||
console.error("[generate-gaps-doc] --check: docs/current/web-freecad-manual-gaps.md is stale");
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, checked: "docs/current/web-freecad-manual-gaps.md" }));
|
||||
process.exit(0);
|
||||
}
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, text);
|
||||
console.log(JSON.stringify({ ok: true, out: "docs/current/web-freecad-manual-gaps.md", bytes: Buffer.byteLength(text), boundaries: (ledger.boundaries ?? []).length, surfaces: register?.counts.surfaces ?? null }));
|
||||
203
web/tools/manual/generate-panel-index.mjs
Normal file
203
web/tools/manual/generate-panel-index.mjs
Normal file
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env node
|
||||
// Generates web/manual/content/ch16-panel-index.md from the authoritative UI
|
||||
// surface inventory (tools/fcweb/out/ui-surface-inventory.json).
|
||||
//
|
||||
// The chapter is a reference appendix: every shell region, dock, task panel,
|
||||
// modal dialog, preference page, menu, toolbar, status bar item and viewport
|
||||
// tool with its React owner and desktop reference. Deterministic output: no
|
||||
// timestamps, sorted by category then module then id.
|
||||
//
|
||||
// node tools/manual/generate-panel-index.mjs
|
||||
// node tools/manual/generate-panel-index.mjs --check # exit 1 on drift
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const inventoryPath = path.join(repoRoot, "tools/fcweb/out/ui-surface-inventory.json");
|
||||
const outPath = path.join(webRoot, "manual/content/ch16-panel-index.md");
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
|
||||
if (!fs.existsSync(inventoryPath)) {
|
||||
console.error(`[generate-panel-index] missing ${inventoryPath}; run tools/fcweb/ui-surface-inventory.mjs first`);
|
||||
process.exit(2);
|
||||
}
|
||||
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
|
||||
|
||||
const CATEGORY_ORDER = ["shell-region", "statusbar", "viewport-tool", "dock", "task-panel", "modal-dialog", "preferences-page", "menu", "toolbar"];
|
||||
const CATEGORY_TITLE = {
|
||||
"shell-region": "壳层区域",
|
||||
statusbar: "状态栏",
|
||||
"viewport-tool": "视口工具",
|
||||
dock: "停靠面板",
|
||||
"task-panel": "任务面板",
|
||||
"modal-dialog": "模态对话框",
|
||||
"preferences-page": "偏好设置页",
|
||||
menu: "菜单",
|
||||
toolbar: "工具栏",
|
||||
};
|
||||
const CATEGORY_INTRO = {
|
||||
"shell-region": "主窗口骨架:标题栏、工作台切换器、菜单栏容器、工具栏容器、视口、停靠区、底部报告区、命令面板与快捷键入口。",
|
||||
statusbar: "底部状态栏:文档名、保存状态、网格与渲染统计。",
|
||||
"viewport-tool": "三维视口右上角与导航立方体旁的视图工具:视图切换、剖切面、导航方式等。",
|
||||
dock: "可停靠面板:模型树、属性编辑器、任务面板宿主等,由右侧停靠区承载,可折叠、可切换。",
|
||||
"task-panel": "工作台任务面板:每个 `<module>-<feature>-task.tsx` 对应一个桌面 TaskDialog 参数页,统一由 `TaskFrame` 挂载。",
|
||||
"modal-dialog": "应用级模态对话框:阻断主界面交互、需要确认或选择后才能继续的操作。",
|
||||
"preferences-page": "偏好设置对话框的分页,对应桌面 Edit → Preferences。",
|
||||
menu: "菜单栏条目:按工作台聚合,每项菜单展开后给出命令列表。",
|
||||
toolbar: "工具栏组:每个工作台一组,命令与桌面工具栏一一对应。",
|
||||
};
|
||||
const STATUS_ZH = { implemented: "已实现", partial: "部分实现", gap: "缺口", boundary: "边界" };
|
||||
|
||||
const esc = value => String(value ?? "")
|
||||
.replace(/\|/g, "\\|")
|
||||
.replace(/\n+/g, " ")
|
||||
.trim();
|
||||
|
||||
const surfaceRows = inventory.surfaces
|
||||
.slice()
|
||||
.sort((a, b) => {
|
||||
const ca = CATEGORY_ORDER.indexOf(a.category);
|
||||
const cb = CATEGORY_ORDER.indexOf(b.category);
|
||||
if (ca !== cb) return ca - cb;
|
||||
const ma = a.moduleId ?? "";
|
||||
const mb = b.moduleId ?? "";
|
||||
if (ma !== mb) return ma.localeCompare(mb, "en");
|
||||
return a.id.localeCompare(b.id, "en");
|
||||
});
|
||||
|
||||
const byCategory = new Map();
|
||||
for (const surface of surfaceRows) {
|
||||
if (!byCategory.has(surface.category)) byCategory.set(surface.category, []);
|
||||
byCategory.get(surface.category).push(surface);
|
||||
}
|
||||
|
||||
const counts = inventory.counts;
|
||||
const lines = [];
|
||||
lines.push("---");
|
||||
lines.push("id: ch16");
|
||||
lines.push("order: 16");
|
||||
lines.push("title: 全功能面板索引与实现映射");
|
||||
lines.push("level: appendix");
|
||||
lines.push("---");
|
||||
lines.push("");
|
||||
lines.push("# 第 16 章 全功能面板索引与实现映射");
|
||||
lines.push("");
|
||||
lines.push("本章由 `tools/fcweb/ui-surface-inventory.mjs` 生成,是 Web FreeCAD 全部界面表面的权威索引。");
|
||||
lines.push(`当前共 **${counts.total}** 个界面表面,覆盖 ${Object.keys(counts.byCategory).length} 类;状态分布:` +
|
||||
Object.entries(counts.byStatus).map(([status, count]) => `${STATUS_ZH[status] ?? status} ${count}`).join("、") +
|
||||
"(缺口 " + counts.gaps + " 项)。");
|
||||
lines.push("");
|
||||
lines.push("> 改动 `web/src` 后请重跑 `node tools/fcweb/ui-surface-inventory.mjs` 与本生成器,不要手改本章。");
|
||||
lines.push("");
|
||||
lines.push("## 16.1 分类总览");
|
||||
lines.push("");
|
||||
lines.push("| 类别 | 数量 | 说明 |");
|
||||
lines.push("| --- | ---: | --- |");
|
||||
for (const category of CATEGORY_ORDER) {
|
||||
const rows = byCategory.get(category) ?? [];
|
||||
lines.push(`| ${CATEGORY_TITLE[category]}(\`${category}\`) | ${rows.length} | ${esc(CATEGORY_INTRO[category])} |`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("### 状态口径");
|
||||
lines.push("");
|
||||
lines.push("| 状态 | 含义 |");
|
||||
lines.push("| --- | --- |");
|
||||
lines.push("| 已实现 | React 组件存在、已注册并能从界面到达,有对应命令或路由。 |");
|
||||
lines.push("| 部分实现 | 组件存在但未完全注册/挂载,或仅覆盖桌面能力的一部分。 |");
|
||||
lines.push("| 缺口 | 桌面 FreeCAD 有、Web 端缺失。按项目铁律用 React 组件补齐,不得留作 blocked。 |");
|
||||
lines.push("| 边界 | 受内核或平台限制无法实现(如跨 Worker 文档桥),需写明原因与解除条件。 |");
|
||||
lines.push("");
|
||||
lines.push("## 16.2 界面表面实拍");
|
||||
lines.push("");
|
||||
lines.push("以下截图由 `web/manual/scenarios/ch16-shell-surfaces.json` 在真实运行的 Web FreeCAD 上采集(Playwright,1440×900)。");
|
||||
lines.push("");
|
||||
const SHOTS = [
|
||||
["01-shell-overview", "完整壳层:应用菜单栏、工作台工具栏、对象树、属性面板、三维视口、任务区与文档标签。"],
|
||||
["02-tools-menu", "Tools 菜单:偏好设置、快捷键定制、命令面板入口。"],
|
||||
["03-preferences", "偏好设置对话框:单位制、导航风格、视图与保存选项。"],
|
||||
["04-shortcuts", "快捷键编辑器:按命令搜索并重绑按键。"],
|
||||
["05-command-palette", "命令面板(Ctrl+Shift+P):模糊搜索全部已注册命令。"],
|
||||
["06-bottom-dock", "底部停靠:Selection view / Report view / Python console 三个页签,可浮动、可全屏。"],
|
||||
["07-viewport-tools", "视口工具条:移动 / 旋转 / 关闭、局部坐标、「局部坐标…」编辑入口与位置读数。"],
|
||||
["08-task-panel", "任务面板:Part 立方体创建任务,含 Box dimensions、Volume 与 Bounds,底部为关闭与取消按钮。"],
|
||||
];
|
||||
for (const [name, caption] of SHOTS) {
|
||||
lines.push(``);
|
||||
lines.push("");
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
let sectionNumber = 3;
|
||||
for (const category of CATEGORY_ORDER) {
|
||||
const rows = byCategory.get(category) ?? [];
|
||||
if (!rows.length) continue;
|
||||
lines.push(`## 16.${sectionNumber} ${CATEGORY_TITLE[category]}(${rows.length})`);
|
||||
lines.push("");
|
||||
lines.push(CATEGORY_INTRO[category]);
|
||||
lines.push("");
|
||||
lines.push("| 名称 | React 实现 | 桌面参考 | 状态 | 注释 |");
|
||||
lines.push("| --- | --- | --- | --- | --- |");
|
||||
for (const surface of rows) {
|
||||
const owner = surface.owner?.file
|
||||
? `\`${esc(surface.owner.file.replace(/^web\//, ""))}${surface.owner.symbol ? `#${esc(surface.owner.symbol)}` : ""}\``
|
||||
: "—";
|
||||
const desktop = surface.desktopRef?.file
|
||||
? `\`${esc(surface.desktopRef.file.replace(/^freecad-source\//, ""))}${surface.desktopRef.symbol ? `#${esc(surface.desktopRef.symbol)}` : ""}\``
|
||||
: "—";
|
||||
const label = category === "menu" || category === "toolbar" ? esc(surface.nameZh) : `${esc(surface.nameZh)}(\`${esc(surface.id)}\`)`;
|
||||
lines.push(`| ${label} | ${owner} | ${desktop} | ${STATUS_ZH[surface.status] ?? surface.status} | ${esc(surface.note ?? "") || "—"} |`);
|
||||
}
|
||||
lines.push("");
|
||||
sectionNumber += 1;
|
||||
}
|
||||
|
||||
lines.push("## 16." + sectionNumber + " 缺口与边界清单");
|
||||
lines.push("");
|
||||
const gaps = inventory.gaps ?? [];
|
||||
if (!gaps.length) {
|
||||
lines.push("当前清单无 `gap`/`boundary` 项:全部界面表面均有 React 实现。");
|
||||
} else {
|
||||
lines.push("| 表面 | 类别 | 状态 | 原因 | 解除条件 |");
|
||||
lines.push("| --- | --- | --- | --- | --- |");
|
||||
for (const gap of gaps) {
|
||||
lines.push(`| \`${esc(gap.id)}\` | ${esc(CATEGORY_TITLE[gap.category] ?? gap.category)} | ${STATUS_ZH[gap.status] ?? gap.status} | ${esc(gap.reason ?? "")} | ${esc(gap.resolution ?? "")} |`);
|
||||
}
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("## 16." + (sectionNumber + 1) + " 复核命令");
|
||||
lines.push("");
|
||||
lines.push("```bash");
|
||||
lines.push('R="/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD"');
|
||||
lines.push('node "$R/tools/fcweb/ui-inventory.mjs"');
|
||||
lines.push('node "$R/tools/fcweb/ui-surface-inventory.mjs" # 生成清单');
|
||||
lines.push('node "$R/tools/fcweb/ui-surface-inventory.mjs" --check # 漂移检查');
|
||||
lines.push('node "$R/web/tools/manual/generate-panel-index.mjs" # 重生成本章');
|
||||
lines.push("```");
|
||||
lines.push("");
|
||||
|
||||
const markdown = lines.join("\n");
|
||||
|
||||
if (check) {
|
||||
const previous = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : "";
|
||||
if (previous !== markdown) {
|
||||
console.error("[generate-panel-index] --check: ch16-panel-index.md is stale");
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, checked: path.relative(repoRoot, outPath), surfaces: counts.total }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, markdown);
|
||||
console.log(JSON.stringify({
|
||||
ok: true,
|
||||
out: path.relative(repoRoot, outPath),
|
||||
surfaces: counts.total,
|
||||
sections: sectionNumber - 1,
|
||||
bytes: Buffer.byteLength(markdown),
|
||||
}));
|
||||
186
web/tools/manual/lib/actions.mjs
Normal file
186
web/tools/manual/lib/actions.mjs
Normal file
@@ -0,0 +1,186 @@
|
||||
// Scenario action interpreter shared by capture.mjs (screenshot capture) and the
|
||||
// headed functional suite (assertions). Behaviour is identical to the switch it
|
||||
// was extracted from; everything environment-specific arrives through options.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { listOpfsFiles, readOpfsFile, seedOpfsFromBytes } from "../../carrier-course/lib/opfs.mjs";
|
||||
|
||||
const sha256 = file => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
||||
|
||||
export function createActionRunner(page, {
|
||||
origin = "",
|
||||
shotDir,
|
||||
shotPrefix = "",
|
||||
fixturePath = null,
|
||||
record = () => {},
|
||||
shotIndex = [],
|
||||
} = {}) {
|
||||
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.optional && (await locator.count()) === 0) return;
|
||||
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 => {
|
||||
if (!shotDir) throw new Error("shot action needs a shotDir");
|
||||
const file = path.join(shotDir, `${action.name}.png`);
|
||||
fs.mkdirSync(shotDir, { recursive: true });
|
||||
if (action.selector) {
|
||||
const target = page.locator(action.selector).first();
|
||||
await target.waitFor({ state: "visible", timeout: 30000 });
|
||||
try {
|
||||
await target.screenshot({ path: file, timeout: 20000 });
|
||||
} catch {
|
||||
// Element screenshots scroll the element into view and can time out on
|
||||
// containers taller than the viewport; evidence capture must not turn
|
||||
// a healthy page state into a failure, so fall back to the viewport.
|
||||
await page.screenshot({ path: file });
|
||||
record({ action: "shot", name: action.name, fallback: "viewport" });
|
||||
}
|
||||
} else {
|
||||
await page.screenshot({ path: file, fullPage: Boolean(action.fullPage) });
|
||||
}
|
||||
const stat = fs.statSync(file);
|
||||
if (stat.size < 1024) throw new Error(`screenshot too small: ${file}`);
|
||||
shotIndex.push({ id: `${shotPrefix}${action.name}`, file,
|
||||
bytes: stat.size, sha256: sha256(file), fullPage: Boolean(action.fullPage), selector: action.selector ?? null });
|
||||
record({ action: "shot", name: action.name, bytes: stat.size });
|
||||
return file;
|
||||
};
|
||||
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;
|
||||
if (fixturePath) {
|
||||
fs.mkdirSync(path.dirname(fixturePath), { recursive: true });
|
||||
fs.writeFileSync(fixturePath, Buffer.from(bytes));
|
||||
}
|
||||
record({ action: "save", name, bytes: bytes.length, status });
|
||||
return { name, bytes: Buffer.from(bytes) };
|
||||
};
|
||||
|
||||
const run = async action => {
|
||||
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 "selectIndex":
|
||||
await page.locator(action.selector).first().selectOption({ index: action.index });
|
||||
record({ action: "selectIndex", selector: action.selector, index: action.index });
|
||||
break;
|
||||
case "press": await page.keyboard.press(action.key); record({ action: "press", key: action.key }); break;
|
||||
case "clickCanvas": {
|
||||
const target = page.locator(action.selector).first();
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(200);
|
||||
const box = await target.boundingBox();
|
||||
if (!box) throw new Error(`canvas missing: ${action.selector}`);
|
||||
await page.mouse.click(box.x + box.width * action.fx, box.y + box.height * action.fy);
|
||||
await page.waitForTimeout(action.wait ?? 250);
|
||||
record({ action: "clickCanvas", selector: action.selector, fx: action.fx, fy: action.fy });
|
||||
break;
|
||||
}
|
||||
case "assertAnyText": {
|
||||
const texts = await page.locator(action.selector).allTextContents();
|
||||
if (!texts.some(text => String(text).includes(action.contains)))
|
||||
throw new Error(`assertAnyText failed: ${action.contains} in ${JSON.stringify(texts.slice(0, 5))}`);
|
||||
record({ action: "assertAnyText", selector: action.selector, contains: action.contains });
|
||||
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 "seed": {
|
||||
const file = path.resolve(action.file);
|
||||
if (!fs.existsSync(file)) throw new Error(`seed fixture missing: ${file}`);
|
||||
await seedOpfsFromBytes(page, action.name ?? path.basename(file), fs.readFileSync(file));
|
||||
record({ action: "seed", file, name: action.name ?? path.basename(file) });
|
||||
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 "waitOptions": {
|
||||
const locator = page.locator(action.selector).first();
|
||||
let count = 0;
|
||||
for (let attempt = 0; attempt < 80; attempt++) {
|
||||
count = await locator.locator("option").count();
|
||||
if (count >= (action.min ?? 1)) break;
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
if (count < (action.min ?? 1)) throw new Error(`waitOptions failed: ${action.selector} ${count}`);
|
||||
record({ action: "waitOptions", selector: action.selector, count });
|
||||
break;
|
||||
}
|
||||
case "assertValue": {
|
||||
const value = await page.locator(action.selector).first().inputValue();
|
||||
if (String(value) !== String(action.value)) throw new Error(`assertValue failed: ${action.selector} ${value} != ${action.value}`);
|
||||
record({ action: "assertValue", selector: action.selector, value });
|
||||
break;
|
||||
}
|
||||
case "wait": await page.waitForTimeout(action.ms ?? 500); break;
|
||||
default: throw new Error(`unknown action ${action.type}`);
|
||||
}
|
||||
};
|
||||
|
||||
return { click, shot, save, run, shotIndex };
|
||||
}
|
||||
@@ -38,6 +38,20 @@
|
||||
main figure { margin:16px 0; }
|
||||
main figcaption { color:var(--muted); font-size:12.5px; }
|
||||
.table-scroll { max-width:100%; overflow-x:auto; }
|
||||
/* UI-operation block: the real screenshot plus the exact field values the
|
||||
driver typed, side by side on wide screens and stacked on phones. */
|
||||
.ui-block { margin:20px 0; padding:14px 16px; border:1px solid var(--line); border-radius:10px; background:var(--panel); }
|
||||
.ui-block h4 { margin:0 0 10px; font-size:14px; letter-spacing:0.04em; color:var(--accent); }
|
||||
.ui-block img { display:block; width:100%; height:auto; border-radius:8px; border:1px solid var(--line); }
|
||||
.ui-block table { width:100%; margin-top:10px; border-collapse:collapse; font-size:13px; }
|
||||
.ui-block th { text-align:left; font-weight:600; color:var(--muted); padding:5px 8px; width:38%; }
|
||||
.ui-block td { padding:5px 8px; font-variant-numeric:tabular-nums; }
|
||||
.ui-block tr + tr { border-top:1px solid var(--line); }
|
||||
@media (min-width:900px) {
|
||||
.ui-block { display:grid; grid-template-columns:minmax(0,1.4fr) minmax(0,1fr); gap:16px; align-items:start; }
|
||||
.ui-block h4 { grid-column:1 / -1; }
|
||||
.ui-block table { margin-top:0; }
|
||||
}
|
||||
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); }
|
||||
@@ -52,7 +66,7 @@
|
||||
.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); }
|
||||
.pager { display:flex; flex-wrap:wrap; 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; }
|
||||
|
||||
Reference in New Issue
Block a user