#!/usr/bin/env node
// Build the full Web FreeCAD UI design document.
//
// Pipeline:
// ui-inventory.mjs -> out/ui-inventory.json
// ui-capture.mjs -> out/ui-shots/*.png + out/ui-capture-report.json
// build-ui-doc.mjs -> docs/current/web-freecad-ui-layout-and-functions.html
//
// The hand-written shell chapters live in docs/current/ui-design/source.html.
// The first run seeds that file from the previous hand-written document, so the
// existing prose is preserved byte-for-byte; only the two markers are added.
//
// node tools/fcweb/build-ui-doc.mjs --seed # one time
// node tools/fcweb/build-ui-doc.mjs
// node tools/fcweb/build-ui-doc.mjs --check # rebuild, compare bytes
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(here, "../..");
const args = process.argv.slice(2);
const argValue = (name, fallback) => {
const index = args.indexOf(name);
return index >= 0 && args[index + 1] ? args[index + 1] : fallback;
};
const inventoryPath = path.resolve(argValue("--inventory", path.join(here, "out", "ui-inventory.json")));
const capturePath = path.resolve(argValue("--capture", path.join(here, "out", "ui-capture-report.json")));
const shotsDir = path.resolve(argValue("--shots", path.join(here, "out", "ui-shots")));
const sourcePath = path.resolve(argValue("--source", path.join(repoRoot, "docs/current/ui-design/source.html")));
const outPath = path.resolve(argValue("--out", path.join(repoRoot, "docs/current/web-freecad-ui-layout-and-functions.html")));
const assetsDir = path.join(path.dirname(outPath), "web-freecad-ui-assets", "workbenches");
const CHAPTERS_MARKER = "";
const APPENDIX_MARKER = "";
const SHELL_MARKER = "";
const MATRIX_MARKER = "";
const PANEL_MARKER = "";
const MODAL_MARKER = "";
const PREFS_MARKER = "";
const MAPPING_MARKER = "";
const GAP_MARKER = "";
function fail(message, code = 2) {
console.error(`[build-ui-doc] ${message}`);
process.exit(code);
}
function esc(value) {
return String(value ?? "")
.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """);
}
const MENU_TEXT = text => String(text ?? "").replace(/&(?![a-z]+;|#\d+;)/g, "&");
// ------------------------------------------------------------------ seed --
if (args.includes("--seed")) {
if (fs.existsSync(sourcePath)) fail(`--seed refused: ${sourcePath} already exists`, 1);
if (!fs.existsSync(outPath)) fail(`--seed: previous document not found at ${outPath}`, 1);
let html = fs.readFileSync(outPath, "utf8");
// Keep the shell prose; insert the two generated markers.
const anchor = '
5 · 面板与对话框 ';
if (!html.includes(anchor)) fail("--seed: could not find section 5 heading to anchor the workbench chapters");
html = html.replace(anchor, `${CHAPTERS_MARKER}\n\n${anchor}`);
if (!html.includes("")) fail("--seed: no found");
html = html.replace("", `${APPENDIX_MARKER}\n\n`);
fs.mkdirSync(path.dirname(sourcePath), { recursive: true });
fs.writeFileSync(sourcePath, html);
console.log(JSON.stringify({ ok: true, seeded: sourcePath, bytes: fs.statSync(sourcePath).size }));
process.exit(0);
}
// ------------------------------------------------------------- inputs ----
if (!fs.existsSync(sourcePath)) fail(`missing source template: ${sourcePath} (run --seed once)`);
if (!fs.existsSync(inventoryPath)) fail(`missing inventory: ${inventoryPath} (run ui-inventory.mjs)`);
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
const capture = fs.existsSync(capturePath) ? JSON.parse(fs.readFileSync(capturePath, "utf8")) : { results: [] };
const captureById = new Map((capture.results ?? []).map(item => [item.id, item]));
const surfacePath = path.resolve(argValue("--surfaces", path.join(here, "out", "ui-surface-inventory.json")));
if (!fs.existsSync(surfacePath)) fail(`missing surface inventory: ${surfacePath} (run ui-surface-inventory.mjs)`);
const surfacesDoc = JSON.parse(fs.readFileSync(surfacePath, "utf8"));
const surfaces = surfacesDoc.surfaces ?? [];
const surfaceById = new Map(surfaces.map(surface => [surface.id, surface]));
const meta = {};
const commandMeta = new Map();
for (const chapter of inventory.chapters) for (const command of chapter.commands) commandMeta.set(command.id, command);
const appendixById = new Map(inventory.appendix.map(row => [row.id, row]));
const placementById = new Map();
for (const chapter of inventory.chapters) {
for (const command of chapter.commands) {
const list = placementById.get(command.id) ?? [];
list.push({ workbench: chapter.id, where: command.placement });
placementById.set(command.id, list);
}
}
// --------------------------------------------------------------- shots ----
fs.mkdirSync(assetsDir, { recursive: true });
// Blank toolbar crops come out as ~195-byte strips when the workbench renders no
// toolbar in the Web shell (Draft, Start, Measure, Sketcher, Cloud, Help, Import,
// Inspection, JtReader, Sandbox, Tux). Copying them would put an empty image into
// the document, so only keep crops with real pixels.
const MIN_TOOLBAR_CROP_BYTES = 1024;
const skippedToolbarCrops = [];
for (const item of capture.results ?? []) {
if (!item.file || !fs.existsSync(item.file)) continue;
fs.copyFileSync(item.file, path.join(assetsDir, `${item.id}.png`));
if (item.toolbarCrop && fs.existsSync(item.toolbarCrop)) {
if (fs.statSync(item.toolbarCrop).size < MIN_TOOLBAR_CROP_BYTES) {
skippedToolbarCrops.push(item.id);
// Drop a blank crop left behind by an earlier build: the assets directory is
// generated, so pruning our own leftovers is safe.
const stale = path.join(assetsDir, `${item.id}-toolbars.png`);
if (fs.existsSync(stale) && fs.statSync(stale).size < MIN_TOOLBAR_CROP_BYTES) fs.unlinkSync(stale);
} else {
fs.copyFileSync(item.toolbarCrop, path.join(assetsDir, `${item.id}-toolbars.png`));
}
}
}
// ------------------------------------------------------------ chapters ----
const statusBadge = chapter => {
const map = {
renders: ["ok", "可渲染"],
fallback: ["warn", "回退"],
unreachable: ["bad", "不可达"],
conditional: ["warn", "需前置条件"],
"manifest-only": ["bad", "仅桌面清单"],
};
const [cls, label] = map[chapter.status] ?? ["", chapter.status];
return `${label} `;
};
const renderMenuList = items => ``;
const dispositionBadge = value => {
const map = { native_handler: ["ok", "原生"], restricted: ["warn", "受限"], not_implemented: ["bad", "未实现"] };
const [cls, label] = map[value] ?? ["", value ?? ""];
return `${label} `;
};
function renderChapter(chapter, index) {
const anchor = `wb-${chapter.id}`;
const shot = captureById.get(chapter.id);
const hasShot = shot && shot.status === "ok" && fs.existsSync(path.join(assetsDir, `${chapter.id}.png`));
const counts = chapter.counts;
const stats = [
counts.webCommands != null ? `${counts.webCommands} 模块命令` : null,
counts.pythonApi != null ? `${counts.pythonApi.toLocaleString("en-US")} Python API` : null,
counts.objectTypes != null ? `${counts.objectTypes} 对象类型` : null,
counts.toolbarSlots ? `${counts.toolbarSlots} 工具栏项` : null,
counts.matrixNative + counts.matrixRestricted > 0
? `桌面命令 ${counts.matrixNative + counts.matrixRestricted}(原生 ${counts.matrixNative} / 受限 ${counts.matrixRestricted})` : null,
].filter(Boolean);
const parts = [];
// The anchor id lives on the heading only: the section and the heading must
// not both carry it (duplicate ids break fragment navigation).
parts.push(``);
parts.push(`${index}. ${esc(chapter.title)} ${statusBadge(chapter)} `);
if (chapter.summary) parts.push(`${esc(chapter.summary)}
`);
parts.push(`${stats.map(esc).join(" · ")}
`);
if (hasShot) {
parts.push(` `
+ `${esc(chapter.title)} · 实际界面(1600×1000)。 `);
} else {
const reason = shot?.warnings?.[0] ?? chapter.reason ?? "本外壳内没有可截取的界面状态。";
parts.push(`无界面截图。 ${esc(reason)}
`);
}
if (chapter.toolbars.length) {
parts.push(`工具栏 `);
const toolbarShot = path.join(assetsDir, `${chapter.id}-toolbars.png`);
if (fs.existsSync(toolbarShot) && fs.statSync(toolbarShot).size >= MIN_TOOLBAR_CROP_BYTES) {
parts.push(` `
+ `${esc(chapter.title)} · 工具栏实际渲染。 `);
} else {
parts.push(`Web 壳层在该工作台未渲染独立工具栏:本表按桌面清单列出,对应命令在 Web 端以工作台页面按钮呈现。
`);
}
}
if (chapter.menus.length) {
parts.push(`菜单 `);
for (const menu of chapter.menus) {
parts.push(`${esc(menu.label)} ${renderMenuList(menu.items)} `);
}
parts.push(`
`);
}
if (chapter.taskPanels.length) {
parts.push(`任务面板 `);
} else if (chapter.status === "renders") {
parts.push(`该工作台在 Web 端没有专用任务面板。
`);
}
if (counts.pages?.length) {
parts.push(`模块页面 ${counts.pages.map(page => `${esc(page)}.html`).join(" · ")}
`);
}
// All commands that touch this workbench: manifest placements + matrix rows.
const matrixRows = inventory.appendix.filter(row => row.module === chapter.id);
if (matrixRows.length || chapter.commands.length) {
const table = [];
const seen = new Set();
for (const command of chapter.commands) {
if (seen.has(command.id)) continue;
seen.add(command.id);
const row = appendixById.get(command.id);
table.push({
id: command.id,
text: MENU_TEXT(command.menuText || ""),
accel: command.accel || "",
where: command.placement === "toolbar" ? "工具栏" : command.placement === "menu" ? "菜单" : "其他",
disposition: row?.disposition ?? "",
source: row ? `${row.sourcePath}:${row.sourceLine}` : "",
});
}
for (const row of matrixRows) {
if (seen.has(row.id)) continue;
seen.add(row.id);
const command = commandMeta.get(row.id);
table.push({
id: row.id,
text: MENU_TEXT(command?.menuText || ""),
accel: command?.accel || "",
where: (row.uiSurfaces ?? []).includes("toolbar") ? "工具栏" : (row.uiSurfaces ?? []).includes("menu") ? "菜单" : "—",
disposition: row.disposition,
source: row.sourcePath ? `${row.sourcePath}:${row.sourceLine}` : "",
});
}
table.sort((a, b) => a.id.localeCompare(b.id));
parts.push(`全部 ${table.length} 条命令 `);
}
parts.push(` `);
return parts.join("\n");
}
// ------------------------------------------------------- surface catalog --
const surfaceStatusBadge = status => {
const map = {
implemented: ["ok", "已实现"],
partial: ["warn", "部分"],
gap: ["bad", "缺口"],
boundary: ["bad", "边界"],
};
const [cls, label] = map[status] ?? ["", status ?? ""];
return `${label} `;
};
const ownerCell = surface => surface?.owner?.file
? `${esc(surface.owner.file)}${surface.owner.symbol ? ` · ${esc(surface.owner.symbol)}` : ""}`
: "—";
const desktopCell = surface => surface?.desktopRef?.file
? `${esc(surface.desktopRef.file.replace(/^freecad-source\//, ""))}${surface.desktopRef.symbol ? ` · ${esc(surface.desktopRef.symbol)}` : ""}`
: "—";
const surfaceTable = (rows, nameHeader = "名称") => {
const parts = [``);
return parts.join("\n");
};
const renderShellCatalog = () => {
const rows = surfaces.filter(surface => ["shell-region", "statusbar", "dock", "viewport-tool"].includes(surface.category));
return `3.4 全局壳区域、停靠与视口工具(生成)
本表由 tools/fcweb/ui-surface-inventory.mjs 生成:每一行给出中文名称、React owner、桌面 FreeCAD 源文件与当前状态。
${surfaceTable(rows)}`;
};
const renderWorkbenchSurfaceMatrix = () => {
const byModule = new Map();
for (const surface of surfaces) {
if (!surface.moduleId) continue;
const entry = byModule.get(surface.moduleId) ?? { total: 0, task: 0, menu: 0, toolbar: 0, partial: 0 };
entry.total += 1;
if (surface.category === "task-panel") entry.task += 1;
if (surface.category === "menu") entry.menu += 1;
if (surface.category === "toolbar") entry.toolbar += 1;
if (surface.status !== "implemented") entry.partial += 1;
byModule.set(surface.moduleId, entry);
}
const parts = [`3.5 工作台表面矩阵(生成) `,
``);
return parts.join("\n");
};
const renderPanelCatalog = () => {
const rows = surfaces.filter(surface => surface.category === "task-panel" || surface.category === "dock");
const byModule = new Map();
for (const surface of rows) {
const key = surface.moduleId ?? "全局停靠";
if (!byModule.has(key)) byModule.set(key, []);
byModule.get(key).push(surface);
}
const parts = [`5.4 全部功能面板(生成) `,
`共 ${rows.length} 个停靠/任务面板,按工作台分组;每行给出 React 实现位置、桌面参考与状态。
`];
for (const [moduleId, list] of [...byModule.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
parts.push(`${esc(moduleId)} · ${list.length} 个面板 ${surfaceTable(list, "面板")} `);
}
return parts.join("\n");
};
const renderModalCatalog = () => {
const rows = surfaces.filter(surface => surface.category === "modal-dialog");
return `5.5 模态对话框与覆盖层(生成) \n${surfaceTable(rows, "对话框")}`;
};
const renderPreferencesCatalog = () => {
const rows = surfaces.filter(surface => surface.category === "preferences-page");
return `5.6 偏好设置页(生成) \n${surfaceTable(rows, "偏好页")}`;
};
const renderImplementationMapping = () => {
const parts = [`10.1 界面 → React 实现 → 桌面源码全量映射(生成) `,
`共 ${surfaces.length} 个 UI 表面。状态口径:已实现 owner 存在且被挂载;部分 组件存在但未挂载或工作台需前置条件;缺口 桌面有而 Web 无;边界 内核能力不支持。
`];
for (const category of ["shell-region", "statusbar", "dock", "viewport-tool", "menu", "toolbar", "task-panel", "modal-dialog", "preferences-page"]) {
const rows = surfaces.filter(surface => surface.category === category);
if (!rows.length) continue;
parts.push(`${esc(category)}(${rows.length}) `);
parts.push(surfaceTable(rows));
}
return parts.join("\n");
};
const renderGapRegister = () => {
const rows = surfaces.filter(surface => surface.status === "gap" || surface.status === "partial");
const parts = [`10.2 缺口登记(生成) `];
if (!rows.length) {
parts.push(`当前没有登记中的 UI 缺口;所有表面均已实现或已标注为边界。
`);
} else {
parts.push(`共 ${rows.length} 项待处理或部分实现。
`, surfaceTable(rows, "表面"));
}
return parts.join("\n");
};
const chapterHtml = inventory.chapters.map((chapter, index) => renderChapter(chapter, index + 1)).join("\n\n");
// ------------------------------------------------------------ appendix ----
const byModule = new Map();
for (const row of inventory.appendix) {
if (!byModule.has(row.module)) byModule.set(row.module, []);
byModule.get(row.module).push(row);
}
const appendixParts = [];
appendixParts.push(`附录 · 命令矩阵(${inventory.appendix.length} 条) `);
appendixParts.push(`来源 web/public/api/workbench-command-matrix.json。处置含义:原生 有完整内核处理;受限 只部分实现或依赖桌面能力;未实现 无处理。
`);
// A command can appear under more than one module group; only the first
// occurrence may carry the fragment id, or the document has duplicate ids.
const anchoredCommands = new Set();
for (const [module, rows] of [...byModule.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
appendixParts.push(`${esc(module)} · ${rows.length} 条 `);
}
const appendixHtml = appendixParts.join("\n");
// ---------------------------------------------------------------- merge ----
let html = fs.readFileSync(sourcePath, "utf8");
if (!html.includes(CHAPTERS_MARKER)) fail(`source template lost the chapters marker ${CHAPTERS_MARKER}`);
if (!html.includes(APPENDIX_MARKER)) fail(`source template lost the appendix marker ${APPENDIX_MARKER}`);
const workbenchIntro = `逐工作台详解
下面按工作台逐一列出:界面截图、工具栏按钮、菜单结构、任务面板与全部命令。状态徽标说明该工作台在主外壳中的可用性。
`;
html = html.replace(CHAPTERS_MARKER, `${workbenchIntro}\n${chapterHtml}`);
html = html.replace(APPENDIX_MARKER, appendixHtml);
const surfaceBodies = [
[SHELL_MARKER, renderShellCatalog()],
[MATRIX_MARKER, renderWorkbenchSurfaceMatrix()],
[PANEL_MARKER, renderPanelCatalog()],
[MODAL_MARKER, renderModalCatalog()],
[PREFS_MARKER, renderPreferencesCatalog()],
[MAPPING_MARKER, renderImplementationMapping()],
[GAP_MARKER, renderGapRegister()],
];
for (const [marker, body] of surfaceBodies) {
if (!html.includes(marker)) fail(`source template lost the surface marker ${marker}`);
html = html.replace(marker, body);
}
// Regenerate the table of contents from the final headings.
const tocEntries = [];
for (const match of html.matchAll(/]*>([\s\S]*?)<\/h2>/g)) {
const text = match[2].replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
tocEntries.push({ id: match[1], text, chapter: match[1].startsWith("wb-") });
}
const tocHtml = `
目录
${tocEntries.map(entry => entry.chapter
? ` ${esc(entry.text)} `
: ` ${esc(entry.text)} `).join("\n")}
`;
html = html.replace(/[\s\S]*?<\/nav>/, tocHtml);
// A few styles the generated body relies on.
if (!html.includes("/* generated */")) {
html = html.replace("", `/* generated */
.wb h3{margin-top:26px}
.menu-tree{margin:6px 0 0;padding-left:18px;font-size:13px}
.menu-tree li{margin:2px 0}
.menu-tree .sep{color:var(--line);list-style:none;margin-left:-10px}
details.card>summary{cursor:pointer;color:#cfe0ea}
.table-scroll{max-height:520px;overflow:auto}
`);
}
const next = `${html}`;
fs.mkdirSync(path.dirname(outPath), { recursive: true });
if (args.includes("--check")) {
if (!fs.existsSync(outPath)) fail("--check: no output to compare", 1);
const previous = fs.readFileSync(outPath, "utf8");
if (previous !== next) fail("--check: document is stale; rebuild without --check", 1);
console.log(JSON.stringify({ ok: true, checked: outPath, bytes: Buffer.byteLength(next) }));
process.exit(0);
}
fs.writeFileSync(outPath, next);
console.log(JSON.stringify({
ok: true,
out: outPath,
bytes: fs.statSync(outPath).size,
chapters: inventory.chapters.length,
captured: capture.results?.length ?? 0,
appendixRows: inventory.appendix.length,
assets: fs.readdirSync(assetsDir).length,
blankToolbarCrops: skippedToolbarCrops.length,
}));