Files
FreeCADWasmDev/tools/fcweb/build-ui-doc.mjs
wangdequan 300c8efb01 docs(web): full UI surface inventory, illustrated manual, panel screenshots
Interface design document and manual now share one authoritative surface
inventory (333 surfaces across 9 categories, gap 0), and every chapter carries
real Playwright screenshots of the panels it documents.

- tools/fcweb: ui-surface-scan/ui-surface-inventory (deterministic --check),
  build-ui-doc renders panel catalog, workbench matrix and mapping tables;
  blank toolbar crops (<1 KB) are skipped and pruned instead of embedded
- web/tools/manual: generate-panel-index (ch16), audit-ui-gaps,
  generate-final-status, generate-gaps-doc; pager is per-chapter so the manual
  no longer overflows horizontally
- manual: 130 screenshot references / 128 PNGs, panel sections for ch02-ch13
- web/src: utility menus stop click propagation (menu reopened on item click);
  workbench shell gains an OPFS document picker so workbench.html can bind a
  real document instead of the fixed workbench-document id; Sketcher panel
  moves from the command column to the main stage

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 01:30:31 +08:00

481 lines
25 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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 = "<!--{{WORKBENCH_CHAPTERS}}-->";
const APPENDIX_MARKER = "<!--{{COMMAND_APPENDIX}}-->";
const SHELL_MARKER = "<!--{{SHELL_REGION_CATALOG}}-->";
const MATRIX_MARKER = "<!--{{WORKBENCH_SURFACE_MATRIX}}-->";
const PANEL_MARKER = "<!--{{PANEL_CATALOG}}-->";
const MODAL_MARKER = "<!--{{MODAL_DIALOG_CATALOG}}-->";
const PREFS_MARKER = "<!--{{PREFERENCES_CATALOG}}-->";
const MAPPING_MARKER = "<!--{{IMPLEMENTATION_MAPPING}}-->";
const GAP_MARKER = "<!--{{GAP_REGISTER}}-->";
function fail(message, code = 2) {
console.error(`[build-ui-doc] ${message}`);
process.exit(code);
}
function esc(value) {
return String(value ?? "")
.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
const MENU_TEXT = text => String(text ?? "").replace(/&(?![a-z]+;|#\d+;)/g, "&amp;");
// ------------------------------------------------------------------ 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 = '<h2 id="s5" class="anchor">5 · 面板与对话框</h2>';
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("</main>")) fail("--seed: no </main> found");
html = html.replace("</main>", `${APPENDIX_MARKER}\n\n</main>`);
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 `<span class="${cls}">${label}</span>`;
};
const renderMenuList = items => `<ul class="menu-tree">${items.map(item => {
if (item.kind === "separator") return `<li class="sep">—</li>`;
if (item.kind === "submenu") return `<li><strong>${esc(item.label)}</strong>${renderMenuList(item.items)}</li>`;
const command = commandMeta.get(item.id);
return `<li><code>${esc(item.id)}</code> ${esc(MENU_TEXT(command?.menuText ?? ""))}</li>`;
}).join("")}</ul>`;
const dispositionBadge = value => {
const map = { native_handler: ["ok", "原生"], restricted: ["warn", "受限"], not_implemented: ["bad", "未实现"] };
const [cls, label] = map[value] ?? ["", value ?? ""];
return `<span class="${cls}">${label}</span>`;
};
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(`<section class="wb">`);
parts.push(`<h2 id="${anchor}">${index}. ${esc(chapter.title)} ${statusBadge(chapter)}</h2>`);
if (chapter.summary) parts.push(`<p>${esc(chapter.summary)}</p>`);
parts.push(`<p class="muted">${stats.map(esc).join(" · ")}</p>`);
if (hasShot) {
parts.push(`<figure><img src="./web-freecad-ui-assets/workbenches/${chapter.id}.png" loading="lazy" decoding="async" alt="${esc(chapter.title)} 界面截图" />`
+ `<figcaption>${esc(chapter.title)} · 实际界面(1600×1000)。</figcaption></figure>`);
} else {
const reason = shot?.warnings?.[0] ?? chapter.reason ?? "本外壳内没有可截取的界面状态。";
parts.push(`<div class="warnbox"><strong>无界面截图。</strong>${esc(reason)}</div>`);
}
if (chapter.toolbars.length) {
parts.push(`<h3>工具栏</h3><div class="table-scroll"><table><thead><tr><th>工具栏</th><th>按钮</th></tr></thead><tbody>`);
for (const toolbar of chapter.toolbars) {
const buttons = toolbar.items.map(id => {
const command = commandMeta.get(id);
return `<code title="${esc(command?.toolTip ?? "")}">${esc(MENU_TEXT(command?.menuText || id))}</code>`;
}).join(" ");
parts.push(`<tr><td><strong>${esc(toolbar.name)}</strong></td><td>${buttons || "—"}</td></tr>`);
}
parts.push(`</tbody></table></div>`);
const toolbarShot = path.join(assetsDir, `${chapter.id}-toolbars.png`);
if (fs.existsSync(toolbarShot) && fs.statSync(toolbarShot).size >= MIN_TOOLBAR_CROP_BYTES) {
parts.push(`<figure><img src="./web-freecad-ui-assets/workbenches/${chapter.id}-toolbars.png" loading="lazy" decoding="async" alt="${esc(chapter.title)} 工具栏截图" />`
+ `<figcaption>${esc(chapter.title)} · 工具栏实际渲染。</figcaption></figure>`);
} else {
parts.push(`<p class="muted">Web 壳层在该工作台未渲染独立工具栏:本表按桌面清单列出,对应命令在 Web 端以工作台页面按钮呈现。</p>`);
}
}
if (chapter.menus.length) {
parts.push(`<h3>菜单</h3><div class="grid two">`);
for (const menu of chapter.menus) {
parts.push(`<details class="card"><summary><strong>${esc(menu.label)}</strong></summary>${renderMenuList(menu.items)}</details>`);
}
parts.push(`</div>`);
}
if (chapter.taskPanels.length) {
parts.push(`<h3>任务面板</h3><div class="table-scroll"><table><thead><tr><th>面板标题</th><th>React 实现</th><th>桌面参考</th><th>状态</th></tr></thead><tbody>`);
for (const panel of chapter.taskPanels) {
const titles = panel.titles.length ? panel.titles.map(t => esc(t)).join(" / ") : "<em>(无静态标题)</em>";
const surface = surfaceById.get(`task:${chapter.id}:${panel.file.replace(/\.tsx?$/, "")}`);
parts.push(`<tr><td>${titles}</td><td><code>web/src/${esc(panel.file)}</code></td>`
+ `<td>${desktopCell(surface)}</td><td>${surfaceStatusBadge(surface?.status ?? "implemented")}</td></tr>`);
}
parts.push(`</tbody></table></div>`);
} else if (chapter.status === "renders") {
parts.push(`<p class="muted">该工作台在 Web 端没有专用任务面板。</p>`);
}
if (counts.pages?.length) {
parts.push(`<h3>模块页面</h3><p>${counts.pages.map(page => `<code>${esc(page)}.html</code>`).join(" · ")}</p>`);
}
// 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(`<details><summary>全部 ${table.length} 条命令</summary><div class="table-scroll"><table><thead><tr><th>命令</th><th>名称</th><th>位置</th><th>加速键</th><th>处置</th><th>来源</th></tr></thead><tbody>`);
for (const row of table) {
parts.push(`<tr><td><code>${esc(row.id)}</code></td><td>${esc(row.text)}</td><td>${esc(row.where)}</td>`
+ `<td>${row.accel ? `<kbd>${esc(row.accel)}</kbd>` : "—"}</td><td>${dispositionBadge(row.disposition)}</td><td class="num">${esc(row.source)}</td></tr>`);
}
parts.push(`</tbody></table></div></details>`);
}
parts.push(`</section>`);
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 `<span class="${cls}">${label}</span>`;
};
const ownerCell = surface => surface?.owner?.file
? `<code>${esc(surface.owner.file)}${surface.owner.symbol ? ` · ${esc(surface.owner.symbol)}` : ""}</code>`
: "—";
const desktopCell = surface => surface?.desktopRef?.file
? `<code>${esc(surface.desktopRef.file.replace(/^freecad-source\//, ""))}${surface.desktopRef.symbol ? ` · ${esc(surface.desktopRef.symbol)}` : ""}</code>`
: "—";
const surfaceTable = (rows, nameHeader = "名称") => {
const parts = [`<div class="table-scroll"><table><thead><tr><th>${esc(nameHeader)}</th><th>React 实现</th><th>桌面 FreeCAD 来源</th><th>状态</th><th>手册锚点</th></tr></thead><tbody>`];
for (const surface of rows) {
const note = surface.note ? `<br><span class="muted">${esc(surface.note)}</span>` : "";
parts.push(`<tr><td>${esc(surface.nameZh)}${note}</td><td>${ownerCell(surface)}</td><td>${desktopCell(surface)}</td>`
+ `<td>${surfaceStatusBadge(surface.status)}</td><td>${surface.manualAnchor ? `<code>${esc(surface.manualAnchor)}</code>` : "—"}</td></tr>`);
}
parts.push(`</tbody></table></div>`);
return parts.join("\n");
};
const renderShellCatalog = () => {
const rows = surfaces.filter(surface => ["shell-region", "statusbar", "dock", "viewport-tool"].includes(surface.category));
return `<h3 id="shell-catalog">3.4 全局壳区域、停靠与视口工具(生成)</h3>
<p class="muted">本表由 <code>tools/fcweb/ui-surface-inventory.mjs</code> 生成:每一行给出中文名称、React owner、桌面 FreeCAD 源文件与当前状态。</p>
${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 = [`<h3 id="workbench-surface-matrix">3.5 工作台表面矩阵(生成)</h3>`,
`<div class="table-scroll"><table><thead><tr><th>工作台</th><th>表面总数</th><th>任务面板</th><th>菜单</th><th>工具栏</th><th>非完全实现</th></tr></thead><tbody>`];
for (const [moduleId, entry] of [...byModule.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
parts.push(`<tr><td><a href="#wb-${esc(moduleId)}">${esc(moduleId)}</a></td><td class="num">${entry.total}</td>`
+ `<td class="num">${entry.task}</td><td class="num">${entry.menu}</td><td class="num">${entry.toolbar}</td>`
+ `<td class="num">${entry.partial}</td></tr>`);
}
parts.push(`</tbody></table></div>`);
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 = [`<h3 id="panel-catalog">5.4 全部功能面板(生成)</h3>`,
`<p class="muted">共 ${rows.length} 个停靠/任务面板,按工作台分组;每行给出 React 实现位置、桌面参考与状态。</p>`];
for (const [moduleId, list] of [...byModule.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
parts.push(`<details class="card"><summary><strong>${esc(moduleId)}</strong> · ${list.length} 个面板</summary>${surfaceTable(list, "面板")}</details>`);
}
return parts.join("\n");
};
const renderModalCatalog = () => {
const rows = surfaces.filter(surface => surface.category === "modal-dialog");
return `<h3 id="modal-catalog">5.5 模态对话框与覆盖层(生成)</h3>\n${surfaceTable(rows, "对话框")}`;
};
const renderPreferencesCatalog = () => {
const rows = surfaces.filter(surface => surface.category === "preferences-page");
return `<h3 id="prefs-catalog">5.6 偏好设置页(生成)</h3>\n${surfaceTable(rows, "偏好页")}`;
};
const renderImplementationMapping = () => {
const parts = [`<h3 id="implementation-mapping">10.1 界面 → React 实现 → 桌面源码全量映射(生成)</h3>`,
`<p class="muted">共 ${surfaces.length} 个 UI 表面。状态口径:<span class="ok">已实现</span> owner 存在且被挂载;<span class="warn">部分</span> 组件存在但未挂载或工作台需前置条件;<span class="bad">缺口</span> 桌面有而 Web 无;<span class="bad">边界</span> 内核能力不支持。</p>`];
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(`<h4>${esc(category)}(${rows.length})</h4>`);
parts.push(surfaceTable(rows));
}
return parts.join("\n");
};
const renderGapRegister = () => {
const rows = surfaces.filter(surface => surface.status === "gap" || surface.status === "partial");
const parts = [`<h3 id="gap-register">10.2 缺口登记(生成)</h3>`];
if (!rows.length) {
parts.push(`<p class="note">当前没有登记中的 UI 缺口;所有表面均已实现或已标注为边界。</p>`);
} else {
parts.push(`<p class="muted">共 ${rows.length} 项待处理或部分实现。</p>`, 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(`<h2 id="appendix-commands" class="anchor">附录 · 命令矩阵(${inventory.appendix.length} 条)</h2>`);
appendixParts.push(`<p class="muted">来源 <code>web/public/api/workbench-command-matrix.json</code>。处置含义:<span class="ok">原生</span> 有完整内核处理;<span class="warn">受限</span> 只部分实现或依赖桌面能力;<span class="bad">未实现</span> 无处理。</p>`);
// 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(`<details><summary><strong>${esc(module)}</strong> · ${rows.length} 条</summary><div class="table-scroll"><table><thead><tr><th>命令</th><th>处置</th><th>受限类别</th><th>位置</th><th>名称</th><th>加速键</th><th>来源</th></tr></thead><tbody>`);
for (const row of rows) {
const command = commandMeta.get(row.id);
const where = placementById.get(row.id)?.map(item => item.where === "toolbar" ? "工具栏" : item.where === "menu" ? "菜单" : item.where).join(" / ") ?? "—";
const anchored = !anchoredCommands.has(row.id);
if (anchored) anchoredCommands.add(row.id);
appendixParts.push(`<tr data-appendix-row><td><code${anchored ? ` id="cmd-${esc(row.id)}"` : ""}>${esc(row.id)}</code></td><td>${dispositionBadge(row.disposition)}</td><td>${row.restrictionClass ? `<code>${esc(row.restrictionClass)}</code>` : "—"}</td><td>${esc(where)}</td>`
+ `<td>${esc(MENU_TEXT(command?.menuText || ""))}</td><td>${command?.accel ? `<kbd>${esc(command.accel)}</kbd>` : "—"}</td>`
+ `<td class="num">${esc(row.sourcePath ? `${row.sourcePath}:${row.sourceLine}` : "")}</td></tr>`);
}
appendixParts.push(`</tbody></table></div></details>`);
}
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 = `<h2 id="s-workbenches" class="anchor">逐工作台详解</h2>
<p class="lead">下面按工作台逐一列出:界面截图、工具栏按钮、菜单结构、任务面板与全部命令。状态徽标说明该工作台在主外壳中的可用性。</p>`;
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(/<h2 id="([^"]+)"[^>]*>([\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 = `<nav class="toc">
<strong>目录</strong>
${tocEntries.map(entry => entry.chapter
? ` <a class="sub" href="#${entry.id}">${esc(entry.text)}</a>`
: ` <a href="#${entry.id}">${esc(entry.text)}</a>`).join("\n")}
</nav>`;
html = html.replace(/<nav class="toc">[\s\S]*?<\/nav>/, tocHtml);
// A few styles the generated body relies on.
if (!html.includes("/* generated */")) {
html = html.replace("</style>", `/* 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}
</style>`);
}
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,
}));