#!/usr/bin/env node // Static UI inventory for the Web FreeCAD design document. // // No browser. Reads the generated manifests plus the module registry and the // task-panel sources, and emits one JSON file the doc builder turns into // chapters. Counts are cross-checked against features.json, so a drifted // registry fails here instead of producing a wrong document. // // node tools/fcweb/ui-inventory.mjs // node tools/fcweb/ui-inventory.mjs --out [--check] 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 checkOnly = args.includes("--check"); const PATHS = { manifest: path.join(repoRoot, "web/public/api/desktop-gui-manifest.json"), matrix: path.join(repoRoot, "web/public/api/workbench-command-matrix.json"), features: path.join(repoRoot, "web/teaching/data/features.json"), overrides: path.join(repoRoot, "docs/current/ui-design/data/workbench-overrides.json"), srcDir: path.join(repoRoot, "web/src"), out: path.resolve(argValue("--out", path.join(here, "out", "ui-inventory.json"))), }; function readJson(file) { if (!fs.existsSync(file)) fail(`missing input: ${file}`, 2); try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch (error) { fail(`malformed JSON in ${file}: ${error.message}`, 2); } } function fail(message, code) { console.error(`[ui-inventory] ${message}`); process.exit(code); } // ------------------------------------------------------------- inputs ---- const manifest = readJson(PATHS.manifest); const matrix = readJson(PATHS.matrix); const features = readJson(PATHS.features); const overrides = readJson(PATHS.overrides); const commandMeta = manifest.commandMetadata ?? {}; const manifestById = new Map(manifest.workbenches.map(wb => [wb.id, wb])); const featuresById = new Map(features.modules.map(module => [module.module, module])); // ------------------------------------------------------- task panels ---- const PREFIX_MODULE = [ ["reverseengineering", "ReverseEngineering"], ["templatepymod", "TemplatePyMod"], ["partdesign", "PartDesign"], ["spreadsheet", "Spreadsheet"], ["meshpart", "MeshPart"], ["part", "Part"], ["sketcher", "Sketcher"], ["techdraw", "TechDraw"], ["assembly", "Assembly"], ["inspection", "Inspection"], ["material", "Material"], ["measure", "Measure"], ["points", "Points"], ["surface", "Surface"], ["robot", "Robot"], ["import", "Import"], ["commanddoc", "Web"], ["sandbox", "Sandbox"], ["jtreader", "JtReader"], ["show", "Show"], ["plot", "Plot"], ["start", "Start"], ["help", "Help"], ["test", "Test"], ["tux", "Tux"], ["cam", "CAM"], ["fem", "Fem"], ["bim", "BIM"], ["draft", "Draft"], ["mesh", "Mesh"], ["web", "Web"], ["link", "Assembly"], ]; function moduleForFile(base) { const lower = base.toLowerCase(); for (const [prefix, module] of PREFIX_MODULE) { if (lower.startsWith(`${prefix}-`)) return module; } return "其他"; } function walk(dir, suffix, acc = []) { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const full = path.join(dir, entry.name); if (entry.isDirectory()) walk(full, suffix, acc); else if (entry.name.endsWith(suffix)) acc.push(full); } return acc; } const stripTags = text => text.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim(); function titlesOf(source) { const titles = []; const push = value => { const text = stripTags(value); if (text && !titles.includes(text)) titles.push(text); }; for (const match of source.matchAll(/<(h2|h3|legend)[^>]*>([\s\S]{0,160}?)<\/\1>/g)) push(match[2]); for (const match of source.matchAll(/<(section|dialog)[^>]*aria-label="([^"]{2,80})"/g)) push(match[2]); return titles.slice(0, 4); } const taskPanels = walk(PATHS.srcDir, "-task.tsx").map(file => { const base = path.basename(file); return { file: path.relative(PATHS.srcDir, file), module: moduleForFile(base), titles: titlesOf(fs.readFileSync(file, "utf8")), }; }).sort((a, b) => a.file.localeCompare(b.file)); const panelsByModule = new Map(); for (const panel of taskPanels) { if (!panelsByModule.has(panel.module)) panelsByModule.set(panel.module, []); panelsByModule.get(panel.module).push(panel); } // ------------------------------------------------------------- matrix ---- const matrixByModule = new Map(); const appendixRows = []; // OpenSCAD is not implemented on the web (project iron rule): it must not // appear in any generated surface, including this document's appendix. const excludedCommands = []; for (const record of matrix.records ?? []) { if (record.module === "OpenSCAD" || /^openscad[._]/i.test(record.command)) { excludedCommands.push(record.command); continue; } if (!matrixByModule.has(record.module)) matrixByModule.set(record.module, { native: 0, restricted: 0, other: 0, commands: [] }); const bucket = matrixByModule.get(record.module); if (record.disposition === "native_handler") bucket.native += 1; else if (record.disposition === "restricted") bucket.restricted += 1; else bucket.other += 1; bucket.commands.push(record.command); appendixRows.push({ id: record.command, module: record.module, disposition: record.disposition, restrictionClass: record.restrictionClass ?? null, kind: record.kind, sourcePath: record.sourcePath, sourceLine: record.sourceLine, uiSurfaces: (record.uiSurfaces ?? []).map(surface => surface.kind), reason: record.capabilityReason ?? "", }); } appendixRows.sort((a, b) => a.module.localeCompare(b.module) || a.id.localeCompare(b.id)); // --------------------------------------------------------- placements ---- // command id -> [{workbench, where}] built from the desktop manifest. const placementByCommand = new Map(); function notePlacement(command, workbench, where) { if (!placementByCommand.has(command)) placementByCommand.set(command, []); const list = placementByCommand.get(command); if (!list.some(item => item.workbench === workbench && item.where === where)) { list.push({ workbench, where }); } } function flattenMenuItems(items, workbench, menuLabel, trail = []) { for (const item of items ?? []) { if (item.type === "command") notePlacement(item.id, workbench, `菜单 ${menuLabel}${trail.length ? " › " + trail.join(" › ") : ""}`); else if (item.type === "submenu") flattenMenuItems(item.items, workbench, menuLabel, [...trail, item.label ?? "子菜单"]); } } for (const wb of manifest.workbenches) { for (const menu of wb.menus ?? []) flattenMenuItems(menu.items, wb.id, menu.label); for (const toolbar of wb.toolbars ?? []) { for (const command of toolbar.items ?? []) notePlacement(command, wb.id, `工具栏 ${toolbar.name}`); } } // ---------------------------------------------------------- chapters ---- const normalizeMenu = items => (items ?? []).map(item => { if (item.type === "command") return { kind: "command", id: item.id }; if (item.type === "separator") return { kind: "separator" }; if (item.type === "submenu") return { kind: "submenu", label: item.label ?? "", items: normalizeMenu(item.items) }; return { kind: "unknown" }; }); const chapters = []; for (const override of overrides.workbenches) { // manifest-only workbenches (currently OpenSCAD) are excluded from the Web // document entirely; the exclusion is stated once in the workbench intro. if (override.status === "manifest-only") continue; const id = override.id; const wb = manifestById.get(id) ?? null; const module = featuresById.get(id) ?? null; const bucket = matrixByModule.get(id) ?? null; const meta = commandMeta; const commands = []; const seen = new Set(); for (const toolbar of wb?.toolbars ?? []) { for (const command of toolbar.items ?? []) { if (seen.has(command)) continue; seen.add(command); commands.push({ id: command, placement: "toolbar", menuText: meta[command]?.menuText ?? "", toolTip: meta[command]?.toolTip ?? "", accel: meta[command]?.accel ?? "", icon: meta[command]?.icon ?? "", }); } } for (const placement of placementByCommand.entries()) { const [command, places] = placement; if (!places.some(place => place.workbench === id)) continue; if (seen.has(command)) continue; seen.add(command); commands.push({ id: command, placement: places.find(place => place.workbench === id)?.where?.startsWith("菜单") ? "menu" : "other", menuText: meta[command]?.menuText ?? "", toolTip: meta[command]?.toolTip ?? "", accel: meta[command]?.accel ?? "", icon: meta[command]?.icon ?? "", }); } chapters.push({ id, title: override.title ?? id, summary: override.summary ?? "", status: override.status, fallbackTo: override.fallbackTo ?? null, reason: override.reason ?? null, inSelect: override.status !== "manifest-only" && override.status !== "unreachable", manifest: wb ? { source: wb.source, docks: wb.docks ?? [] } : null, counts: { webCommands: module?.commandCount ?? null, pythonApi: module?.pythonApiCount ?? null, objectTypes: module?.objectTypeCount ?? null, guiDependency: module?.guiDependency ?? null, formats: module?.formats ?? [], probeBytes: module?.probeBytes ?? null, pages: (features.pageMap ?? []).filter(row => row.module === id).map(row => row.page), matrixNative: bucket?.native ?? 0, matrixRestricted: bucket?.restricted ?? 0, toolbarSlots: (wb?.toolbars ?? []).reduce((sum, toolbar) => sum + (toolbar.items?.length ?? 0), 0), menuCommands: commands.filter(command => command.placement === "menu").length, }, toolbars: (wb?.toolbars ?? []).map(toolbar => ({ name: toolbar.name, items: toolbar.items ?? [] })), menus: (wb?.menus ?? []).map(menu => ({ label: menu.label, items: normalizeMenu(menu.items) })), commands, taskPanels: (panelsByModule.get(id) ?? []).map(panel => ({ file: panel.file, titles: panel.titles })), }); } // ------------------------------------------------------------- totals ---- const totals = { chapters: chapters.length, webModules: features.moduleCount, webCommands: features.commandCount, pythonApi: features.pythonApiCount, objectTypes: features.objectTypeCount, manifestWorkbenches: manifest.workbenchCount ?? manifest.workbenches.length, manifestCommands: Object.keys(commandMeta).length, matrixRecords: matrix.recordCount ?? appendixRows.length, matrixDispositions: matrix.dispositionCounts ?? null, taskPanelFiles: taskPanels.length, appendixRows: appendixRows.length, excludedOpenScad: excludedCommands.length, }; // -------------------------------------------------------- validation ---- const problems = []; if (features.moduleCount !== features.modules.length) { problems.push(`features.moduleCount ${features.moduleCount} != modules[] ${features.modules.length}`); } for (const chapter of chapters) { const module = featuresById.get(chapter.id); if (!module) continue; if (chapter.counts.webCommands !== module.commandCount) problems.push(`${chapter.id}: webCommands ${chapter.counts.webCommands} != ${module.commandCount}`); if (chapter.counts.pythonApi !== module.pythonApiCount) problems.push(`${chapter.id}: pythonApi ${chapter.counts.pythonApi} != ${module.pythonApiCount}`); if (chapter.counts.objectTypes !== module.objectTypeCount) problems.push(`${chapter.id}: objectTypes ${chapter.counts.objectTypes} != ${module.objectTypeCount}`); } const chapterIds = new Set(chapters.map(chapter => chapter.id)); for (const module of features.modules) { if (!chapterIds.has(module.module)) problems.push(`module ${module.module} has no chapter`); } if ((matrix.recordCount ?? appendixRows.length) !== appendixRows.length + excludedCommands.length) { problems.push(`appendix ${appendixRows.length} + excluded ${excludedCommands.length} != matrix.recordCount ${matrix.recordCount}`); } if (appendixRows.some(row => row.module === "OpenSCAD" || /^openscad[._]/i.test(row.id))) { problems.push("OpenSCAD commands leaked into the appendix"); } if (problems.length) { console.error(`[ui-inventory] ${problems.length} consistency problem(s):`); for (const problem of problems.slice(0, 20)) console.error(` - ${problem}`); process.exit(1); } const inventory = { schema: "freecad-web/ui-inventory/v1", totals, taskPanelTotals: Object.fromEntries([...panelsByModule.entries()].map(([module, list]) => [module, list.length]).sort()), chapters, appendix: appendixRows, }; const json = `${JSON.stringify(inventory, null, 2)}\n`; fs.mkdirSync(path.dirname(PATHS.out), { recursive: true }); if (checkOnly) { if (!fs.existsSync(PATHS.out)) fail(`--check: no inventory at ${PATHS.out}`, 1); const previous = fs.readFileSync(PATHS.out, "utf8"); if (previous !== json) fail("--check: inventory is stale; re-run without --check", 1); console.log(JSON.stringify({ ok: true, checked: PATHS.out, totals })); process.exit(0); } fs.writeFileSync(PATHS.out, json); console.log(JSON.stringify({ ok: true, out: PATHS.out, totals }, null, 2));