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>
This commit is contained in:
2026-11-23 01:30:31 +08:00
parent 3c2c623f70
commit 300c8efb01
180 changed files with 27036 additions and 4185 deletions

125
tools/fcweb/README.md Normal file
View File

@@ -0,0 +1,125 @@
# fcweb — 建零件与装配的通用工具库
把二级减速器教程里反复出现的建零件、建装配机制收成一层可复用的内核客户端。
不依赖任何案例目录,自带自检门。
```js
import { openPart, openPartDesign, openAssembly } from "<repo>/tools/fcweb/index.mjs";
```
完整中文指南:`web/teaching/fcweb-toolkit.html`
## 目录
| 文件 | 作用 |
| --- | --- |
| `index.mjs` | 统一出口;含旧接口适配器 `openPartLegacy` |
| `kernel.mjs` | 唯一的 `ccall` 触点:探针定位、会话、trace |
| `part.mjs` | `part.document` — 图元、布尔、定位、导入导出 |
| `partdesign.mjs` | `partdesign.document` — Body、草图、Pad/Pocket、齿轮 |
| `assembly.mjs` | `assembly.*` — 装配对象、原生插入链接、求解 |
| `opfs.mjs` | OPFS 契约(目录 `freecad-exports`,根可配置) |
| `capture.mjs` | Chromium 启动、截图、页面健康检查 |
| `selftest.mjs` | 内核自检门,32 项,无浏览器无 fixture |
| `ui-inventory.mjs` | UI 静态清单:工作台、菜单、工具栏、任务面板、命令矩阵 |
| `ui-capture.mjs` | 逐工作台驱动外壳并截图 |
| `build-ui-doc.mjs` | 由清单与截图汇编 UI 设计文档 |
## 探针
| 命令族 | 探针产物 |
| --- | --- |
| `part.document` | `FreeCADWebDocumentProbe` |
| `partdesign.document` | `FreeCADWebPartDesignRuntimeProbe` |
| `assembly.*` | `FreeCADWebAssemblyProbe` |
第三个的名字和源码文件名(`AssemblyRuntimeProbe.cpp`)不一致——源码里
`AssemblyRuntimeProbe.cpp:642` 定义命令,但 `CMakeLists.txt:798` 把它编进
`FreeCADWebAssemblyProbe`。
探针优先从 `web/public/kernel` 取,其次 `web/dist/kernel`。两处产物不一致时打警告。
## 快速例子
```js
import { openPart, openPartDesign, openAssembly, storeRoot } from "./index.mjs";
// 零件
const part = await openPart("Block");
try {
part.create();
part.box("Base", { length: 40, width: 30, height: 10 });
part.primitive("Bore", { kind: "Cylinder",
parameters: { Radius: 5, Height: 30, Angle: 360, FirstAngle: 0, SecondAngle: 0 },
placement: { position: [20, 15, -10] } });
part.cut({ object: "Bored", base: "Base", tool: "Bore" });
part.saveDocument();
} finally {
try { part.close(); } catch {}
part.dispose();
}
// 装配
const asm = await openAssembly({ document: "Asm", label: "总装" });
try {
asm.create();
asm.insertLinks([{ file: `${storeRoot()}/Block.FCStd`,
sourceDocument: "Block", sourceObject: "Base", position: [0, 0, 0] }]);
asm.solve();
} finally {
asm.dispose();
}
```
## 契约要点
- **图元参数键不同**:Part 用 `primitive`,PartDesign 用 `primitiveType`;
Part 位置用 `primitivePlacement`,PartDesign 用 `position: [x,y,z]`。
- **`volume` 可为 `null`**:草图、基准、2D 齿轮轮廓没有体积。
- **编辑动作回复不带几何**:`volumeOf` / `objectOf` 内部走 `snapshot`。
- **内核 `/tmp` 是 MEMFS**:导出暂存与读取都用 `part.kernel.FS`。
- **`close()` ≠ `dispose()`**:前者关文档,后者终止 pthread 池;后者必须调用,
否则 Node 不退出;且不可在会话中途调用。
## UI 设计文档管线
三个工具把「界面清单 → 实拍截图 → HTML 文档」串起来:
```bash
# 1. 静态清单(无浏览器):31 模块 / 746 命令元数据 / 144 任务面板 / 1492 条矩阵
node tools/fcweb/ui-inventory.mjs
# 2. 逐工作台截图(需先启动应用:web/ 下 npx vite preview --port 5182)
node tools/fcweb/ui-capture.mjs --all
node tools/fcweb/ui-capture.mjs --only Part,Fem --headed # 单个排查
# 3. 汇编文档
node tools/fcweb/build-ui-doc.mjs # 生成 docs/current/web-freecad-ui-layout-and-functions.html
node tools/fcweb/build-ui-doc.mjs --check # 幂等性检查
```
- 工作台状态(可渲染 / 回退 / 不可达 / 需前置条件)由 `docs/current/ui-design/data/workbench-overrides.json` 统一维护;矩阵里出现的 OpenSCAD 命令一律排除。
- 手写正文章节在 `docs/current/ui-design/source.html`,构建只替换三个占位符,重复构建字节一致。
- 校验:`node web/tools/manual/check-ui-design-doc.mjs`(两个视口、零溢出、零断图、零重复 id、附录行数匹配)。
## 自检
```bash
node tools/fcweb/selftest.mjs
node tools/fcweb/selftest.mjs --json tools/fcweb/out/selftest.json
```
失败即非零退出,报告写到 `tools/fcweb/out/selftest.json`。
## 迁移既有案例
旧案例用的是 `web/teaching/cases/secondary-reducer-pro/parts/buildPart.mjs` 的
`openPart(document, {snapshots})`,返回 `{document, kernel, call, timed, timings, trace}`。
本库的 `openPartLegacy(document, options)` 返回同样的形状:
```diff
- import { openPart } from "./buildPart.mjs";
+ import { openPartLegacy as openPart } from "<repo>/tools/fcweb/index.mjs";
```
现有案例脚本**未**改动;迁移是逐案决定的事。

200
tools/fcweb/assembly.mjs Normal file
View File

@@ -0,0 +1,200 @@
// Assembly client: create an Assembly::AssemblyObject, insert linked
// components, solve, export.
//
// Served by `FreeCADWebAssemblyProbe` -- AssemblyRuntimeProbe.cpp compiles into
// that executable (CMakeLists.txt:798); the artifact name does not match the
// source file name.
//
// Two dispatch families:
// assembly.createRecompute { documentName, objectName, objectType, label }
// assembly.pythonFamily { tier, records:[{apiId, args}] }
//
// The insertion flow is native and headless (AssemblyInsertLink.h):
// open -- stage each source FCStd into the kernel FS (/tmp/assembly-links)
// begin -- start an insertion session on the target assembly
// insert -- one component at a time, with position + quaternion
// accept -- commit the session
// Desktop refuses to link into an unsaved document, so the target gets a
// staging path up front; that is what keeps App::Link relative paths sane.
import fs from "node:fs";
import path from "node:path";
import {
STEM_ASSEMBLY, KernelError, openKernel, dispatch,
} from "./kernel.mjs";
import { storeBytes } from "./opfs.mjs";
export const ASSEMBLY_OBJECT_TYPE = "Assembly::AssemblyObject";
const ASSEMBLY_SCHEMA = "freecad-web-assembly/create-recompute/v1";
function requireString(value, what) {
if (typeof value !== "string" || !value.trim()) {
throw new KernelError(`${what} is required`, { code: "bad_request" });
}
return value;
}
function quaternion(value, fallback = [0, 0, 0, 1], what = "rotation") {
if (value == null) return fallback;
if (!Array.isArray(value) || value.length !== 4 || value.some(item => typeof item !== "number" || !Number.isFinite(item))) {
throw new KernelError(`${what} must be a 4-number quaternion (got ${JSON.stringify(value)})`, { code: "bad_vector" });
}
return value;
}
function position3(value, fallback = [0, 0, 0], what = "position") {
if (value == null) return fallback;
if (!Array.isArray(value) || value.length !== 3 || value.some(item => typeof item !== "number" || !Number.isFinite(item))) {
throw new KernelError(`${what} must be a 3-number array (got ${JSON.stringify(value)})`, { code: "bad_vector" });
}
return value;
}
export class AssemblySession {
constructor(handle, { document, assembly, label }) {
this.handle = handle;
this.kernel = handle.kernel;
this.document = document;
this.assembly = assembly;
this.label = label;
this.timings = [];
this.events = [];
this.lastResult = null;
}
/** Raw call, unwrapping the pythonFamily envelope for record-shaped replies. */
dispatch(cmd, args) {
const reply = dispatch(this.handle, cmd, args);
if (!reply || reply.ok === false) {
throw new KernelError(`${this.document} ${cmd}: ${reply?.error ?? "kernel rejected the call"}`,
{ code: reply?.code ?? null, action: cmd, reply });
}
return reply;
}
/** Send one `Assembly:desktop:*` command through assembly.pythonFamily. */
command(apiId, args = {}, { tier = "tier-1-readonly" } = {}) {
const reply = this.dispatch("assembly.pythonFamily", {
tier,
records: [{ apiId: `Assembly:desktop:${apiId}`, name: apiId, family: "assembly", args }],
});
const record = (reply.records ?? []).find(item => item?.apiId === `Assembly:desktop:${apiId}`) ?? reply.records?.[0];
if (!record) throw new KernelError(`${apiId}: no record in reply`, { code: "bad_reply", action: apiId, reply });
if (record.status !== "exposed") {
throw new KernelError(`${apiId}: ${record.message ?? record.status}`, {
code: record.code ?? record.status, action: apiId, reply,
});
}
this.lastResult = record.result ?? null;
return this.lastResult;
}
create() {
const reply = this.dispatch("assembly.createRecompute", {
documentName: this.document,
objectName: this.assembly,
objectType: ASSEMBLY_OBJECT_TYPE,
label: this.label,
});
if (reply.ok === false) {
throw new KernelError(`${this.document} create assembly: ${reply.error ?? "failed"}`, { code: reply.code ?? null, reply });
}
this.lastResult = reply;
return reply;
}
componentCount() {
return this.lastResult?.object?.componentCount ?? null;
}
/**
* Insert components. Each item is
* { file: "<name>.FCStd", sourceDocument, sourceObject, position, rotation, rigid }
* and `file` must be readable on the host; its bytes are staged into the
* kernel before the session opens, because the native flow reads them from
* /tmp/assembly-links.
*/
insertLinks(items, { groundFirst = true } = {}) {
if (!Array.isArray(items) || items.length === 0) {
throw new KernelError("insertLinks requires a non-empty items array", { code: "bad_request" });
}
const files = new Map();
for (const item of items) {
requireString(item.file, "item.file");
requireString(item.sourceDocument, "item.sourceDocument");
requireString(item.sourceObject, "item.sourceObject");
const key = path.basename(item.file);
if (!files.has(key)) {
const bytes = fs.readFileSync(item.file);
files.set(key, { fileName: key, contentBase64: bytes.toString("base64") });
}
}
const base = { documentId: this.document, assembly: this.assembly };
// 1. Stage the source documents inside the kernel FS.
this.command("Assembly_InsertLink", { ...base, action: "open", files: [...files.values()] });
// 2. Start the insertion session.
this.command("Assembly_InsertLink", { ...base, action: "begin" });
// 3. Insert one component at a time.
const inserted = [];
for (const [index, item] of items.entries()) {
const result = this.command("Assembly_InsertLink", {
...base,
action: "insert",
sourceDocument: item.sourceDocument,
sourceObject: item.sourceObject,
position: position3(item.position),
rotation: quaternion(item.rotation),
rigid: item.rigid !== false,
groundFirst: groundFirst && index === 0,
});
inserted.push({
file: path.basename(item.file),
sourceDocument: item.sourceDocument,
sourceObject: item.sourceObject,
position: position3(item.position),
rotation: quaternion(item.rotation),
result,
});
}
// 4. Commit.
const accepted = this.command("Assembly_InsertLink", { ...base, action: "accept" });
return { inserted, accepted };
}
solve() {
return this.command("Assembly_SolveAssembly", { documentId: this.document, assembly: this.assembly });
}
exportASMT({ name } = {}) {
const result = this.command("Assembly_ExportASMT", { documentId: this.document, assembly: this.assembly });
const encoded = result?.content ?? result?.base64 ?? null;
if (!encoded) return { ...result, bytes: 0, stored: null };
const bytes = Buffer.from(String(encoded), "base64");
return { ...result, bytes: bytes.byteLength, stored: storeBytes(name ?? `${this.document}.asmt`, bytes) };
}
bom() {
return this.command("Assembly_CreateBom", { documentId: this.document, assembly: this.assembly });
}
trace() {
return {
schema: "freecad-web-process-trace/v1",
document: this.document,
builder: "assembly",
totals: { steps: this.events.length, timings: this.timings },
events: this.events,
};
}
}
export async function openAssembly({ document, assembly = "Assembly", label = "Assembly", kernelDirs, print, printErr } = {}) {
requireString(document, "document");
const handle = await openKernel({ stem: STEM_ASSEMBLY, dirs: kernelDirs, print, printErr });
const session = new AssemblySession(handle, { document, assembly, label });
session.dispose = () => handle.close();
return session;
}

View File

@@ -0,0 +1,480 @@
#!/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,
}));

127
tools/fcweb/capture.mjs Normal file
View File

@@ -0,0 +1,127 @@
// Browser capture helpers: launch Chromium, walk a page, assert it is healthy.
//
// This module deliberately touches neither the kernel nor OPFS. It takes
// already-projected mesh data and already-written files, so the kernel selftest
// can stay browser-free while the guide checker reuses the same primitives.
//
// The browser dependency (playwright) lives in web/node_modules, so the require
// is resolved from there rather than from the host's global module path.
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 repoRoot = path.resolve(here, "../..");
const require = createRequire(path.join(repoRoot, "web", "package.json"));
export const DEFAULT_CHROME = process.env.FREECAD_CHROME || "/usr/bin/google-chrome";
/** Launch Chromium with the flags this project already needs. */
export async function launchBrowser({ headed = false, executablePath = DEFAULT_CHROME } = {}) {
const { chromium } = require("playwright");
return chromium.launch({
executablePath,
headless: !headed,
args: ["--no-sandbox", "--disable-dev-shm-usage"],
});
}
/**
* Open a page and start collecting everything a check needs to judge it.
* Returns { page, errors, consoleErrors, failedRequests }.
*/
export async function openPage(browser, url, { viewport = { width: 1440, height: 900 } } = {}) {
const page = await browser.newPage({ viewport });
const errors = [];
const consoleErrors = [];
const failedRequests = [];
page.on("pageerror", error => errors.push(String(error)));
page.on("console", message => { if (message.type() === "error") consoleErrors.push(message.text()); });
page.on("requestfailed", request => failedRequests.push(`${request.url()} ${request.failure()?.errorText ?? ""}`));
const response = await page.goto(url, { waitUntil: "networkidle" });
return { page, response, errors, consoleErrors, failedRequests };
}
export async function screenshot(page, { file, fullPage = false, locator } = {}) {
fs.mkdirSync(path.dirname(file), { recursive: true });
if (locator) await page.locator(locator).screenshot({ path: file });
else await page.screenshot({ path: file, fullPage });
return { file, bytes: fs.statSync(file).size };
}
/**
* Structural health check of a served page at one or more viewports.
*
* `expect.chapters` is the number of content files the page should have
* rendered; `expect.anchorIds` are ids that must resolve. Everything is
* measured in the page, so a missing element or a broken image is reported
* rather than thrown.
*/
export async function pageCheck(browser, url, { viewports = [{ width: 1440, height: 900 }], expect = {} } = {}) {
const reports = [];
for (const viewport of viewports) {
const { page, response, errors, consoleErrors, failedRequests } = await openPage(browser, url, { viewport });
try {
const dom = await page.evaluate(() => {
// An <img> with no src is a placeholder (the shared manual template
// ships one as its lightbox target), not a broken image.
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 overflow = Math.max(0, doc.scrollWidth - doc.clientWidth);
const ids = [...document.querySelectorAll("[id]")].map(node => node.id);
return {
brokenImages,
overflow,
ids,
title: document.title,
chapterCount: document.querySelectorAll("main section, main article").length,
headings: [...document.querySelectorAll("h1, h2")].map(node => node.id || node.textContent.trim().slice(0, 40)),
};
});
const missingIds = (expect.anchorIds ?? []).filter(id => !dom.ids.includes(id));
reports.push({
viewport,
status: response?.status() ?? null,
...dom,
missingIds,
pageErrors: errors,
consoleErrors,
failedRequests,
ok: (response?.status() ?? 0) === 200
&& errors.length === 0
&& failedRequests.length === 0
&& dom.brokenImages.length === 0
&& dom.overflow === 0
&& missingIds.length === 0
&& (expect.chapters == null || dom.chapterCount >= expect.chapters),
});
} finally {
await page.close();
}
}
return { url, viewports: reports, ok: reports.every(item => item.ok) };
}
/** Mesh projection shared with the viewer: already-rounded positions + normals. */
export function projectMesh(objects) {
return (objects ?? []).map(item => ({
name: item.name,
label: item.label ?? item.name,
volume: item.volume ?? null,
positions: item.positions ?? [],
normals: item.normals ?? [],
triangleCount: item.triangleCount ?? (item.positions ?? []).length / 9,
}));
}
export function writeArtifact(dir, name, value) {
fs.mkdirSync(dir, { recursive: true });
const file = path.join(dir, name);
const text = typeof value === "string" ? value : JSON.stringify(value, null, 2);
fs.writeFileSync(file, text);
return { file, bytes: fs.statSync(file).size };
}

76
tools/fcweb/index.mjs Normal file
View File

@@ -0,0 +1,76 @@
// fcweb toolkit -- one import for part, part-design, assembly and capture work.
//
// import { openPart } from "<repo>/tools/fcweb/index.mjs";
//
// See README.md for the full surface and the contract notes that matter
// (primitive argument keys differ between the two probes; volume is null for
// sketches and datums; kernel artifacts live in MEMFS, not on the host).
export {
KernelError,
TRACE_SCHEMA,
STEM_PART,
STEM_PARTDESIGN,
STEM_ASSEMBLY,
KERNEL_DIRS,
locateProbe,
openKernel,
dispatch,
createSession,
compactArgs,
summarise,
writeTrace,
} from "./kernel.mjs";
export { openPart, PartDocument, PART_SCHEMA, PART_MODULE, hostBytes } from "./part.mjs";
export { openPartDesign, PartDesignDocument, PARTDESIGN_SCHEMA, PARTDESIGN_MODULE } from "./partdesign.mjs";
export { openAssembly, AssemblySession, ASSEMBLY_OBJECT_TYPE } from "./assembly.mjs";
export {
EXPORT_DIRECTORY,
DEFAULT_ROOT,
configureOpfs,
storeRoot,
safeName,
writeExportFile,
readExportFile,
hasExportFile,
listExportFiles,
storeBytes,
evidence,
sha256,
outRoot,
} from "./opfs.mjs";
export {
DEFAULT_CHROME,
launchBrowser,
openPage,
screenshot,
pageCheck,
projectMesh,
writeArtifact,
} from "./capture.mjs";
/**
* Adapter for scripts written against the old case-local helper
* (`web/teaching/cases/secondary-reducer-pro/parts/buildPart.mjs`).
* It returns the exact shape those scripts destructure, so migrating a case is
* an import swap rather than a rewrite.
*/
export async function openPartLegacy(document, options = {}) {
const { openPart } = await import("./part.mjs");
const part = await openPart(document, options);
return {
document,
kernel: part.kernel,
call: part.call,
timed: part.timed,
timings: part.timings,
trace: {
events: part.events,
record: () => { /* legacy callers record through `timed` */ },
finish: extra => ({ ...part.trace(), ...extra }),
},
close: () => part.dispose(),
};
}

243
tools/fcweb/kernel.mjs Normal file
View File

@@ -0,0 +1,243 @@
// Kernel access for the fcweb toolkit.
//
// Every probe is an Emscripten build exposing one entry point:
// fc_web_dispatch_json(requestJson) -> responseJson
// where the request is `{ cmd, args }`. This module is the only place that
// touches ccall; everything else speaks in actions.
//
// Three probes matter here:
// FreeCADWebDocumentProbe cmd "part.document"
// FreeCADWebPartDesignRuntimeProbe cmd "partdesign.document"
// FreeCADWebAssemblyProbe cmd "assembly.*"
// (AssemblyRuntimeProbe.cpp compiles into
// this target, see CMakeLists.txt:798 --
// the file name is not the artifact name)
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { fileURLToPath, pathToFileURL } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(here, "../..");
/** Warn once per stem about public/dist drift. */
const warned = new Set();
export const TRACE_SCHEMA = "freecad-web-process-trace/v1";
export const STEM_PART = "FreeCADWebDocumentProbe";
export const STEM_PARTDESIGN = "FreeCADWebPartDesignRuntimeProbe";
export const STEM_ASSEMBLY = "FreeCADWebAssemblyProbe";
export const KERNEL_DIRS = [
path.join(repoRoot, "web", "public", "kernel"),
path.join(repoRoot, "web", "dist", "kernel"),
];
/** A kernel reply that came back with ok:false, or a transport failure. */
export class KernelError extends Error {
constructor(message, { code = null, action = null, stage = null, reply = null } = {}) {
super(message);
this.name = "KernelError";
this.code = code;
this.action = action;
this.stage = stage;
this.reply = reply;
}
}
function artifactsIn(directory, stem) {
const js = path.join(directory, `${stem}.js`);
const wasm = path.join(directory, `${stem}.wasm`);
return fs.existsSync(js) && fs.existsSync(wasm) ? { js, wasm } : null;
}
function statKey(file) {
const stats = fs.statSync(file);
return `${stats.size}:${Math.round(stats.mtimeMs)}`;
}
/**
* Find the first kernel directory that ships both the .js and .wasm for `stem`.
* public/ and dist/ can drift (different build times), so the chosen directory
* and a freshness key are reported and a mismatch is warned about rather than
* silently picked.
*/
export function locateProbe(stem, dirs = KERNEL_DIRS) {
const found = [];
for (const directory of dirs) {
const artifacts = artifactsIn(directory, stem);
if (artifacts) found.push({ directory, ...artifacts });
}
if (!found.length) {
throw new KernelError(`no ${stem}.{js,wasm} under ${dirs.join(" or ")}`, { code: "probe_missing" });
}
const chosen = found[0];
const keys = new Set(found.map(entry => statKey(entry.js)));
if (keys.size > 1 && !warned.has(stem)) {
warned.add(stem);
console.warn(`[fcweb] ${stem} differs between kernel directories: ` +
found.map(entry => `${path.relative(repoRoot, entry.directory)}=${statKey(entry.js)}`).join(", "));
}
return { ...chosen, copies: found.length, buildKey: statKey(chosen.js) };
}
/**
* Instantiate one probe. Always pair with `handle.close()` in a finally block:
* the probes are pthread builds, and without terminating them Node's event loop
* never drains.
*/
export async function openKernel({ stem, dirs = KERNEL_DIRS, print = () => {}, printErr = () => {} } = {}) {
if (!stem) throw new KernelError("openKernel requires { stem }", { code: "bad_request" });
const located = locateProbe(stem, dirs);
const { loadWasmProbe } = await import(pathToFileURL(path.join(repoRoot, "tools", "wasm-probe-runtime.mjs")).href);
const { kernel } = await loadWasmProbe(located.directory, stem, { print, printErr });
let closed = false;
const handle = {
kernel,
stem,
directory: located.directory,
buildKey: located.buildKey,
copies: located.copies,
get closed() { return closed; },
/** Idempotent: terminate the pthread pool exactly once. */
close() {
if (closed) return;
closed = true;
try { kernel.PThread?.terminateAllThreads(); } catch { /* pool already gone */ }
},
};
return handle;
}
/** Raw JSON round-trip. Returns the parsed reply without judging ok. */
export function dispatch(handle, cmd, args) {
if (!handle || handle.closed) throw new KernelError("kernel handle is closed", { code: "closed" });
const request = JSON.stringify({ cmd, args });
const text = handle.kernel.ccall("fc_web_dispatch_json", "string", ["string"], [request]);
try {
return JSON.parse(String(text));
} catch {
throw new KernelError(`${cmd}: reply was not JSON (${String(text).slice(0, 160)})`, { code: "bad_reply" });
}
}
/** Drop the heavy geometry arrays a trace must not carry. */
export function compactArgs(args) {
const clone = { ...args };
delete clone.includeMesh;
delete clone.schema;
delete clone.module;
delete clone.document;
for (const key of ["geometries", "constraints"]) {
if (Array.isArray(clone[key])) {
clone[key] = { count: clone[key].length, sha256: digest(clone[key]) };
}
}
delete clone.mesh;
return clone;
}
function digest(value) {
return createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 16);
}
/** Keep only the drawable facts of a reply for the trace. */
export function summarise(response) {
const objects = response?.objects ?? [];
return {
objectCount: response?.objectCount ?? objects.length,
tip: objects.length ? objects[objects.length - 1].name : null,
objects: objects.map(object => ({
name: object.name,
label: object.label,
type: object.type,
position: object.position,
volume: object.volume ?? null,
faceCount: object.faceCount ?? null,
edgeCount: object.edgeCount ?? null,
vertexCount: object.vertexCount ?? null,
})),
};
}
/**
* A document session over one kernel handle.
*
* `call` injects the schema/module/document header every probe expects and
* throws on ok:false. `timed` additionally records a trace event, which is what
* makes a build replayable later without re-running it.
*/
export function createSession({ handle, cmd, schema, module, document, extra = {} }) {
const timings = [];
const events = [];
let last = null;
const call = (action, args = {}) => {
const reply = dispatch(handle, cmd, { schema, module, document, action, includeMesh: false, ...extra, ...args });
if (!reply || reply.ok === false) {
throw new KernelError(
`${document} ${action}: ${reply?.error ?? "kernel rejected the call"}`,
{ code: reply?.code ?? null, action, stage: reply?.stage ?? null, reply },
);
}
last = reply.result;
return reply.result;
};
const timed = (label, action, args = {}) => {
const started = performance.now();
const result = call(action, args);
const seconds = (performance.now() - started) / 1000;
timings.push({ label, action, seconds });
events.push({
step: events.length + 1,
label,
action,
args: compactArgs(args),
seconds: Number(seconds.toFixed(4)),
tips: summarise(result),
});
return result;
};
const session = {
document,
cmd,
schema,
module,
kernel: handle.kernel,
handle,
call,
timed,
timings,
events,
get last() { return last; },
trace() {
return {
schema: TRACE_SCHEMA,
document,
builder: extra.builder ?? null,
totals: {
seconds: Number(timings.reduce((sum, item) => sum + item.seconds, 0).toFixed(3)),
steps: events.length,
timings,
},
events,
};
},
};
return session;
}
/** Write a session trace through the OPFS contract and mirror it on disk. */
export async function writeTrace(session, { extra = {} } = {}) {
const { storeBytes, outRoot } = await import(pathToFileURL(path.join(here, "opfs.mjs")).href);
const trace = { ...session.trace(), ...extra };
const json = JSON.stringify(trace, null, 2);
const stored = storeBytes(`trace-${session.document}.json`, json);
const local = path.join(outRoot(), "traces", `${session.document}.json`);
fs.mkdirSync(path.dirname(local), { recursive: true });
fs.writeFileSync(local, json);
return { opfs: stored.name, bytes: stored.bytes, sha256: stored.sha256, local, events: trace.events.length };
}

98
tools/fcweb/opfs.mjs Normal file
View File

@@ -0,0 +1,98 @@
// OPFS contract shared by every fcweb consumer.
//
// The browser keeps exported geometry in real OPFS under the directory
// `freecad-exports` (web/src/storage.ts). Node scripts cannot reach
// navigator.storage, so this module mirrors the same directory layout on disk
// and addresses files by the bare export name, exactly like the UI does.
//
// Unlike the case-local opfs-store.mjs this root is configurable, so the
// toolkit does not depend on any teaching case directory. The default lives
// inside the toolkit's own out/, which keeps selftest hermetic.
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
export const EXPORT_DIRECTORY = "freecad-exports";
export const DEFAULT_ROOT = path.join(here, "out", "opfs", EXPORT_DIRECTORY);
let root = DEFAULT_ROOT;
/** Point the store at another directory (absolute path). Returns the new root. */
export function configureOpfs({ root: next }) {
if (!next) throw new Error("configureOpfs requires { root }");
root = path.resolve(next);
return root;
}
export function storeRoot() {
return root;
}
/**
* A bare export name, no directory part, with an extension.
* Rejecting separators is what keeps `../x.brep` from escaping the store.
*/
export function safeName(name) {
if (typeof name !== "string") throw new Error(`invalid export name: ${String(name)}`);
if (name.includes("/") || name.includes("\\") || name.includes("\0")) throw new Error(`invalid export name: ${name}`);
const base = name.split(/[\\/]/).pop() || "";
if (base === "." || base === "..") throw new Error(`invalid export name: ${name}`);
if (!/^[A-Za-z0-9._-]+$/.test(base)) throw new Error(`invalid export name: ${name}`);
if (!/\.[A-Za-z0-9]+$/.test(base)) throw new Error(`invalid export name: ${name}`);
return base;
}
export function writeExportFile(name, bytes) {
const file = safeName(name);
fs.mkdirSync(root, { recursive: true });
const target = path.join(root, file);
fs.writeFileSync(target, Buffer.from(bytes));
return { name: file, path: target, bytes: fs.statSync(target).size };
}
export function readExportFile(name) {
const file = safeName(name);
const target = path.join(root, file);
if (!fs.existsSync(target)) throw new Error(`export missing from OPFS store: ${file}`);
return new Uint8Array(fs.readFileSync(target));
}
export function hasExportFile(name) {
return fs.existsSync(path.join(root, safeName(name)));
}
export function listExportFiles() {
if (!fs.existsSync(root)) return [];
return fs.readdirSync(root).sort();
}
export function sha256(bytes) {
return createHash("sha256").update(Buffer.from(bytes)).digest("hex");
}
/** Write bytes and report size + digest in one call. */
export function storeBytes(name, bytes) {
const stored = writeExportFile(name, bytes);
return { name: stored.name, path: stored.path, bytes: stored.bytes, sha256: sha256(bytes) };
}
/**
* Persist a JSON evidence record into the store and next to it on disk, so a
* report can be read without knowing the OPFS mirror location.
*/
export function evidence(name, value) {
const json = JSON.stringify(value, null, 2);
const stored = storeBytes(name, json);
const local = path.join(path.dirname(root), `evidence-${safeName(name)}`);
fs.mkdirSync(path.dirname(local), { recursive: true });
fs.writeFileSync(local, json);
return { ...stored, local };
}
/** Directory the OPFS mirror sits in, for evidence and trace side files. */
export function outRoot() {
return path.dirname(root);
}

287
tools/fcweb/part.mjs Normal file
View File

@@ -0,0 +1,287 @@
// Part workbench client: primitives, booleans, placement, import/export.
//
// Serves `cmd: "part.document"` via FreeCADWebDocumentProbe
// (freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp:918).
//
// The point of this module is to collapse the four-step "create -> size ->
// position -> label" triad that every teaching case used to hand-write, and to
// stop callers from guessing which object an import produced.
import fs from "node:fs";
import path from "node:path";
import {
STEM_PART, KernelError, openKernel, createSession, writeTrace,
} from "./kernel.mjs";
import { storeBytes } from "./opfs.mjs";
export const PART_SCHEMA = "freecad-web-part/document/v1";
export const PART_MODULE = "Part";
/** Kernel rule (DocumentProbe.cpp setBoolean): names are identifiers. */
const NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
const PRIMITIVES = ["Box", "Cylinder", "Sphere", "Torus", "Cone"];
const BOOLEANS = ["Fuse", "Cut", "Common"];
function assertName(name, what = "object") {
if (typeof name !== "string" || !NAME.test(name)) {
throw new KernelError(`${what} name must match ${NAME} (got ${JSON.stringify(name)})`, { code: "bad_name" });
}
return name;
}
function assertPositive(values, what) {
for (const value of values) {
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
throw new KernelError(`${what} must be positive finite numbers (got ${JSON.stringify(values)})`, { code: "bad_dimension" });
}
}
}
function vector3(value, fallback, what) {
if (value == null) return fallback;
if (!Array.isArray(value) || value.length !== 3 || value.some(item => typeof item !== "number" || !Number.isFinite(item))) {
throw new KernelError(`${what} must be a 3-number array (got ${JSON.stringify(value)})`, { code: "bad_vector" });
}
return value;
}
export class PartDocument {
constructor(session, kernelDir) {
this.session = session;
this.document = session.document;
this.kernel = session.kernel;
this.kernelDir = kernelDir;
}
get call() { return this.session.call; }
get timed() { return this.session.timed; }
get timings() { return this.session.timings; }
get events() { return this.session.events; }
// ---- document lifecycle -------------------------------------------------
create() { return this.call("create"); }
open(file) { return this.call("open", { path: file }); }
close() { return this.call("close"); }
remove(object) { assertName(object); return this.call("remove", { object }); }
label(object, text) { assertName(object); return this.call("setLabel", { object, label: String(text) }); }
// ---- primitives ---------------------------------------------------------
/**
* Part::Box built the way the desktop box command builds it:
* createFixedBox -> setBox(dimensions) -> setPosition -> setLabel.
*/
box(object, { length, width, height, position, label } = {}) {
assertName(object);
assertPositive([length, width, height], "box dimensions");
const at = vector3(position, [0, 0, 0], "box position");
// createFixedBox allocates the object; setBox is what actually sizes it.
let result = this.call("createFixedBox", { boxCommand: "Part_Box", object });
result = this.call("setBox", { object, dimensions: [length, width, height] });
result = this.call("setPosition", { object, position: at });
if (label) result = this.call("setLabel", { object, label: String(label) });
return result;
}
/**
* Any Part primitive. `kind` selects the Part:: type; `parameters` are the
* native property names (Radius/Height/Angle for a cylinder, Length/Width/
* Height for a box, and so on -- the kernel wants the capitalised names).
*/
primitive(object, { kind, parameters = {}, placement, container, label, builderInfo = true } = {}) {
assertName(object);
if (!PRIMITIVES.includes(kind)) {
throw new KernelError(`unknown part primitive ${JSON.stringify(kind)}; expected one of ${PRIMITIVES.join(", ")}`, { code: "bad_primitive" });
}
const args = {
primitive: kind,
object,
primitiveCreate: true,
parameters,
builderInfo,
};
if (container) args.primitiveContainer = container;
if (placement) {
args.primitivePlacement = {
position: vector3(placement.position, [0, 0, 0], "primitive position"),
axis: vector3(placement.axis, [0, 0, 1], "primitive axis"),
angle: typeof placement.angle === "number" ? placement.angle : 0,
};
}
let result = this.call("setPrimitive", args);
if (label) result = this.call("setLabel", { object, label: String(label) });
return result;
}
/** Convenience for the very common "cylinder, rotated about Y" shaft case. */
cylinder(object, { radius, height, position, axis = [0, 1, 0], angle = 90, container, label } = {}) {
assertPositive([radius, height], "cylinder dimensions");
return this.primitive(object, {
kind: "Cylinder",
parameters: { Radius: radius, Height: height, Angle: 360, FirstAngle: 0, SecondAngle: 0 },
placement: { position: position ?? [0, 0, 0], axis, angle },
container,
label,
});
}
// ---- booleans -----------------------------------------------------------
boolean(operation, { object, base, tool } = {}) {
if (!BOOLEANS.includes(operation)) {
throw new KernelError(`unknown boolean ${JSON.stringify(operation)}; expected ${BOOLEANS.join(", ")}`, { code: "bad_boolean" });
}
assertName(object);
assertName(base, "base");
assertName(tool, "tool");
return this.call("setBoolean", { operation, object, base, tool });
}
fuse(args) { return this.boolean("Fuse", args); }
cut(args) { return this.boolean("Cut", args); }
common(args) { return this.boolean("Common", args); }
// ---- placement ----------------------------------------------------------
move(object, position) {
assertName(object);
return this.call("setPosition", { object, position: vector3(position, [0, 0, 0], "position") });
}
place(object, { position, axis = [0, 0, 1], angle = 0 } = {}) {
assertName(object);
return this.call("setPlacement", {
object,
position: vector3(position, [0, 0, 0], "placement position"),
axis: vector3(axis, [0, 0, 1], "placement axis"),
angle: typeof angle === "number" ? angle : 0,
});
}
compound(object, links, { label } = {}) {
assertName(object);
if (!Array.isArray(links) || links.length === 0) {
throw new KernelError("compound requires a non-empty links array", { code: "bad_request" });
}
links.forEach(link => assertName(link, "compound link"));
let result = this.call("createCompound", { object, links });
if (label) result = this.call("setLabel", { object, label: String(label) });
return result;
}
// ---- import / export ----------------------------------------------------
/**
* Import a STEP or BREP file that already sits in the kernel's MEMFS.
*
* Returns `{ object, solid, objects }`: `solid` is the first imported object
* that actually carries volume, which is the "pick the real body out of the
* import result" step every caller used to write by hand.
*/
importPath(file, { object, step = null, command, label } = {}) {
const isStep = step ?? /\.(stp|step)$/i.test(file);
const action = isStep ? "importStep" : "importShape";
const args = { path: file };
if (object) args.object = assertName(object);
if (command) args.desktopImportCommand = command;
else if (!isStep) args.desktopImportCommand = "Import_ReadBREP";
let result = this.call(action, args);
if (label && object) result = this.call("setLabel", { object, label: String(label) });
const objects = result?.objects ?? [];
const solid = objects.find(item => typeof item?.volume === "number" && item.volume > 0) ?? null;
return { object: solid?.name ?? object ?? null, solid, objects };
}
/** Put host bytes into the kernel's virtual file system (never host /tmp). */
stageFile(name, bytes) {
const target = `/tmp/${path.basename(name)}`;
this.kernel.FS.writeFile(target, new Uint8Array(bytes));
return target;
}
/**
* Export one object and store it through the OPFS contract.
* `extension` is the OCCT format: brep, step, stp, iges, stl.
*/
exportObject(object, extension = "brep", { name } = {}) {
assertName(object);
const suffix = String(extension).replace(/^\./, "").toLowerCase();
const staged = `/tmp/${this.document}-${object}.${suffix}`;
const reply = this.call("exportShape", { path: staged, object });
const bytes = this.kernel.FS.readFile(staged);
const stored = storeBytes(name ?? `${this.document}-${object}.${suffix}`, bytes);
return { object, format: suffix, ...stored, nativeSize: reply?.size ?? null };
}
/** Save the whole document as FCStd (Assembly_InsertLink only accepts .FCStd). */
saveDocument({ name } = {}) {
const staged = `/tmp/${this.document}.FCStd`;
this.call("save", { path: staged });
const bytes = this.kernel.FS.readFile(staged);
return { format: "FCStd", ...storeBytes(name ?? `${this.document}.FCStd`, bytes) };
}
// ---- inspection ---------------------------------------------------------
//
// Primitive-editing actions (setBox/setPosition/setLabel) answer with object
// stubs that carry no geometry, so measurement always goes through snapshot.
objects() { return this.snapshot().objects ?? []; }
objectOf(name) { return this.objects().find(item => item.name === name) ?? null; }
volumeOf(name) { return this.objectOf(name)?.volume ?? null; }
snapshot({ mesh = false, objects } = {}) {
const args = { includeMesh: mesh === true, builderInfo: false };
if (mesh && Array.isArray(objects)) args.includeMeshObjects = objects;
return this.call("snapshot", args);
}
/**
* Mesh projection for a viewer: positions/normals rounded to 1e-3 and a
* triangle count, which is what the teaching pages consume.
*
* The kernel nests the geometry under `object.mesh` ({positions, normals,
* triangleCount, bounds, colors, ...}); the object itself only carries the
* B-rep summary.
*/
meshOf(name) {
const result = this.snapshot({ mesh: true, objects: [name] });
const item = (result?.objects ?? []).find(entry => entry.name === name);
if (!item) throw new KernelError(`snapshot returned no object ${name}`, { code: "missing_object" });
const mesh = item.mesh ?? {};
const round = values => (values ?? []).map(value => Math.round(value * 1000) / 1000);
const positions = round(mesh.positions);
return {
name,
label: item.label ?? name,
volume: item.volume ?? null,
bounds: mesh.bounds ?? null,
positions,
normals: round(mesh.normals),
triangleCount: mesh.triangleCount ?? positions.length / 9,
};
}
trace() { return this.session.trace(); }
writeTrace(extra) { return writeTrace(this.session, { extra }); }
}
/**
* Open a Part document. Does not create it -- callers decide whether to
* `create()` or `open(path)`, because both flows are legitimate.
*/
export async function openPart(document, { kernelDirs, print, printErr, builder } = {}) {
if (!document) throw new KernelError("openPart requires a document name", { code: "bad_request" });
const handle = await openKernel({ stem: STEM_PART, dirs: kernelDirs, print, printErr });
const session = createSession({
handle,
cmd: "part.document",
schema: PART_SCHEMA,
module: PART_MODULE,
document,
extra: builder ? { builder } : {},
});
const part = new PartDocument(session, handle.directory);
// `close` here closes the pthread pool; closing the *document* is explicit.
part.dispose = () => handle.close();
return part;
}
/** Read a file from the host and stage it into the kernel FS. */
export function hostBytes(file) {
return fs.readFileSync(file);
}

259
tools/fcweb/partdesign.mjs Normal file
View File

@@ -0,0 +1,259 @@
// PartDesign client: Body, sketches, profile features, gears.
//
// Serves `cmd: "partdesign.document"` via FreeCADWebPartDesignRuntimeProbe
// (PartDesignRuntimeProbe.cpp:1353 -> PartDesignDocumentWorkflow.cpp:1196).
//
// Contract notes that differ from the Part probe and are easy to get wrong:
// - primitives use `primitiveType` (Part uses `primitive`)
// - primitives take a `position` array, not `primitivePlacement`
// - setSketch accepts profileType Rectangle | Circle | Geometry | Wire
// - setFeature takes `length` for Pad/Pocket (not `depth`)
// - sketches and datums report volume: null -- only solids have volume
import {
STEM_PARTDESIGN, KernelError, openKernel, createSession, writeTrace,
} from "./kernel.mjs";
import { storeBytes } from "./opfs.mjs";
export const PARTDESIGN_SCHEMA = "freecad-web-partdesign-document/v1";
export const PARTDESIGN_MODULE = "PartDesign";
const NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
const PROFILE_TYPES = ["Rectangle", "Circle", "Geometry", "Wire"];
const PRIMITIVES = [
"AdditiveBox", "AdditiveCylinder", "AdditiveSphere", "AdditiveCone",
"AdditiveEllipsoid", "AdditiveTorus", "AdditivePrism", "AdditiveWedge",
"SubtractiveBox", "SubtractiveCylinder", "SubtractiveSphere", "SubtractiveCone",
"SubtractiveEllipsoid", "SubtractiveTorus", "SubtractivePrism", "SubtractiveWedge",
];
const FEATURES = [
"Pad", "Pocket", "Revolution", "Groove", "Hole", "Loft", "Pipe",
"SubtractiveLoft", "SubtractivePipe",
];
const GEAR_TYPES = ["InvoluteGear", "Sprocket"];
const DRESS_UPS = ["Fillet", "Chamfer", "Draft", "Thickness"];
function assertName(name, what = "object") {
if (typeof name !== "string" || !NAME.test(name)) {
throw new KernelError(`${what} name must match ${NAME} (got ${JSON.stringify(name)})`, { code: "bad_name" });
}
return name;
}
function assertPositive(value, what) {
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
throw new KernelError(`${what} must be a positive finite number (got ${JSON.stringify(value)})`, { code: "bad_dimension" });
}
return value;
}
function vector3(value, fallback, what) {
if (value == null) return fallback;
if (!Array.isArray(value) || value.length !== 3 || value.some(item => typeof item !== "number" || !Number.isFinite(item))) {
throw new KernelError(`${what} must be a 3-number array (got ${JSON.stringify(value)})`, { code: "bad_vector" });
}
return value;
}
export class PartDesignDocument {
constructor(session) {
this.session = session;
this.document = session.document;
this.kernel = session.kernel;
}
get call() { return this.session.call; }
get timed() { return this.session.timed; }
get timings() { return this.session.timings; }
get events() { return this.session.events; }
// ---- document / body ----------------------------------------------------
create() { return this.call("create"); }
open(file) { return this.call("open", { path: file }); }
close() { return this.call("close"); }
saveDocument({ name } = {}) {
const staged = `/tmp/${this.document}.FCStd`;
this.call("save", { path: staged });
const bytes = this.kernel.FS.readFile(staged);
return { format: "FCStd", ...storeBytes(name ?? `${this.document}.FCStd`, bytes) };
}
/** Create a body. The default name matches what the desktop workbench uses. */
body(name = "Body") {
assertName(name, "body");
return this.call("createBody", { object: name });
}
// ---- sketch -------------------------------------------------------------
/**
* Rectangle and Circle profiles take { Width, Height } / { Radius };
* `Geometry` takes a pre-built geometry list; `Wire` takes `points`.
*/
sketch(object, { body = "Body", profileType = "Rectangle", parameters, position, points, placementRotation, label } = {}) {
assertName(object, "sketch");
if (!PROFILE_TYPES.includes(profileType)) {
throw new KernelError(`unknown profileType ${JSON.stringify(profileType)}; expected ${PROFILE_TYPES.join(", ")}`, { code: "bad_profile" });
}
const args = {
object,
body,
profileType,
position: vector3(position, [0, 0, 0], "sketch position"),
};
if (profileType === "Wire") {
if (!Array.isArray(points) || points.length < 3) {
throw new KernelError("Wire profile needs at least three points", { code: "bad_profile" });
}
args.points = points;
} else if (profileType !== "Geometry") {
if (!parameters || typeof parameters !== "object") {
throw new KernelError(`${profileType} profile needs parameters`, { code: "bad_profile" });
}
if (profileType === "Circle") assertPositive(parameters.Radius, "Radius");
else {
assertPositive(parameters.Width, "Width");
assertPositive(parameters.Height, "Height");
}
args.parameters = parameters;
}
if (Array.isArray(placementRotation)) {
if (placementRotation.length !== 4) throw new KernelError("placementRotation must have 4 numbers", { code: "bad_vector" });
args.placementRotation = placementRotation;
}
let result = this.call("setSketch", args);
if (label) result = this.call("setLabel", { object, label: String(label) });
return result;
}
// ---- profile features ---------------------------------------------------
/**
* Pad / Pocket / Revolution / Groove / Hole / Loft / Pipe.
* `length` is the native dimension for Pad and Pocket; Revolution and Groove
* take `angle`; Hole takes `depth` (or depthType "ThroughAll").
*/
feature(object, { featureType = "Pad", body = "Body", profile, length, angle, depth, depthType, midplane, reversed, axis, label } = {}) {
assertName(object, "feature");
if (!FEATURES.includes(featureType)) {
throw new KernelError(`unknown featureType ${JSON.stringify(featureType)}; expected ${FEATURES.join(", ")}`, { code: "bad_feature" });
}
assertName(profile, "profile");
const args = { object, featureType, body, profile };
if (featureType === "Revolution" || featureType === "Groove") {
if (angle != null) args.angle = assertPositive(angle, "angle");
if (axis) args.axis = axis;
} else if (featureType === "Hole") {
if (depthType) args.depthType = depthType;
if (depth != null) args.depth = assertPositive(depth, "depth");
} else if (featureType !== "Loft" && featureType !== "Pipe") {
if (length != null) args.length = assertPositive(length, "length");
}
if (midplane != null) args.midplane = Boolean(midplane);
if (reversed != null) args.reversed = Boolean(reversed);
let result = this.call("setFeature", args);
if (label) result = this.call("setLabel", { object, label: String(label) });
return result;
}
pad(object, args) { return this.feature(object, { ...args, featureType: "Pad" }); }
pocket(object, args) { return this.feature(object, { ...args, featureType: "Pocket" }); }
/** Body primitive, e.g. AdditiveBox / SubtractiveCylinder. */
primitive(object, { body = "Body", primitiveType, parameters = {}, position, label } = {}) {
assertName(object, "primitive");
if (!PRIMITIVES.includes(primitiveType)) {
throw new KernelError(`unknown primitiveType ${JSON.stringify(primitiveType)}; expected one of ${PRIMITIVES.join(", ")}`, { code: "bad_primitive" });
}
const args = { object, body, primitiveType, parameters };
if (position) args.position = vector3(position, [0, 0, 0], "primitive position");
let result = this.call("setPrimitive", args);
if (label) result = this.call("setLabel", { object, label: String(label) });
return result;
}
/** Involute gear (or sprocket) as a PartDesign feature. */
gear(object, { body = "Body", gearType = "InvoluteGear", gearParameters, label } = {}) {
assertName(object, "gear");
if (!GEAR_TYPES.includes(gearType)) {
throw new KernelError(`unknown gearType ${JSON.stringify(gearType)}; expected ${GEAR_TYPES.join(", ")}`, { code: "bad_gear" });
}
if (!gearParameters || typeof gearParameters !== "object") {
throw new KernelError("gear requires gearParameters", { code: "bad_gear" });
}
if (!Number.isInteger(gearParameters.NumberOfTeeth)) {
throw new KernelError("NumberOfTeeth must be an integer", { code: "bad_gear" });
}
let result = this.call("setGear", { object, body, gearType, gearParameters });
if (label) result = this.call("setLabel", { object, label: String(label) });
return result;
}
dressUp(object, { dressUpType, body = "Body", ...rest } = {}) {
if (!DRESS_UPS.includes(dressUpType)) {
throw new KernelError(`unknown dressUpType ${JSON.stringify(dressUpType)}; expected ${DRESS_UPS.join(", ")}`, { code: "bad_dressup" });
}
return this.call("setDressUp", { object, dressUpType, body, ...rest });
}
/** Mass properties of a selection; returns the kernel's report object. */
massProperties({ selection, saveResult = false } = {}) {
if (!Array.isArray(selection) || selection.length === 0) {
throw new KernelError("massProperties requires a non-empty selection", { code: "bad_request" });
}
return this.call("massProperties", { selection, saveResult });
}
// ---- inspection ---------------------------------------------------------
snapshot({ mesh = false, objects } = {}) {
const args = { includeMesh: mesh === true, builderInfo: false };
if (mesh && Array.isArray(objects)) args.includeMeshObjects = objects;
return this.call("snapshot", args);
}
objects() { return this.snapshot().objects ?? []; }
objectOf(name) { return this.objects().find(item => item.name === name) ?? null; }
volumeOf(name) { return this.objectOf(name)?.volume ?? null; }
meshOf(name) {
const result = this.snapshot({ mesh: true, objects: [name] });
const item = (result?.objects ?? []).find(entry => entry.name === name);
if (!item) throw new KernelError(`snapshot returned no object ${name}`, { code: "missing_object" });
const mesh = item.mesh ?? {};
const round = values => (values ?? []).map(value => Math.round(value * 1000) / 1000);
const positions = round(mesh.positions);
return {
name,
label: item.label ?? name,
volume: item.volume ?? null,
bounds: mesh.bounds ?? null,
positions,
normals: round(mesh.normals),
triangleCount: mesh.triangleCount ?? positions.length / 3,
};
}
trace() { return this.session.trace(); }
writeTrace(extra) { return writeTrace(this.session, { extra }); }
}
/**
* Open a PartDesign document with a Body already in it -- that is the state the
* desktop workbench hands you, and every feature needs a body to attach to.
*/
export async function openPartDesign(document, { kernelDirs, print, printErr, builder, body = "Body", create = true } = {}) {
if (!document) throw new KernelError("openPartDesign requires a document name", { code: "bad_request" });
const handle = await openKernel({ stem: STEM_PARTDESIGN, dirs: kernelDirs, print, printErr });
const session = createSession({
handle,
cmd: "partdesign.document",
schema: PARTDESIGN_SCHEMA,
module: PARTDESIGN_MODULE,
document,
extra: builder ? { builder } : {},
});
const part = new PartDesignDocument(session, handle.directory);
part.dispose = () => handle.close();
if (create) {
part.create();
part.body(body);
}
return part;
}

281
tools/fcweb/selftest.mjs Normal file
View File

@@ -0,0 +1,281 @@
#!/usr/bin/env node
// fcweb toolkit self-check.
//
// No fixtures, no browser, no teaching case. Every number below is either an
// analytic volume or a cross-probe agreement, so this is a gate on the kernel
// contract rather than a smoke test: if a probe renames an argument key or
// changes a return shape, a check here fails instead of a case script quietly
// producing a different model.
//
// node tools/fcweb/selftest.mjs
// node tools/fcweb/selftest.mjs --json <path>
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { openPart } from "./part.mjs";
import { openPartDesign } from "./partdesign.mjs";
import { openAssembly } from "./assembly.mjs";
import { configureOpfs, storeRoot, storeBytes, readExportFile, hasExportFile, listExportFiles, safeName } from "./opfs.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const outDir = path.join(here, "out");
const TOL = 1e-6;
const results = [];
function check(name, expected, actual, { tolerance = TOL, note = null } = {}) {
const ok = typeof expected === "number" && typeof actual === "number"
? Math.abs(expected - actual) <= tolerance
: actual === expected;
results.push({ name, expected, actual, tolerance, ok, note });
console.log(`${ok ? "PASS" : "FAIL"} ${name} expected=${expected} actual=${actual}`);
if (!ok) throw new Error(`selftest failed: ${name} (expected ${expected}, got ${actual})`);
return ok;
}
function checkTrue(name, value, note = null) {
const ok = Boolean(value);
results.push({ name, expected: true, actual: Boolean(value), tolerance: null, ok, note });
console.log(`${ok ? "PASS" : "FAIL"} ${name}`);
if (!ok) throw new Error(`selftest failed: ${name} ${note ?? ""}`);
}
const CY15 = Math.PI * 25; // area of a r=5 circle, the recurring term
// ---------------------------------------------------------------- Part ----
async function partChecks() {
// Box 20x30x10 -> exact volume; also the reference for the cross-probe check.
const part = await openPart("SelfTestPart");
let boxVolume;
try {
part.create();
part.box("B1", { length: 20, width: 30, height: 10 });
boxVolume = part.volumeOf("B1");
check("part.box volume 20x30x10", 6000, boxVolume, { tolerance: 1e-6 });
// Fuse with a disjoint cylinder: avoids OCCT's touching-face ambiguity.
// Default axis is +Z, so no rotation is involved and the volume is exact.
part.primitive("C1", {
kind: "Cylinder",
parameters: { Radius: 5, Height: 10, Angle: 360, FirstAngle: 0, SecondAngle: 0 },
placement: { position: [40, 10, 0] },
});
part.fuse({ object: "Fused", base: "B1", tool: "C1" });
check("part.fuse volume", 6000 + CY15 * 10, part.volumeOf("Fused"), { tolerance: 1e-6 });
// Cut a full cylinder out of a 20-cube. The cylinder sits wholly inside
// (centred at x=y=10, spanning the full height), so the removed volume is
// exactly pi*r^2*h -- no partial-quadrant guesswork.
part.box("Cube", { length: 20, width: 20, height: 20 });
part.primitive("C2", {
kind: "Cylinder",
parameters: { Radius: 5, Height: 20, Angle: 360, FirstAngle: 0, SecondAngle: 0 },
placement: { position: [10, 10, 0] },
});
part.cut({ object: "CutResult", base: "Cube", tool: "C2" });
check("part.cut volume", 8000 - CY15 * 20, part.volumeOf("CutResult"), { tolerance: 1e-6 });
// Common of two cubes offset by 10 in X -> 10 x 20 x 20.
part.box("K1", { length: 20, width: 20, height: 20 });
part.box("K2", { length: 20, width: 20, height: 20, position: [10, 0, 0] });
part.common({ object: "CommonResult", base: "K1", tool: "K2" });
check("part.common volume", 4000, part.volumeOf("CommonResult"), { tolerance: 1e-6 });
// Mesh projection: a box is 12 triangles.
const mesh = part.meshOf("B1");
check("part.mesh triangleCount", 12, mesh.triangleCount, { tolerance: 0 });
check("part.mesh positions length", 108, mesh.positions.length, { tolerance: 0 });
checkTrue("part.mesh normals match positions", mesh.normals.length === mesh.positions.length);
// Export -> import round trip.
const exported = part.exportObject("B1", "brep");
checkTrue("part.export produced bytes", exported.bytes > 0 && exported.sha256.length === 64);
} finally {
try { part.close(); } catch { /* document may already be closed */ }
part.dispose();
}
const second = await openPart("SelfTestPartImport");
try {
second.create();
const staged = second.stageFile("B1.brep", fs.readFileSync(path.join(storeRoot(), "SelfTestPart-B1.brep")));
const imported = second.importPath(staged, { object: "Imported" });
checkTrue("part.import found a solid", imported.solid !== null, JSON.stringify(imported.objects?.map(o => o.name)));
check("part.import preserves volume", 6000, imported.solid?.volume, { tolerance: 1e-6 });
// An imported Part::Feature carries volume but no B-rep counters, so the
// geometry is confirmed through the mesh: a 20x30x10 box is 12 triangles,
// and the bounding box must match the source.
const measured = second.objectOf(imported.solid.name);
check("part.import volume via snapshot", 6000, measured?.volume, { tolerance: 1e-6 });
const mesh = second.meshOf(imported.solid.name);
check("part.import preserves mesh triangles", 12, mesh.triangleCount, { tolerance: 0 });
checkTrue("part.import preserves bounds",
JSON.stringify(mesh.bounds) === JSON.stringify([0, 0, 0, 20, 30, 10]),
JSON.stringify(mesh.bounds));
} finally {
try { second.close(); } catch { /* closed by save */ }
second.dispose();
}
return boxVolume;
}
// ---------------------------------------------------------- PartDesign ----
async function partDesignChecks(partBoxVolume) {
const part = await openPartDesign("SelfTestPartDesign");
let gearVolume;
try {
// Rectangle 40x25 padded 8 -> 8000 exactly.
part.sketch("Plate", { profileType: "Rectangle", parameters: { Width: 40, Height: 25 }, position: [0, 0, 0] });
part.pad("PlatePad", { profile: "Plate", length: 8 });
check("partdesign.pad volume", 8000, part.volumeOf("PlatePad"), { tolerance: 1e-6 });
// Circle r=5 pocketed through a mid-plane of the 8 mm plate: removes 2 mm.
part.sketch("Bore", { profileType: "Circle", parameters: { Radius: 5 }, position: [0, 0, 0] });
part.pocket("BorePocket", { profile: "Bore", length: 28, midplane: true });
check("partdesign.pocket volume", 8000 - CY15 * 2, part.volumeOf("BorePocket"), { tolerance: 1e-6 });
// Body primitive must agree with the Part box of the same size.
const other = await openPartDesign("SelfTestPartDesignPrim");
try {
other.primitive("PrimBox", { primitiveType: "AdditiveBox", parameters: { Length: 20, Width: 30, Height: 10 } });
check("cross-probe box volume agrees", partBoxVolume, other.volumeOf("PrimBox"), { tolerance: 1e-6 });
} finally {
try { other.close(); } catch { /* closed */ }
other.dispose();
}
} finally {
try { part.close(); } catch { /* closed */ }
part.dispose();
}
// Involute gear: two independently built documents must agree exactly, and
// the gear must be a real solid. Neither document carries any other feature,
// so the compared volume is the gear alone -- a Pad reports the accumulated
// shape of the whole body, which is why the plate document above cannot be
// the reference.
gearVolume = await buildGear("SelfTestGearA");
const gearAgain = await buildGear("SelfTestGearB");
check("partdesign.gear deterministic", gearVolume.volume, gearAgain.volume, { tolerance: 1e-9 });
checkTrue("partdesign.gear volume is positive", gearVolume.volume > 0, `volume=${gearVolume.volume}`);
checkTrue("partdesign.gear has faces", gearVolume.faceCount > 0, `faces=${gearVolume.faceCount}`);
}
/** Build one stand-alone 20-tooth gear and report its measured shape. */
async function buildGear(document) {
const part = await openPartDesign(document);
try {
part.gear("GearProfile", {
gearParameters: {
NumberOfTeeth: 20, Modules: 2, PressureAngle: 20,
AddendumCoefficient: 1, DedendumCoefficient: 1.25, RootFilletCoefficient: 0.38,
ProfileShiftCoefficient: 0, HighPrecision: false, ExternalGear: true,
},
});
part.pad("GearPad", { profile: "GearProfile", length: 20 });
const object = part.objectOf("GearPad");
return { volume: object?.volume ?? 0, faceCount: object?.faceCount ?? 0 };
} finally {
try { part.close(); } catch { /* closed */ }
part.dispose();
}
}
// ------------------------------------------------------------ Assembly ----
async function assemblyChecks() {
// Two source parts, each saved as its own FCStd.
for (const [document, name] of [["SelfTestSrcA", "BlockA"], ["SelfTestSrcB", "BlockB"]]) {
const part = await openPart(document);
try {
part.create();
part.box(name, { length: 40, width: 30, height: 10 });
part.saveDocument();
} finally {
try { part.close(); } catch { /* closed */ }
part.dispose();
}
}
const assembly = await openAssembly({ document: "SelfTestAsm", assembly: "Assembly", label: "自检装配" });
try {
const created = assembly.create();
check("assembly.componentCount before insert", 0, created.object?.componentCount, { tolerance: 0 });
const { inserted, accepted } = assembly.insertLinks([
{ file: path.join(storeRoot(), "SelfTestSrcA.FCStd"), sourceDocument: "SelfTestSrcA", sourceObject: "BlockA", position: [0, 0, 0] },
{ file: path.join(storeRoot(), "SelfTestSrcB.FCStd"), sourceDocument: "SelfTestSrcB", sourceObject: "BlockB", position: [60, 0, 0], rotation: [0, 0, 0, 1] },
]);
check("assembly.insertLinks count", 2, inserted.length, { tolerance: 0 });
checkTrue("assembly.accept returned a session", Boolean(accepted), JSON.stringify(Object.keys(accepted ?? {})).slice(0, 200));
const solved = assembly.solve();
checkTrue("assembly.solve returned a result", solved !== null && typeof solved === "object");
} finally {
assembly.dispose();
}
}
// ----------------------------------------------------------- lifecycle ----
async function lifecycleChecks() {
// Same handle: create -> close document -> create again must work.
const part = await openPart("SelfTestLifecycle");
try {
part.create();
part.box("L1", { length: 10, width: 10, height: 10 });
check("lifecycle first document", 1000, part.volumeOf("L1"), { tolerance: 1e-6 });
part.close();
part.create();
part.box("L2", { length: 5, width: 5, height: 5 });
check("lifecycle second document", 125, part.volumeOf("L2"), { tolerance: 1e-6 });
} finally {
try { part.close(); } catch { /* closed */ }
part.dispose();
}
}
// ---------------------------------------------------------------- OPFS ----
async function opfsChecks() {
const bytes = new TextEncoder().encode("fcweb selftest payload");
const stored = storeBytes("selftest-payload.txt", bytes);
checkTrue("opfs storeBytes wrote a file", stored.bytes === bytes.byteLength && stored.sha256.length === 64);
checkTrue("opfs hasExportFile", hasExportFile("selftest-payload.txt"));
check("opfs readExportFile round-trips", bytes.byteLength, readExportFile("selftest-payload.txt").length, { tolerance: 0 });
checkTrue("opfs listExportFiles includes the payload", listExportFiles().includes("selftest-payload.txt"));
for (const bad of ["../x.brep", "a/b.brep", "noext"]) {
let rejected = false;
try { safeName(bad); } catch { rejected = true; }
checkTrue(`opfs safeName rejects ${JSON.stringify(bad)}`, rejected);
}
}
// ----------------------------------------------------------------- run ----
const started = Date.now();
try {
configureOpfs({ root: path.join(outDir, "opfs", "freecad-exports") });
const boxVolume = await partChecks();
await partDesignChecks(boxVolume);
await assemblyChecks();
await lifecycleChecks();
await opfsChecks();
const report = {
schema: "freecad-web/fcweb-selftest/v1",
ok: results.every(item => item.ok),
checks: results.length,
seconds: Number(((Date.now() - started) / 1000).toFixed(2)),
results,
};
fs.mkdirSync(outDir, { recursive: true });
fs.writeFileSync(path.join(outDir, "selftest.json"), JSON.stringify(report, null, 2));
console.log(`\n${report.checks} checks passed in ${report.seconds}s`);
const jsonArg = process.argv.indexOf("--json");
if (jsonArg >= 0 && process.argv[jsonArg + 1]) {
fs.writeFileSync(path.resolve(process.argv[jsonArg + 1]), JSON.stringify(report, null, 2));
}
process.exit(0);
} catch (error) {
console.error(`\nselftest aborted: ${error?.message ?? error}`);
const report = { schema: "freecad-web/fcweb-selftest/v1", ok: false, checks: results.length, error: String(error?.message ?? error), results };
fs.mkdirSync(outDir, { recursive: true });
fs.writeFileSync(path.join(outDir, "selftest.json"), JSON.stringify(report, null, 2));
process.exit(1);
}

163
tools/fcweb/ui-capture.mjs Normal file
View File

@@ -0,0 +1,163 @@
#!/usr/bin/env node
// Capture one screenshot per workbench from the running Web FreeCAD shell.
//
// Reuses tools/fcweb/capture.mjs for browser launch and screenshots. The
// inventory decides what exists and what status each workbench has; this tool
// only drives the shell and records what it observed.
//
// node tools/fcweb/ui-capture.mjs --all
// node tools/fcweb/ui-capture.mjs --only Part,Fem --headed
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { launchBrowser, openPage, screenshot } from "./capture.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
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 url = argValue("--url", "http://127.0.0.1:5182/");
const inventoryPath = path.resolve(argValue("--inventory", path.join(here, "out", "ui-inventory.json")));
const outDir = path.resolve(argValue("--out", path.join(here, "out", "ui-shots")));
const reportPath = path.resolve(argValue("--report", path.join(here, "out", "ui-capture-report.json")));
const only = argValue("--only", "");
const headed = args.includes("--headed");
const timeoutMs = Number(argValue("--timeout", "120000"));
const [width, height] = argValue("--viewport", "1600x1000").split("x").map(Number);
if (!fs.existsSync(inventoryPath)) {
console.error(`[ui-capture] missing inventory: ${inventoryPath}`);
process.exit(2);
}
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
const wanted = only ? new Set(only.split(",").map(item => item.trim()).filter(Boolean)) : null;
const capturable = inventory.chapters.filter(chapter =>
(chapter.status === "renders" || chapter.status === "fallback")
&& (!wanted || wanted.has(chapter.id)));
const skipped = inventory.chapters
.filter(chapter => !capturable.includes(chapter))
.map(chapter => ({ id: chapter.id, status: chapter.status, reason: chapter.reason ?? null }));
fs.mkdirSync(outDir, { recursive: true });
const browser = await launchBrowser({ headed });
const results = [];
let baselineSha = null;
try {
for (const chapter of capturable) {
const started = Date.now();
const id = chapter.id;
const { page, errors, failedRequests } = await openPage(browser, url, { viewport: { width, height } });
const record = {
id,
status: "failed",
ms: 0,
file: null,
bytes: 0,
sha256: null,
toolbarCrop: null,
iframe: false,
domToolbarButtons: 0,
pageErrors: [],
failedRequests: [],
warnings: [],
};
try {
await page.waitForSelector('select[aria-label="Workbench"]', { state: "attached", timeout: 60000 });
// The Start overlay covers the shell on a cold load; Escape closes it.
await page.keyboard.press("Escape").catch(() => {});
await page.waitForTimeout(400);
const select = page.locator('select[aria-label="Workbench"]');
if (await select.isDisabled().catch(() => false)) {
// A task panel disables the switcher; close whatever is open.
await page.keyboard.press("Escape").catch(() => {});
await page.waitForTimeout(400);
}
await select.selectOption(id, { timeout: 30000 });
await page.waitForFunction(
expected => document.querySelector('select[aria-label="Workbench"]')?.value === expected,
id,
{ timeout: 15000 },
);
// Wait for whatever this workbench actually shows.
const toolbars = `[aria-label="${id} toolbars"]`;
const frame = `iframe[title="${id} workbench"]`;
const deadline = Date.now() + timeoutMs;
let sawSomething = false;
while (Date.now() < deadline) {
if (await page.locator(toolbars).count() > 0) { sawSomething = true; break; }
if (await page.locator(frame).count() > 0) { record.iframe = true; sawSomething = true; break; }
// Part is special-cased (no parity toolbars); fall back to its dock.
if (await page.locator('[data-toolbar-name="Solids"]').count() > 0) { sawSomething = true; break; }
await page.waitForTimeout(500);
}
if (!sawSomething) record.warnings.push("no toolbar dock or iframe appeared; screenshot taken anyway");
await page.waitForTimeout(1800);
const file = path.join(outDir, `${id}.png`);
await screenshot(page, { file });
const bytes = fs.readFileSync(file);
record.bytes = bytes.length;
record.sha256 = createHash("sha256").update(bytes).digest("hex");
record.file = file;
record.domToolbarButtons = await page.evaluate(() =>
document.querySelectorAll('[aria-label$=" toolbars"] div[role="toolbar"] button, [data-toolbar-name] button').length
).catch(() => 0);
if (await page.locator(toolbars).count() > 0) {
const crop = path.join(outDir, `${id}-toolbars.png`);
try {
await screenshot(page, { file: crop, locator: toolbars });
record.toolbarCrop = crop;
} catch {
record.warnings.push("toolbar crop failed");
}
}
record.pageErrors = errors.slice(0, 5);
record.failedRequests = failedRequests.slice(0, 5);
if (record.bytes < 20000) record.warnings.push(`screenshot is only ${record.bytes} bytes`);
if (baselineSha === null) baselineSha = record.sha256;
else if (id !== "Architecture" && record.sha256 === baselineSha) {
record.warnings.push("screenshot is byte-identical to the first capture (possible blank page)");
}
record.status = record.pageErrors.length === 0 ? "ok" : "page-errors";
} catch (error) {
record.status = "failed";
record.warnings.push(String(error?.message ?? error).slice(0, 300));
record.pageErrors = errors.slice(0, 5);
} finally {
record.ms = Date.now() - started;
results.push(record);
console.log(`${record.status === "ok" ? "OK " : "FAIL"} ${id.padEnd(20)} ${String(record.ms).padStart(7)}ms ${record.bytes}B ${record.warnings[0] ?? ""}`);
await page.close().catch(() => {});
}
}
} finally {
await browser.close();
}
const summary = {
schema: "freecad-web/ui-capture/v1",
url,
viewport: { width, height },
captured: results.length,
ok: results.filter(item => item.status === "ok").length,
failed: results.filter(item => item.status !== "ok").length,
skipped,
results,
};
fs.mkdirSync(path.dirname(reportPath), { recursive: true });
fs.writeFileSync(reportPath, `${JSON.stringify(summary, null, 2)}\n`);
console.log(JSON.stringify({ ok: summary.failed === 0, captured: summary.captured, failed: summary.failed, report: reportPath }));
process.exit(summary.failed === 0 ? 0 : 1);

View File

@@ -0,0 +1,336 @@
#!/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 <path> [--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));

View File

@@ -0,0 +1,62 @@
#!/usr/bin/env node
// Builds the authoritative inventory of Web FreeCAD UI surfaces: every shell
// region, dock, task panel, dialog, preference page, menu, toolbar, status bar
// item and viewport tool, paired with its React owner and desktop source.
//
// node tools/fcweb/ui-surface-inventory.mjs
// node tools/fcweb/ui-surface-inventory.mjs --stable # reproducible bytes
// node tools/fcweb/ui-surface-inventory.mjs --check # compare, exit 1 on drift
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { scanSurfaces } from "./ui-surface-scan.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(here, "../..");
const desktopRoot = path.join(repoRoot, "freecad-source");
const webSrcRoot = path.join(repoRoot, "web", "src");
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 outPath = path.resolve(argValue("--out", path.join(here, "out", "ui-surface-inventory.json")));
const stable = args.includes("--stable") || args.includes("--check");
const fail = (message, code = 2) => {
console.error(`[ui-surface-inventory] ${message}`);
process.exit(code);
};
if (!fs.existsSync(inventoryPath)) fail(`missing inventory: ${inventoryPath} (run ui-inventory.mjs first)`);
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
const manualFeaturesPath = path.join(repoRoot, "web", "manual", "data", "manual-features.json");
const manualFeatures = fs.existsSync(manualFeaturesPath)
? JSON.parse(fs.readFileSync(manualFeaturesPath, "utf8"))
: null;
const result = scanSurfaces({ repoRoot, desktopRoot, inventory, manualFeatures, webSrcRoot, stable });
if (args.includes("--check")) {
if (!fs.existsSync(outPath)) fail(`--check: missing ${outPath}`, 1);
const previous = JSON.parse(fs.readFileSync(outPath, "utf8"));
const strip = value => JSON.stringify({ ...value, generatedAt: "__stable__" });
if (strip(previous) !== strip(result)) fail("--check: surface inventory is stale; rebuild without --check", 1);
console.log(JSON.stringify({ ok: true, checked: outPath, total: result.counts.total, gaps: result.counts.gaps }));
process.exit(0);
}
fs.mkdirSync(path.dirname(outPath), { recursive: true });
fs.writeFileSync(outPath, `${JSON.stringify(result, null, 2)}\n`);
console.log(JSON.stringify({
ok: true,
out: outPath,
total: result.counts.total,
byCategory: result.counts.byCategory,
byStatus: result.counts.byStatus,
gaps: result.counts.gaps,
}));

View File

@@ -0,0 +1,562 @@
// Scans the Web FreeCAD shell, workbench panels, task panels and dialogs, and
// pairs each UI surface with its React owner and the desktop FreeCAD source it
// mirrors. The result feeds tools/fcweb/ui-surface-inventory.mjs and, through
// docs/current/ui-design/source.html markers, the generated UI design document.
import fs from "node:fs";
import path from "node:path";
const SOURCE_EXT = /\.(tsx?|jsx?)$/;
const CJK = /[一-龥]/;
export const CATEGORIES = [
"shell-region",
"dock",
"task-panel",
"modal-dialog",
"preferences-page",
"menu",
"toolbar",
"statusbar",
"viewport-tool",
];
const CHAPTER_STATUS = {
renders: "implemented",
conditional: "partial",
fallback: "partial",
unreachable: "boundary",
};
const TERMS = {
attachment: "附着",
boolean: "布尔运算",
builder: "形状构建器",
box: "立方体",
chamfer: "倒角",
clone: "克隆",
common: "交集",
compound: "复合",
cone: "圆锥",
cut: "差集",
cylinder: "圆柱",
datum: "基准",
draft: "拔模",
dressup: "修饰",
extrude: "拉伸",
fillet: "圆角",
fragment: "切片",
fuse: "并集",
groove: "沟槽",
helix: "螺旋",
hole: "孔",
ifc: "IFC",
joint: "关节",
loft: "放样",
mirror: "镜像",
model: "模型",
multi: "多重",
offset: "偏移",
pad: "凸台",
pattern: "阵列",
pipe: "管道",
pocket: "凹槽",
primitive: "基本体",
prism: "棱柱",
revolution: "旋转",
scale: "缩放",
section: "截面",
shape: "形状",
shapebinder: "形状绑定",
sketch: "草图",
sphere: "球体",
spreadsheet: "电子表格",
thickness: "抽壳",
torus: "圆环",
transform: "变换",
tube: "管",
validate: "校验",
wedge: "楔体",
};
const MODULE_ZH = {
Assembly: "装配",
BIM: "BIM",
CAM: "CAM",
Cloud: "云",
Draft: "Draft",
Fem: "FEM",
Help: "帮助",
Import: "导入",
Inspection: "检测",
JtReader: "JT 读取",
Material: "材料",
Measure: "测量",
Mesh: "网格",
MeshPart: "网格零件",
Part: "零件",
PartDesign: "零件设计",
Plot: "绘图",
Points: "点云",
ReverseEngineering: "逆向工程",
Robot: "机器人",
Sandbox: "沙箱",
Show: "显示",
Sketcher: "草图器",
Spreadsheet: "电子表格",
Start: "开始",
Surface: "曲面",
TechDraw: "工程图",
TemplatePyMod: "模板",
Test: "测试",
Tux: "Tux",
Web: "Web",
};
const MENU_ZH = {
File: "文件",
Edit: "编辑",
View: "视图",
Tools: "工具",
Macro: "宏",
Windows: "窗口",
Help: "帮助",
Sketch: "草图",
Part: "零件",
"Part Design": "零件设计",
Assembly: "装配",
Measure: "测量",
Mesh: "网格",
"Mesh Design": "网格设计",
Surface: "曲面",
Spreadsheet: "电子表格",
TechDraw: "工程图",
Robot: "机器人",
Material: "材料",
Inspection: "检测",
"Reverse Engineering": "逆向工程",
Points: "点云",
Draft: "Draft",
Arch: "建筑",
BIM: "BIM",
Path: "CAM",
CAM: "CAM",
FEM: "FEM",
Std: "标准",
};
const TOOLBAR_ZH = {
File: "文件",
Workbench: "工作台",
Macro: "宏",
View: "视图",
Structure: "结构",
"Std View": "标准视图",
Solids: "实体",
"Part Tools": "零件工具",
"Boolean Tools": "布尔工具",
"Part Design Helper Features": "零件设计辅助特征",
"Part Design Modeling Features": "零件设计建模特征",
"Part Design Dressup Features": "零件设计修饰特征",
"Sketch Tools": "草图工具",
"Sketcher Tools": "草图器工具",
"Draft Tools": "Draft 工具",
"Arch Tools": "建筑工具",
"BIM Tools": "BIM 工具",
"Mesh Tools": "网格工具",
"FEM Tools": "FEM 工具",
"TechDraw Tools": "工程图工具",
"Robot Tools": "机器人工具",
};
const SHELL_SURFACES = [
{ id: "shell:menubar", nameZh: "菜单栏", file: "web/src/shell/menu-bar.tsx", symbol: "DesktopMenuBar", desktop: "src/Gui/MenuManager.cpp", desktopSymbol: "MenuManager" },
{ id: "shell:toolbar", nameZh: "工具栏", file: "web/src/shell/toolbar.tsx", symbol: "DesktopToolbars", desktop: "src/Gui/ToolBarManager.cpp", desktopSymbol: "ToolBarManager" },
{ id: "shell:workbench-menu", nameZh: "工作台菜单", file: "web/src/shell/workbench-menu.tsx", symbol: "ParityWorkbenchMenu", desktop: "src/Gui/Workbench.cpp", desktopSymbol: "Workbench::setupMenuBar" },
{ id: "shell:workbench-toolbars", nameZh: "工作台工具栏", file: "web/src/shell/workbench-toolbars.tsx", symbol: "ParityWorkbenchToolbars", desktop: "src/Gui/Workbench.cpp", desktopSymbol: "Workbench::setupToolBars" },
{ id: "shell:task-view", nameZh: "任务面板视图", file: "web/src/shell/task-frame.tsx", symbol: "TaskFrame", desktop: "src/Gui/TaskView/TaskView.cpp", desktopSymbol: "TaskView" },
{ id: "shell:dock-overlay", nameZh: "停靠覆盖层", file: "web/src/dock-overlay-host.tsx", symbol: "DockOverlayHost", desktop: "src/Gui/DockWindowManager.cpp", desktopSymbol: "DockWindowManager" },
{ id: "shell:bottom-dock", nameZh: "底部停靠(报告视图)", file: "web/src/shell/bottom-dock.tsx", symbol: "BottomDock", desktop: "src/Gui/MainWindow.cpp", desktopSymbol: "setupDockWindows" },
{ id: "shell:statusbar", nameZh: "状态栏", file: "web/src/project-shell.tsx", symbol: "App", desktop: "src/Gui/MainWindow.cpp", desktopSymbol: "statusBar" },
{ id: "shell:viewport", nameZh: "三维视口", file: "web/src/scene-viewport.tsx", symbol: "SceneViewport", desktop: "src/Gui/View3DInventor.cpp", desktopSymbol: "View3DInventor" },
{ id: "shell:python-console", nameZh: "Python 控制台", file: "web/src/shell/python-console.tsx", symbol: "PythonConsole", desktop: "src/Gui/PythonConsole.cpp", desktopSymbol: "PythonConsole" },
{ id: "shell:preferences", nameZh: "偏好设置对话框", file: "web/src/shell/preferences-dialog.tsx", symbol: "PreferencesDialog", desktop: "src/Gui/Dialogs/DlgPreferencesImp.cpp", desktopSymbol: "DlgPreferencesImp" },
{ id: "shell:workbench-frame", nameZh: "工作台框架", file: "web/src/shell/workbench-frame.tsx", symbol: "WorkbenchFrame", desktop: "src/Gui/Workbench.cpp", desktopSymbol: "Workbench" },
{ id: "shell:document-tabs", nameZh: "文档标签栏", file: "web/src/project-shell.tsx", symbol: "App", desktop: "src/Gui/MainWindow.cpp", desktopSymbol: "tabbedDocuments" },
{ id: "shell:utility-menus", nameZh: "工具菜单(偏好/快捷键/停靠)", file: "web/src/shell/utility-menus.tsx", symbol: "UtilityMenus", desktop: "src/Gui/CommandStd.cpp", desktopSymbol: "Std_ViewDockMenu" },
];
const VIEWPORT_TOOLS = [
{ id: "viewport:navigation", nameZh: "导航样式切换", file: "web/src/shell/preferences-dialog.tsx", symbol: "PreferencesDialog", desktop: "src/Gui/NavigationStyle.cpp", desktopSymbol: "NavigationStyle" },
{ id: "viewport:navigation-hints", nameZh: "导航提示与手势", file: "web/src/scene-navigation.ts", symbol: "SceneNavigation", desktop: "src/Gui/NavigationStyle.cpp", desktopSymbol: "NavigationStyle" },
{ id: "viewport:fit-all", nameZh: "适配全部", file: "web/src/scene-viewport.tsx", symbol: "SceneViewport", desktop: "src/Gui/View3DInventorViewer.cpp", desktopSymbol: "Std_ViewFitAll" },
{ id: "viewport:view-directions", nameZh: "标准视图方向", file: "web/src/scene-viewport.tsx", symbol: "SceneViewport", desktop: "src/Gui/View3DInventorViewer.cpp", desktopSymbol: "Std_ViewAxo" },
{ id: "viewport:selection", nameZh: "选择与拾取", file: "web/src/scene-viewport.tsx", symbol: "SceneViewport", desktop: "src/Gui/Selection.cpp", desktopSymbol: "SelectionSingleton" },
{ id: "viewport:clipping", nameZh: "剖切面", file: "web/src/scene-viewport.tsx", symbol: "SceneViewport", desktop: "src/Gui/View3DInventor.cpp", desktopSymbol: "Std_ToggleClipPlane" },
{ id: "viewport:transform", nameZh: "变换手柄", file: "web/src/scene-viewport.tsx", symbol: "SceneViewport", desktop: "src/Gui/View3DInventor.cpp", desktopSymbol: "Std_TransformManip" },
{ id: "viewport:view-cube", nameZh: "视图立方/坐标轴", file: "web/src/scene-viewport.tsx", symbol: "SceneViewport", desktop: "src/Gui/View3DInventor.cpp", desktopSymbol: "navigation cube" },
];
const PREFERENCES_PAGES = [
{ id: "preferences:units", nameZh: "单位系统", file: "web/src/shell/preferences-dialog.tsx", symbol: "PreferencesDialog", desktop: "src/Gui/PreferencePages/DlgSettingsGeneral.ui", desktopSymbol: "Unit system" },
{ id: "preferences:navigation", nameZh: "导航样式", file: "web/src/shell/preferences-dialog.tsx", symbol: "PreferencesDialog", desktop: "src/Gui/PreferencePages/DlgSettingsNavigation.ui", desktopSymbol: "Navigation style" },
{ id: "preferences:theme", nameZh: "主题", file: "web/src/shell/preferences-dialog.tsx", symbol: "PreferencesDialog", desktop: "src/Gui/PreferencePages/DlgSettingsUI.ui", desktopSymbol: "Theme" },
{ id: "preferences:grid", nameZh: "网格显示", file: "web/src/shell/preferences-dialog.tsx", symbol: "PreferencesDialog", desktop: "src/Gui/PreferencePages/DlgSettings3DView.ui", desktopSymbol: "Show grid" },
];
const DOCK_ZH = {
Std_DockOverlay: "停靠覆盖层",
Std_DockOverlayAll: "全部停靠覆盖",
Std_DockOverlayTransparentAll: "全部透明覆盖",
Std_DockOverlayToggle: "切换覆盖层",
Std_DockOverlayToggleTransparent: "切换透明覆盖",
Std_DockOverlayMouseTransparent: "鼠标穿透",
Std_DockOverlayToggleLeft: "左侧覆盖",
Std_DockOverlayToggleRight: "右侧覆盖",
Std_DockOverlayToggleTop: "顶部覆盖",
Std_DockOverlayToggleBottom: "底部覆盖",
Std_TreeViewMVC: "模型树(MVC)",
};
export function walkSource(root, { maxDepth = 6 } = {}) {
const out = [];
const walk = (dir, depth) => {
if (depth > maxDepth) return;
let entries = [];
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
for (const entry of entries) {
if (entry.name === "node_modules" || entry.name === "tests" || entry.name.startsWith(".")) continue;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) walk(full, depth + 1);
else if (SOURCE_EXT.test(entry.name)) out.push(full);
}
};
walk(root, 0);
return out.sort();
}
function exportsOf(text) {
const names = [];
for (const match of text.matchAll(/export\s+(?:async\s+)?function\s+([A-Za-z0-9_]+)/g)) names.push(match[1]);
for (const match of text.matchAll(/export\s+const\s+([A-Za-z0-9_]+)/g)) names.push(match[1]);
for (const match of text.matchAll(/export\s+class\s+([A-Za-z0-9_]+)/g)) names.push(match[1]);
return [...new Set(names)];
}
function existsFile(file) {
try { return fs.statSync(file).isFile(); } catch { return false; }
}
function buildDesktopIndex(desktopRoot) {
const index = [];
const addDir = dir => {
let entries = [];
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
for (const entry of entries) {
if (!entry.isFile()) continue;
if (!/^(Task|Dlg|Preference)/i.test(entry.name)) continue;
if (!/\.(cpp|h|ui)$/i.test(entry.name)) continue;
index.push({ file: path.relative(desktopRoot, path.join(dir, entry.name)), base: entry.name });
}
};
addDir(path.join(desktopRoot, "src/Gui/Dialogs"));
addDir(path.join(desktopRoot, "src/Gui/PreferencePages"));
let mods = [];
try { mods = fs.readdirSync(path.join(desktopRoot, "src/Mod"), { withFileTypes: true }); } catch { mods = []; }
for (const mod of mods) {
if (!mod.isDirectory()) continue;
addDir(path.join(desktopRoot, "src/Mod", mod.name, "Gui"));
}
return index.sort((a, b) => a.file.localeCompare(b.file));
}
function matchDesktop(desktopIndex, moduleId, stem) {
const tokens = stem.split("-").filter(token => token && token !== "task"
&& token !== moduleId.toLowerCase() && token !== "parameters");
if (!tokens.length) return null;
const moduleDir = `/src/Mod/${moduleId}/Gui/`;
const candidates = desktopIndex.filter(item => tokens.every(token =>
item.base.toLowerCase().replace(/[^a-z0-9]/g, "").includes(token.replace(/[^a-z0-9]/g, ""))));
if (!candidates.length) return null;
const preferred = candidates.find(item => item.file.includes(moduleDir)) ?? candidates[0];
return { file: `freecad-source/${preferred.file}`, symbol: preferred.base.replace(/\.(cpp|h|ui)$/i, "") };
}
function zhTerm(stem) {
const parts = stem.split("-").filter(Boolean);
for (const part of parts) {
if (TERMS[part]) return TERMS[part];
}
return null;
}
function labelZh(map, label) {
const clean = String(label ?? "").replace(/&/g, "").trim();
return map[clean] ?? clean;
}
export function scanSurfaces({ repoRoot, desktopRoot, inventory, manualFeatures, webSrcRoot, stable = false }) {
const surfaces = [];
const push = surface => {
surfaces.push({
workbench: surface.workbench ?? null,
owner: surface.file ? { file: surface.file, symbol: surface.symbol ?? null, mountPoint: surface.mountPoint ?? null } : null,
desktopRef: surface.desktop ? { file: `freecad-source/${surface.desktop.replace(/^freecad-source\//, "")}`, symbol: surface.desktopSymbol ?? null } : null,
status: surface.status ?? "implemented",
screenshotId: surface.screenshotId ?? null,
manualAnchor: surface.manualAnchor ?? null,
id: surface.id,
category: surface.category,
moduleId: surface.moduleId ?? null,
nameZh: surface.nameZh,
note: surface.note ?? null,
});
};
const sourceFiles = walkSource(webSrcRoot).filter(file => !/-test\.tsx?$/i.test(file));
const texts = new Map();
for (const file of sourceFiles) {
try { texts.set(file, fs.readFileSync(file, "utf8")); } catch { /* skip unreadable */ }
}
const refCount = (symbol, selfFile, stem) => {
if (!symbol) return 0;
let count = 0;
for (const [file, text] of texts) {
if (file === selfFile) continue;
if (text.includes(symbol) || (stem && text.includes(stem))) count += 1;
}
return count;
};
// 1. Shell regions and status bar.
for (const item of SHELL_SURFACES) {
const file = path.join(repoRoot, item.file);
const present = existsFile(file);
const desktop = item.desktop && existsFile(path.join(desktopRoot, item.desktop)) ? item.desktop : null;
push({
id: item.id,
category: item.id === "shell:statusbar" ? "statusbar" : "shell-region",
moduleId: null,
nameZh: item.nameZh,
file: item.file,
symbol: item.symbol,
mountPoint: present ? (texts.get(file)?.includes(`<${item.symbol}`) ? "rendered" : "exported") : null,
desktop,
desktopSymbol: item.desktopSymbol,
status: present ? "implemented" : "gap",
note: present ? null : `缺少 React owner:${item.file}`,
});
}
// 2. Docks (dock overlay commands + manifest docks).
const dockCommandsPath = path.join(webSrcRoot, "dock-overlay-commands.json");
let dockCommands = {};
try { dockCommands = JSON.parse(fs.readFileSync(dockCommandsPath, "utf8")); } catch { dockCommands = {}; }
for (const key of Object.keys(dockCommands).sort()) {
push({
id: `dock:${key}`,
category: "dock",
moduleId: null,
nameZh: DOCK_ZH[key] ?? key,
file: "web/src/dock-overlay-host.tsx",
symbol: "DockOverlayHost",
mountPoint: "rendered",
desktop: "src/Gui/DockWindowManager.cpp",
desktopSymbol: key,
status: "implemented",
note: null,
});
}
for (const chapter of inventory.chapters) {
for (const dock of (chapter.manifest?.docks ?? [])) {
push({
id: `dock:${chapter.id}:${dock}`,
category: "dock",
moduleId: chapter.id,
nameZh: DOCK_ZH[dock] ?? dock,
file: "web/src/dock-overlay-host.tsx",
symbol: "DockOverlayHost",
mountPoint: "rendered",
desktop: chapter.manifest?.source?.replace(/^freecad-source\//, "") ?? null,
desktopSymbol: dock,
status: CHAPTER_STATUS[chapter.status] ?? "partial",
note: null,
});
}
}
// 3. Task panels from the workbench inventory.
const desktopIndex = buildDesktopIndex(desktopRoot);
for (const chapter of inventory.chapters) {
for (const panel of (chapter.taskPanels ?? [])) {
const stem = panel.file.replace(/\.tsx?$/, "");
let file = path.join(webSrcRoot, panel.file);
if (!existsFile(file)) {
const found = sourceFiles.find(candidate => path.basename(candidate) === panel.file);
if (found) file = found;
}
const present = existsFile(file);
const text = present ? texts.get(file) ?? "" : "";
const symbol = exportsOf(text).find(name => /Task$/.test(name)) ?? exportsOf(text)[0] ?? null;
const refs = present ? refCount(symbol, file, stem) : 0;
const matched = matchDesktop(desktopIndex, chapter.id, stem);
const title = (panel.titles ?? []).find(value => CJK.test(value)) ?? (panel.titles ?? [])[0] ?? stem;
const term = zhTerm(stem);
push({
id: `task:${chapter.id}:${stem}`,
category: "task-panel",
moduleId: chapter.id,
nameZh: term ? `${MODULE_ZH[chapter.id] ?? chapter.id} · ${term}` : `${MODULE_ZH[chapter.id] ?? chapter.id} · ${title}`,
file: present ? path.relative(repoRoot, file) : panel.file,
symbol,
mountPoint: refs > 0 ? "referenced" : present ? "isolated" : null,
desktop: matched?.file ?? chapter.manifest?.source ?? null,
desktopSymbol: matched?.symbol ?? null,
status: !present ? "gap" : refs > 0 ? "implemented" : "partial",
note: !present ? `缺少任务面板文件:${panel.file}` : refs === 0 ? "组件未被 shell 或工作台面板引用" : null,
});
}
}
// 4. Modal dialogs discovered from the shell.
const dialogFiles = sourceFiles.filter(file =>
/(dialog|preferences|palette|shortcut|context-menu)[^/]*\.tsx$/i.test(file)
&& !/\/tests?\//.test(file)
&& !/shell-preview/.test(file)
&& !/-test\.tsx?$/i.test(file));
for (const file of dialogFiles) {
const rel = path.relative(repoRoot, file);
if (surfaces.some(item => item.owner?.file === rel)) continue;
const text = texts.get(file) ?? "";
const symbols = exportsOf(text);
const symbol = symbols[0] ?? null;
const stem = path.basename(file).replace(/\.tsx$/, "");
push({
id: `dialog:${stem}`,
category: /preferences/i.test(stem) ? "preferences-page" : "modal-dialog",
moduleId: null,
nameZh: /preferences/i.test(stem) ? "偏好设置" : stem,
file: rel,
symbol,
mountPoint: refCount(symbol, file, stem) > 0 ? "referenced" : "isolated",
desktop: /preferences/i.test(stem) ? "src/Gui/Dialogs/DlgPreferencesImp.cpp" : null,
desktopSymbol: /preferences/i.test(stem) ? "DlgPreferencesImp" : null,
status: symbol ? (refCount(symbol, file, stem) > 0 ? "implemented" : "partial") : "gap",
note: null,
});
}
// 5. Preference pages (the web preferences dialog exposes four groups).
for (const item of PREFERENCES_PAGES) {
push({
id: item.id,
category: "preferences-page",
moduleId: null,
nameZh: item.nameZh,
file: item.file,
symbol: item.symbol,
mountPoint: "rendered",
desktop: existsFile(path.join(desktopRoot, item.desktop)) ? item.desktop : null,
desktopSymbol: item.desktopSymbol,
status: "implemented",
note: null,
});
}
// 6. Viewport tools.
for (const item of VIEWPORT_TOOLS) {
const present = existsFile(path.join(repoRoot, item.file));
push({
id: item.id,
category: "viewport-tool",
moduleId: null,
nameZh: item.nameZh,
file: item.file,
symbol: item.symbol,
mountPoint: present ? "referenced" : null,
desktop: existsFile(path.join(desktopRoot, item.desktop)) ? item.desktop : null,
desktopSymbol: item.desktopSymbol,
status: present ? "implemented" : "gap",
note: present ? null : `缺少视口 owner:${item.file}`,
});
}
// 7. Workbench menus and toolbars from the inventory.
for (const chapter of inventory.chapters) {
const status = CHAPTER_STATUS[chapter.status] ?? "partial";
const moduleZh = MODULE_ZH[chapter.id] ?? chapter.id;
for (const menu of (chapter.menus ?? [])) {
const label = labelZh(MENU_ZH, menu.label);
push({
id: `menu:${chapter.id}:${slug(menu.label)}`,
category: "menu",
moduleId: chapter.id,
nameZh: `${moduleZh} · ${label} 菜单`,
file: "web/src/shell/workbench-menu.tsx",
symbol: "ParityWorkbenchMenu",
mountPoint: "rendered",
desktop: chapter.manifest?.source ?? null,
desktopSymbol: `setupMenuBar/${menu.label}`,
status,
note: status === "partial" ? "该工作台由 Python InitGui 注册,Web 端以静态菜单层级呈现:命令可执行,二级分组被压平。" : null,
});
}
for (const toolbar of (chapter.toolbars ?? [])) {
const label = labelZh(TOOLBAR_ZH, toolbar.name);
push({
id: `toolbar:${chapter.id}:${slug(toolbar.name)}`,
category: "toolbar",
moduleId: chapter.id,
nameZh: `${moduleZh} · ${label} 工具栏`,
file: "web/src/shell/workbench-toolbars.tsx",
symbol: "ParityWorkbenchToolbars",
mountPoint: "rendered",
desktop: chapter.manifest?.source ?? null,
desktopSymbol: `setupToolBars/${toolbar.name}`,
status,
note: status === "partial" ? "该工作台由 Python InitGui 注册,Web 端以静态工具栏呈现:命令可执行,分组顺序以清单为准。" : null,
});
}
}
// 8. Manual coverage evidence.
const chapterAnchors = new Map();
for (const chapter of manualFeatures?.chapters ?? []) {
chapterAnchors.set(chapter.id, chapter.id);
}
for (const surface of surfaces) {
const moduleId = surface.moduleId ?? surface.workbench;
if (moduleId && chapterAnchors.has(moduleId)) surface.manualAnchor = chapterAnchors.get(moduleId);
else if (!moduleId) surface.manualAnchor = "ch16";
}
// Deterministic ordering and counts.
surfaces.sort((a, b) => a.category.localeCompare(b.category) || a.id.localeCompare(b.id));
const byCategory = {};
const byStatus = {};
const byModule = {};
for (const surface of surfaces) {
byCategory[surface.category] = (byCategory[surface.category] ?? 0) + 1;
byStatus[surface.status] = (byStatus[surface.status] ?? 0) + 1;
if (surface.moduleId) byModule[surface.moduleId] = (byModule[surface.moduleId] ?? 0) + 1;
}
const gaps = surfaces.filter(surface => surface.status === "gap").map(surface => surface.id);
return {
schema: "freecad-web/ui-surface-inventory/v1",
generatedAt: stable ? "1970-01-01T00:00:00.000Z" : new Date().toISOString(),
sources: {
inventory: "tools/fcweb/out/ui-inventory.json",
webSrc: "web/src",
desktop: "freecad-source",
manualFeatures: "web/manual/data/manual-features.json",
},
counts: { total: surfaces.length, byCategory, byStatus, byModule, gaps: gaps.length },
surfaces,
gaps,
};
}
function slug(text) {
return String(text ?? "").toLowerCase().replace(/[^a-z0-9一-龥]+/g, "-").replace(/^-+|-+$/g, "");
}
export { CHAPTER_STATUS };