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>
3184
docs/current/ui-design/data/doc-check-last-run.json
Normal file
3184
docs/current/ui-design/data/doc-check.json
Normal file
2347
docs/current/ui-design/data/gap-register.json
Normal file
46
docs/current/ui-design/data/workbench-overrides.json
Normal file
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"schema": "freecad-web/ui-workbench-overrides/v1",
|
||||
"note": "Workbench ids differ between the select control, the GUI manifest and the web module registry. This file is the single authority for which workbench a chapter describes and whether it renders in the main shell.",
|
||||
"statusValues": {
|
||||
"renders": "可在主外壳中切换并渲染",
|
||||
"fallback": "可选中但内容回退到另一工作台",
|
||||
"unreachable": "主外壳内无法到达",
|
||||
"conditional": "需要前置条件(如已打开原生文档)",
|
||||
"manifest-only": "只存在于桌面 GUI 清单,Web 端不提供"
|
||||
},
|
||||
"workbenches": [
|
||||
{ "id": "Part", "status": "renders", "title": "Part 零件", "summary": "基础实体、布尔运算、导入导出与形状修复。" },
|
||||
{ "id": "Sketcher", "status": "renders", "title": "Sketcher 草图", "summary": "二维几何与约束求解,是特征建模的输入。" },
|
||||
{ "id": "PartDesign", "status": "renders", "title": "PartDesign 零件设计", "summary": "Body 内的草图特征链:拉伸、切除、旋转、齿轮与修饰。" },
|
||||
{ "id": "Spreadsheet", "status": "renders", "title": "Spreadsheet 电子表格", "summary": "参数表与表达式,驱动其他对象属性。" },
|
||||
{ "id": "Surface", "status": "renders", "title": "Surface 曲面", "summary": "填充、拉伸、混合曲面与曲面延伸。" },
|
||||
{ "id": "Assembly", "status": "renders", "title": "Assembly 装配", "summary": "装配对象、插入链接、关节、求解、BOM 与爆炸视图。" },
|
||||
{ "id": "Draft", "status": "renders", "title": "Draft 草图与制图工具", "summary": "线、面、阵列、文字与风格设置。" },
|
||||
{ "id": "Architecture", "status": "fallback", "fallbackTo": "Part", "title": "Architecture 建筑(回退)", "summary": "选择后工具栏回退到 Part;建筑功能实际由 BIM 工作台提供。" },
|
||||
{ "id": "BIM", "status": "renders", "title": "BIM 建筑信息模型", "summary": "墙体、楼层、门窗、IFC 读写与工程量。" },
|
||||
{ "id": "CAM", "status": "renders", "title": "CAM 加工", "summary": "作业、刀具、刀路策略、3D 仿真与后处理。" },
|
||||
{ "id": "Cloud", "status": "renders", "title": "Cloud 云端", "summary": "云端文档与协作入口。" },
|
||||
{ "id": "Fem", "status": "renders", "title": "Fem 有限元", "summary": "材料、边界条件、网格与求解器。" },
|
||||
{ "id": "Help", "status": "renders", "title": "Help 帮助", "summary": "在线帮助下载与帮助偏好。" },
|
||||
{ "id": "Import", "status": "renders", "title": "Import 导入", "summary": "多格式导入导出(STEP、IGES、STL、OBJ 等)。" },
|
||||
{ "id": "Inspection", "status": "renders", "title": "Inspection 检测", "summary": "尺寸检测与可视化检查。" },
|
||||
{ "id": "JtReader", "status": "renders", "title": "JtReader JT 读取", "summary": "JT 格式读取。" },
|
||||
{ "id": "Material", "status": "renders", "title": "Material 材料", "summary": "材料库、外观与材料指定。" },
|
||||
{ "id": "Measure", "status": "renders", "title": "Measure 测量", "summary": "距离、角度、质量属性。" },
|
||||
{ "id": "Mesh", "status": "renders", "title": "Mesh 网格", "summary": "网格导入、修复、布尔与抽稀。" },
|
||||
{ "id": "MeshPart", "status": "renders", "title": "MeshPart 网格零件", "summary": "网格转形状、截面与曲线投影。" },
|
||||
{ "id": "Points", "status": "renders", "title": "Points 点云", "summary": "点云导入、合并与重采样。" },
|
||||
{ "id": "ReverseEngineering", "status": "renders", "title": "ReverseEngineering 逆向", "summary": "网格分割与曲面拟合。" },
|
||||
{ "id": "Robot", "status": "renders", "title": "Robot 机器人", "summary": "机器人模型、轨迹与仿真。" },
|
||||
{ "id": "Sandbox", "status": "renders", "title": "Sandbox 沙箱", "summary": "实验性工具与示例部件。" },
|
||||
{ "id": "Start", "status": "renders", "title": "Start 起始页", "summary": "启动面板:新建、最近文件与参考模型。" },
|
||||
{ "id": "TechDraw", "status": "renders", "title": "TechDraw 工程图", "summary": "投影视图、剖视、标注、符号与图框。" },
|
||||
{ "id": "Test", "status": "renders", "title": "Test 测试", "summary": "框架自检与界面示例命令。" },
|
||||
{ "id": "Tux", "status": "renders", "title": "Tux 示例", "summary": "示例模块。" },
|
||||
{ "id": "TemplatePyMod", "status": "conditional", "title": "TemplatePyMod 模板模块", "summary": "需要先存在原生文档才可选;提供 Python 模块模板示例。" },
|
||||
{ "id": "Plot", "status": "unreachable", "reason": "不在主外壳的工作台下拉中;仅能通过「Open Plot session」按钮进入,且会以 window.location.assign 跳出外壳。", "title": "Plot 绘图(外部会话)", "summary": "二维绘图会话,落在独立页面。" },
|
||||
{ "id": "Show", "status": "unreachable", "reason": "不在主外壳的工作台下拉中,没有进入入口。", "title": "Show 显示(不可达)", "summary": "剖切与显示控制。" },
|
||||
{ "id": "Web", "status": "unreachable", "reason": "不在主外壳的工作台下拉中,没有进入入口。", "title": "Web 工具(不可达)", "summary": "文档结构、宏调试、选择过滤等 Web 化工具。" },
|
||||
{ "id": "OpenSCAD", "status": "manifest-only", "reason": "仅存在于桌面 GUI 清单;Web 端整体不实现。", "title": "OpenSCAD(不实现)", "summary": "Web 端不提供该工作台。" }
|
||||
]
|
||||
}
|
||||
579
docs/current/ui-design/source.html
Normal file
@@ -0,0 +1,579 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>FreeCAD 1.2 Web · UI 布局与功能设计文档</title>
|
||||
<style>
|
||||
:root{
|
||||
--bg:#0d1319;--panel:#151d25;--panel2:#1b252f;--line:#2a3742;--text:#e7edf3;--muted:#93a7b4;
|
||||
--accent:#4fb3c8;--ok:#7fdc9f;--warn:#f2c46d;--bad:#ff9e9e;
|
||||
--mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
html{scroll-behavior:smooth}
|
||||
body{margin:0;background:var(--bg);color:var(--text);font:16px/1.75 -apple-system,"Segoe UI","Noto Sans SC",system-ui,sans-serif}
|
||||
header.top{position:sticky;top:0;z-index:20;background:rgba(13,19,25,.96);backdrop-filter:blur(8px);border-bottom:1px solid var(--line)}
|
||||
.bar{max-width:1200px;margin:0 auto;padding:12px 22px;display:flex;align-items:center;gap:14px;flex-wrap:wrap}
|
||||
.brand{background:var(--accent);color:#071219;font-weight:800;border-radius:6px;padding:5px 9px;text-decoration:none;font-size:14px}
|
||||
.bar h1{font-size:16.5px;margin:0;font-weight:600}
|
||||
.bar .ver{margin-left:auto;color:var(--muted);font-size:13px}
|
||||
.wrap{max-width:1200px;margin:0 auto;padding:26px 22px 90px;display:grid;grid-template-columns:220px minmax(0,1fr);gap:34px}
|
||||
nav.toc{position:sticky;top:74px;align-self:start;font-size:13.5px;max-height:calc(100vh - 100px);overflow:auto}
|
||||
nav.toc strong{display:block;color:var(--muted);font-size:11.5px;letter-spacing:.08em;text-transform:uppercase;margin:0 0 8px}
|
||||
nav.toc a{display:block;color:#a9bcc8;text-decoration:none;padding:5px 10px;border-left:2px solid transparent;border-radius:0 6px 6px 0}
|
||||
nav.toc a:hover{color:var(--accent);background:#121b23}
|
||||
nav.toc a.sub{padding-left:22px;font-size:12.5px;color:#8ea3b0}
|
||||
main{min-width:0}
|
||||
h2{font-size:26px;margin:56px 0 10px;padding-top:6px;border-top:1px solid var(--line)}
|
||||
h2:first-of-type{border-top:0;margin-top:0}
|
||||
h3{font-size:19px;margin:30px 0 8px;color:#cfe0ea}
|
||||
h4{font-size:15.5px;margin:22px 0 6px;color:#b9cbd7}
|
||||
p{color:#cfdae2}
|
||||
.lead{font-size:18px;color:#b9cbd7}
|
||||
.muted{color:var(--muted)}
|
||||
.card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:16px 20px;margin:16px 0}
|
||||
.note{background:#132029;border-left:3px solid var(--accent);padding:10px 14px;border-radius:0 8px 8px 0;color:#c3d4de;font-size:14.5px}
|
||||
.warnbox{background:#241f14;border-left:3px solid var(--warn);padding:10px 14px;border-radius:0 8px 8px 0;color:#e8dcc0;font-size:14.5px}
|
||||
.grid{display:grid;gap:14px}
|
||||
.grid.two{grid-template-columns:repeat(auto-fit,minmax(280px,1fr))}
|
||||
.grid.three{grid-template-columns:repeat(auto-fit,minmax(190px,1fr))}
|
||||
.stat{background:var(--panel2);border:1px solid var(--line);border-radius:10px;padding:13px 15px}
|
||||
.stat b{display:block;font-size:24px;line-height:1.15;color:var(--accent);font-variant-numeric:tabular-nums}
|
||||
.stat span{font-size:12.5px;color:var(--muted)}
|
||||
code,kbd{font-family:var(--mono);font-size:13.5px;background:#0a1016;border:1px solid var(--line);border-radius:4px;padding:1px 5px;overflow-wrap:anywhere}
|
||||
kbd{border-bottom-width:2px;padding:1px 6px}
|
||||
pre{background:#0a1016;border:1px solid var(--line);border-radius:10px;padding:13px 15px;overflow:auto;font-size:12.8px;line-height:1.6}
|
||||
pre code{background:none;border:0;padding:0}
|
||||
table{border-collapse:collapse;width:100%;font-size:14px;margin:14px 0}
|
||||
.table-scroll{overflow-x:auto;border:1px solid var(--line);border-radius:10px}
|
||||
th,td{border-bottom:1px solid var(--line);padding:8px 11px;text-align:left;vertical-align:top}
|
||||
tbody tr:last-child td{border-bottom:0}
|
||||
th{color:#9cb6c2;font-size:12px;letter-spacing:.04em;text-transform:uppercase;background:#121b23;position:sticky;top:0}
|
||||
td.num{font-family:var(--mono);font-size:12.8px;white-space:nowrap}
|
||||
.ok{color:var(--ok)}.bad{color:var(--bad)}.warn{color:var(--warn)}
|
||||
figure{margin:20px 0}
|
||||
figure img{width:100%;border-radius:10px;border:1px solid var(--line);display:block;background:#0a1016}
|
||||
figcaption{font-size:13px;color:var(--muted);margin-top:8px}
|
||||
/* ---- wireframe ---- */
|
||||
.wire{border:1px solid var(--line);border-radius:10px;overflow:hidden;background:#0a1016;font-size:11.5px}
|
||||
.wire .row{display:flex;border-bottom:1px solid var(--line)}
|
||||
.wire .row:last-child{border-bottom:0}
|
||||
.wire .cell{padding:8px 10px;border-right:1px solid var(--line);color:#b9cbd7;display:flex;align-items:center;gap:6px;flex-wrap:wrap}
|
||||
.wire .cell:last-child{border-right:0}
|
||||
.wire .cell b{color:var(--accent);font-family:var(--mono);font-size:11px;font-weight:600;margin-right:4px}
|
||||
.wire .grow{flex:1;min-width:0}
|
||||
.wire .tall{min-height:120px;align-items:flex-start}
|
||||
.wire .mono{font-family:var(--mono);font-size:10.5px;color:#7f95a3}
|
||||
.badge{display:inline-block;font-family:var(--mono);font-size:10.5px;background:#1d2b36;border:1px solid #2f4350;color:#8fb8c9;border-radius:999px;padding:1px 8px;margin-left:6px;vertical-align:1px}
|
||||
.anchor{scroll-margin-top:80px}
|
||||
@media(max-width:900px){
|
||||
.wrap{grid-template-columns:1fr;gap:18px}
|
||||
nav.toc{position:static;max-height:none;border:1px solid var(--line);border-radius:10px;padding:10px 6px}
|
||||
nav.toc a{display:inline-block;border-left:0;padding:4px 8px}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="top">
|
||||
<div class="bar">
|
||||
<a class="brand" href="#top">FC</a>
|
||||
<h1>FreeCAD 1.2 Web · UI 布局与功能设计文档</h1>
|
||||
<span class="ver">2026-11-20 · 依据当前源码与实测界面</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="wrap" id="top">
|
||||
<nav class="toc">
|
||||
<strong>目录</strong>
|
||||
<a href="#s1">1 · 概览</a>
|
||||
<a href="#s2">2 · 全局布局</a>
|
||||
<a class="sub" href="#s2-1">2.1 实测界面</a>
|
||||
<a class="sub" href="#s2-2">2.2 区域线框</a>
|
||||
<a class="sub" href="#s2-3">2.3 布局机制</a>
|
||||
<a href="#s3">3 · 区域详解</a>
|
||||
<a href="#s4">4 · 工作台系统</a>
|
||||
<a href="#s5">5 · 面板与对话框</a>
|
||||
<a href="#s6">6 · 视口交互</a>
|
||||
<a href="#s7">7 · 文件与 OPFS</a>
|
||||
<a href="#s8">8 · 键盘与可访问性</a>
|
||||
<a href="#s9">9 · 响应式</a>
|
||||
<a href="#s10">10 · 与桌面的差异</a>
|
||||
<a href="#s11">11 · 附录:选择器速查</a>
|
||||
</nav>
|
||||
|
||||
<main>
|
||||
|
||||
<!-- ============================ 1 ============================ -->
|
||||
<h2 id="s1" class="anchor">1 · 概览</h2>
|
||||
<p class="lead">FreeCAD 1.2 Web 是把桌面 FreeCAD 的几何内核(OCCT)与 Python 解释器编译为 WebAssembly 后,运行在浏览器里的完整 CAD 应用。本文档描述它的界面结构、各区域职责、交互方式与功能边界。</p>
|
||||
|
||||
<div class="grid three" style="margin:18px 0">
|
||||
<div class="stat"><b>31</b><span>可切换工作台(模块)</span></div>
|
||||
<div class="stat"><b>302</b><span>模块命令</span></div>
|
||||
<div class="stat"><b>13,091</b><span>Python API 条目</span></div>
|
||||
</div>
|
||||
|
||||
<h3>两个应用入口</h3>
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>页面</th><th>加载的组件</th><th>作用</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td class="num">web/index.html</td><td class="num">src/project-shell.tsx</td><td>主应用:标题栏、菜单、工具栏、树、属性、视口、状态栏</td></tr>
|
||||
<tr><td class="num">web/workbench.html</td><td class="num">src/workbench-shell.tsx</td><td>统一工作台子应用,被主应用以 iframe 嵌入任务框架</td></tr>
|
||||
<tr><td class="num">web/shell-preview.html</td><td class="num">src/shell/shell-preview.tsx</td><td>外壳演示页,不是正式应用</td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<div class="note"><strong>技术栈:</strong>React + TypeScript 负责界面;three.js 负责视口显示;Emscripten 编译的 WASM 探针按模块拆分,经 Web Worker 加载;几何与文档数据全部留在浏览器本地(OPFS)。页面需要 <code>Cross-Origin-Opener-Policy: same-origin</code> 与 <code>Cross-Origin-Embedder-Policy: require-corp</code> 才能启用 WASM 线程池。</div>
|
||||
|
||||
<!-- ============================ 2 ============================ -->
|
||||
<h2 id="s2" class="anchor">2 · 全局布局</h2>
|
||||
|
||||
<h3 id="s2-1" class="anchor">2.1 实测界面</h3>
|
||||
<p>下面是 1600×1000 视口下的真实界面(Start 工作台)。所有区域都在一屏内:</p>
|
||||
|
||||
<figure>
|
||||
<img id="shot-desktop" src="./web-freecad-ui-assets/ui-desktop-1600.png" alt="FreeCAD 1.2 Web 主界面截图:顶部为视图页签与工作台页签,其下是品牌栏、菜单栏、工具栏区,左侧 Objects 树,中间 Properties 面板,右侧主工作区与 3D 视口。" />
|
||||
<figcaption>主界面(1600×1000)。从左到右:Objects 树 · PROPERTIES 面板 · 主工作区;顶部自上而下:视图页签与工作台页签 · 品牌栏 · 菜单栏 · 工具栏区。</figcaption>
|
||||
</figure>
|
||||
|
||||
<div class="grid two">
|
||||
<div class="card">
|
||||
<h4 style="margin-top:0">纵向结构(自上而下)</h4>
|
||||
<ol style="margin:0;padding-left:20px;color:#cfdae2">
|
||||
<li><strong>视图页签 + 工作台页签</strong>:<code>3D 视图 / 文档 / 主链 / 工程 / 全线 / 工作台 / Python</code> 之后再接各工作台名(Assembly、BIM、CAM …)</li>
|
||||
<li><strong>品牌栏</strong>:FC 徽标、产品名、右侧当前文档名</li>
|
||||
<li><strong>菜单栏</strong>:Start ▸ File ▸ Edit ▸ View ▸ Tools ▸ Windows ▸ Help ▸(随工作台变化的最后一个菜单)</li>
|
||||
<li><strong>工具栏区</strong>:工具栏可见性/排列 → 工作台选择与命令按钮 → 视图导航控件</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h4 style="margin-top:0">横向结构(自左而右)</h4>
|
||||
<ol style="margin:0;padding-left:20px;color:#cfdae2">
|
||||
<li><strong>Objects 树</strong>(默认 240 px,可拖 180–420)</li>
|
||||
<li><strong>PROPERTIES 面板</strong>(默认 300 px,可拖 180–420),其中上半是属性、下半是 Tasks</li>
|
||||
<li><strong>主工作区</strong>:文档标题 → 视图工具 → 3D 视口 → 文档页签条(在底部)</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 id="s2-2" class="anchor">2.2 区域线框</h3>
|
||||
<p>下表是渲染顺序与区域编号(编号贯穿全文):</p>
|
||||
|
||||
<div class="wire" role="img" aria-label="界面区域线框图">
|
||||
<div class="row">
|
||||
<div class="cell grow"><b>①</b>视图页签 / 工作台页签<span class="mono">3D 视图 · 文档 · 主链 · 工程 · 全线 · 工作台 · Python · Assembly · BIM · …</span></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="cell grow"><b>②</b>品牌栏<span class="mono">FC · FreeCAD 1.2 Web</span><span class="grow"></span><span class="mono">当前文档名</span></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="cell grow"><b>③</b>菜单栏<span class="mono">Start ▸ File ▸ Edit ▸ View ▸ Tools ▸ Windows ▸ Help ▸ <工作台菜单></span></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="cell grow"><b>④a</b>工具栏可见性 / 排列<span class="mono">Toolbars · Arrange toolbars</span></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="cell grow"><b>④b</b>顶部工具栏坞<span class="mono">Workbench ⌄ · 命令按钮组 · 视图导航控件</span></div>
|
||||
</div>
|
||||
<div class="row tall">
|
||||
<div class="cell" style="width:22%"><b>⑤</b>Objects 树<span class="mono">240 px</span></div>
|
||||
<div class="cell" style="width:26%"><b>⑥</b>Properties + Tasks<span class="mono">300 px</span></div>
|
||||
<div class="cell grow"><b>⑦</b>主工作区 · 3D 视口<span class="mono">flex:1</span></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="cell grow"><b>⑧</b>状态栏(粘底)<span class="mono">role=status</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<figure>
|
||||
<img id="shot-mobile" src="./web-freecad-ui-assets/ui-mobile-390.png" alt="FreeCAD 1.2 Web 在 390×844 移动视口下的界面:工具栏换行堆叠,面板自上而下排列。" />
|
||||
<figcaption>同一界面在 390×844 下的表现:工具栏逐行换行,三栏布局改为纵向堆叠(见第 9 节)。</figcaption>
|
||||
</figure>
|
||||
|
||||
<h3 id="s2-3" class="anchor">2.3 布局机制</h3>
|
||||
<p>纯 CSS Grid,没有引入分栏库。外壳是两层嵌套网格,第三层是工作台子应用。</p>
|
||||
|
||||
<h4>外层:工具栏工作区</h4>
|
||||
<pre><code>/* persistent-toolbar-workspace.tsx:132 */
|
||||
.toolbar-workspace{
|
||||
display:grid;
|
||||
grid-template-columns: auto minmax(0,1fr) auto;
|
||||
grid-template-rows: auto auto minmax(0,1fr) auto;
|
||||
}
|
||||
/* 第 1 行:可见性/排列;第 2 行:顶部坞(跨全部列)
|
||||
第 3 行:左坞 | 内容 | 右坞;第 4 行:底部坞(跨全部列) */</code></pre>
|
||||
|
||||
<h4>内层:三栏工作区</h4>
|
||||
<pre><code>/* project-shell.tsx:1785 */
|
||||
.layout{
|
||||
display:grid;
|
||||
grid-template-columns: var(--tree-width) 5px var(--property-width) 5px minmax(0,1fr);
|
||||
}
|
||||
/* 列:树 | 分隔条 | 属性 | 分隔条 | 主工作区
|
||||
--tree-width 默认 240px,--property-width 默认 300px */</code></pre>
|
||||
|
||||
<div class="card">
|
||||
<p style="margin:0"><strong>分隔条</strong>是手写的 <code><div role="separator"></code>:鼠标拖动改宽度,键盘 <kbd>←</kbd>/<kbd>→</kbd> 每次 20 px,<kbd>Home</kbd> 收到 180 px,<kbd>End</kbd> 撑到 420 px。宽度保存在组件状态里。</p>
|
||||
</div>
|
||||
|
||||
<h4>子应用:统一工作台</h4>
|
||||
<pre><code>/* workbench-shell.tsx:397 */
|
||||
.layout{ display:grid; grid-template-columns:260px 340px minmax(0,1fr); }
|
||||
/* 模块列表 | 命令列表 | 舞台 */</code></pre>
|
||||
|
||||
<!-- ============================ 3 ============================ -->
|
||||
<h2 id="s3" class="anchor">3 · 区域详解</h2>
|
||||
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>#</th><th>区域</th><th>默认尺寸 / 行为</th><th>主要内容</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>①</td><td>页签条</td><td>整行,可横向滚动</td><td>视图页签与工作台页签;点击切换当前工作台,影响 ③ 的末项菜单与 ④b 的命令按钮</td></tr>
|
||||
<tr><td>②</td><td>品牌栏</td><td>约 56 px,flex 可换行</td><td>FC 徽标、产品名、当前文档名(右对齐)</td></tr>
|
||||
<tr><td>③</td><td>菜单栏</td><td>约 32 px,<code>role="menubar"</code></td><td>Start、File、Edit、View、Tools、Macro、Windows、Help 下拉;下拉面板绝对定位、最小宽 230 px</td></tr>
|
||||
<tr><td>④a</td><td>工具栏控制</td><td>一行</td><td>工具栏可见性菜单与「Arrange toolbars」排列模式</td></tr>
|
||||
<tr><td>④b</td><td>顶部工具栏坞</td><td>最小高 30 px,自动换行</td><td>工作台下拉框 + 各工具栏(Solids / Part Tools / Boolean Tools / Spreadsheet tools / 3D display controls / Robot),按钮 30×30</td></tr>
|
||||
<tr><td>⑤</td><td>Objects 树</td><td>240 px(180–420 可拖)</td><td>对象列表,三列:<em>Labels & Attributes</em> / <em>Description</em> / <em>Internal name</em>;每行有可见性复选框与类型图标;底部「New Group」</td></tr>
|
||||
<tr><td>⑥</td><td>Properties + Tasks</td><td>300 px(180–420 可拖)</td><td>上半:选中对象的属性编辑器(View 组、Placement、属性行);下半:Tasks 任务区与建模工具入口</td></tr>
|
||||
<tr><td>⑦</td><td>主工作区</td><td>占满剩余宽度</td><td>文档标题 → View Tools 下拉 → 3D 视口(330 px 起,可伸缩)→ 文档页签条(底部)</td></tr>
|
||||
<tr><td>⑧</td><td>状态栏</td><td>粘底,最小高 22 px</td><td>单行 <code>role="status"</code>:导入阶段、错误(红色)或成功(绿色)提示</td></tr>
|
||||
<tr><td>⑨</td><td>底部坞(可开)</td><td>固定浮层 180 px 高</td><td>Selection view / Report view / Python console 三个页签,可浮动、全屏、关闭</td></tr>
|
||||
<tr><td>⑩</td><td>任务框架(模态)</td><td>96vw × 92vh 上限</td><td>以 iframe 打开 <code>/workbench.html?module=…&command=…</code>,承载工作台任务面板</td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<div class="note"><strong>文档页签在底部</strong>,不在顶部——这是与桌面 FreeCAD 的明显差异;顶部那一排是视图/工作台页签,不是文档。</div>
|
||||
|
||||
<!--{{SHELL_REGION_CATALOG}}-->
|
||||
|
||||
<!--{{WORKBENCH_SURFACE_MATRIX}}-->
|
||||
|
||||
<h2 id="s4" class="anchor">4 · 工作台系统</h2>
|
||||
<p class="lead">工作台(Workbench)是功能的分组单位。切换工作台会更换工具栏按钮组、菜单末项,并决定任务面板里可用的建模工具。</p>
|
||||
|
||||
<div class="grid three" style="margin:18px 0">
|
||||
<div class="stat"><b>31</b><span>Web 端模块</span></div>
|
||||
<div class="stat"><b>302</b><span>模块命令</span></div>
|
||||
<div class="stat"><b>403</b><span>对象类型</span></div>
|
||||
<div class="stat"><b>1492</b><span>桌面命令(GUI 清单)</span></div>
|
||||
<div class="stat"><b>103</b><span>已验收案例</span></div>
|
||||
<div class="stat"><b>84</b><span>模块页面</span></div>
|
||||
</div>
|
||||
|
||||
<h3>4.1 工作台清单</h3>
|
||||
<p>注册表里只有模块 id,没有显示名与图标字段——显示名就是 id,图标来自各命令的元数据。按职能分组如下:</p>
|
||||
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>组</th><th>工作台(命令数 / Python API / 对象类型)</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td><strong>核心建模</strong></td><td>Part(10 / 1191 / 116)· PartDesign(50 / 238 / 65)· Sketcher(6 / 141 / 10)· Surface(7 / 10 / 7)· Mesh(6 / 211 / 31)· MeshPart(4 / 13 / 0)· Points(7 / 12 / 8)· ReverseEngineering(5 / 3 / 0)</td></tr>
|
||||
<tr><td><strong>数据与测量</strong></td><td>Spreadsheet(6 / 63 / 5)· Measure(7 / 31 / 11)· Material(5 / 178 / 22)</td></tr>
|
||||
<tr><td><strong>装配</strong></td><td>Assembly(7 / 552 / 8)</td></tr>
|
||||
<tr><td><strong>制图与 BIM</strong></td><td>Draft(4 / 2043 / 0)· BIM(32 / 2366 / 0)· TechDraw(8 / 247 / 41)</td></tr>
|
||||
<tr><td><strong>仿真</strong></td><td>Fem(5 / 1305 / 53)</td></tr>
|
||||
<tr><td><strong>加工</strong></td><td>CAM(77 / 2883 / 12)</td></tr>
|
||||
<tr><td><strong>检测</strong></td><td>Inspection(5 / 3 / 3)· Test(1 / 0 / 0)</td></tr>
|
||||
<tr><td><strong>机器人</strong></td><td>Robot(5 / 16 / 6)</td></tr>
|
||||
<tr><td><strong>基础设施</strong></td><td>Import(6 / 1135 / 2)· JtReader(4 / 0 / 1)· Web(4 / 0 / 0)· Cloud(7 / 3 / 0)· Show(6 / 104 / 0)· Plot(2 / 28 / 0)· Help(2 / 14 / 0)· Start(5 / 2 / 0)· TemplatePyMod(3 / 244 / 0)· Sandbox(5 / 30 / 2)· Tux(1 / 25 / 0)</td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<div class="note">桌面端的 GUI 清单有 <strong>29</strong> 个工作台:比 Web 少 <code>Plot</code>、<code>Show</code>、<code>Web</code>,多一个 <code>OpenSCAD</code>。OpenSCAD 在 Web 端整体不实现,也不会出现在任何注册表或页面上。</div>
|
||||
|
||||
<h3>4.2 如何切换</h3>
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>入口</th><th>位置</th><th>行为</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>工作台下拉框</td><td>顶部工具栏坞,<code><select aria-label="Workbench"></code></td><td>切换后写入该文档的 <code>LastModule</code>,每个文档独立记忆</td></tr>
|
||||
<tr><td>页签行</td><td>界面最顶部一行</td><td>点击工作台名直接切换(Assembly、BIM、CAM …)</td></tr>
|
||||
<tr><td>统一工作台中栏</td><td><code>workbench.html</code> 左侧「模块」列表</td><td>带筛选输入框;每项显示 <code>N objects · M Python APIs</code></td></tr>
|
||||
<tr><td>Start 页面</td><td>启动面板</td><td>经 <code>postMessage</code> 请求切换</td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<p>切换期间会显示模态对话框「Workbench switching」,完成后清空当前命令与选择。工作台切换<b>不会</b>重启 Worker——Worker 持有文档,重启会丢数据。</p>
|
||||
|
||||
<div class="warnbox"><strong>没有全局的工作台切换快捷键。</strong>现有全局按键只有 <kbd>Esc</kbd>(取消/关闭)与 BIM 微调组合键(<kbd>Alt</kbd>+方向键、<kbd>Alt</kbd>+<kbd>,</kbd>/<kbd>.</kbd>、<kbd>Alt</kbd>+<kbd>PageUp</kbd>/<kbd>PageDown</kbd>、<kbd>Alt</kbd>+<kbd>/</kbd>)。单条命令的加速键来自命令元数据,可在快捷键编辑器里改。</p>
|
||||
|
||||
<h3>4.3 工具栏如何生成</h3>
|
||||
<p>三层数据,各司其职:</p>
|
||||
<ol style="color:#cfdae2">
|
||||
<li><strong>模块注册表</strong>(<code>module-registry.generated.ts</code>)提供每个模块的 <em>Worker 命令词汇</em>:哪些命令由哪个 Worker 执行。</li>
|
||||
<li><strong>桌面 GUI 清单</strong>(<code>public/api/desktop-gui-manifest.json</code>)提供 <em>界面真相</em>:每个工作台的菜单、工具栏(名称 + 命令 id 列表)、停靠面板,以及扁平的命令元数据(菜单文字、提示、图标、加速键)。</li>
|
||||
<li><strong>命令矩阵</strong>(<code>public/api/workbench-command-matrix.json</code>,1492 条)把桌面命令映射到 Web 处置:<code>native_handler</code> 196 条、<code>restricted</code> 1296 条。</li>
|
||||
</ol>
|
||||
<p>渲染时遍历工作台的 <code>toolbars[]</code>,每条工具栏最多取 <strong>18</strong> 个命令变成按钮(30×30 图标)。没有 Worker 绑定的命令会被过滤掉,不会出现死按钮。</p>
|
||||
|
||||
<h3>4.4 命令选择器</h3>
|
||||
<p>命令按钮带 <code>data-help-page="<命令>"</code>(去掉 <code>Module:desktop:</code> 前缀)与 <code>data-command</code>(原始命令 id)。自动化脚本统一用这个选择器点击命令:</p>
|
||||
<pre><code>button[data-help-page="Assembly_CreateBom"]</code></pre>
|
||||
<div class="warnbox"><strong>工作台按钮没有 aria-label 也没有 data-*</strong>,只有 <code>button.module</code> 类名(选中项加 <code>.selected</code>)。要选工作台只能按类名加文本匹配。</div>
|
||||
|
||||
<!--{{WORKBENCH_CHAPTERS}}-->
|
||||
|
||||
<h2 id="s5" class="anchor">5 · 面板与对话框</h2>
|
||||
|
||||
<h3>5.1 常驻面板</h3>
|
||||
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>面板</th><th>内容</th><th>交互</th></tr></thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><strong>Objects 树</strong></td>
|
||||
<td>扁平对象列表(Part 图元、布尔结果、网格等),每行含可见性复选框、类型图标、错误/已修改/外部引用标记。三列对应 Qt 树控件的标签、描述与内部名。</td>
|
||||
<td>单选;选中即更新属性面板与视口高亮。测量任务进行中时,点击会被导向测量选择列表,而不是改变树的选中项。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Properties</strong></td>
|
||||
<td>按对象类型分组的属性行:<br>
|
||||
<em>View</em>:Label、Color(取色器)、Visibility<br>
|
||||
<em>Placement</em>:Position / Euler XYZ° / Axis(只读展示)<br>
|
||||
<em>Data</em>:随类型变化——<code>Part::Box</code> 为 Length/Width/Height;图元为各自字段(含 Angle1/Angle2);布尔为 Operation / Base / Tool(下拉选择对象)<br>
|
||||
<em>Geometry</em>:源文件、面数/三角面数、网格统计</td>
|
||||
<td>属性行按对象类型写死,没有通用的 <code>App::Property*</code> 反射;枚举用下拉、布尔用复选框、对象引用用 Link 下拉。属性名列宽可拖,宽度记在本地偏好里。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Tasks</strong></td>
|
||||
<td>当前任务的内联面板:标题「Edit <task>」、关闭/取消按钮,以及该任务自己的表单。</td>
|
||||
<td>不是模态窗口,直接显示在主工作区里。</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>底部坞</strong></td>
|
||||
<td>三个页签:<em>Selection view</em>(当前选择)、<em>Report view</em>(消息日志)、<em>Python console</em>(解释器)。</td>
|
||||
<td>可浮动、全屏、关闭;默认关闭。</td>
|
||||
</tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<h3>5.2 树与选择</h3>
|
||||
<ul style="color:#cfdae2">
|
||||
<li>树是<strong>扁平列表</strong>,没有 Body/特征/分组层级——层级只存在于装配树里。</li>
|
||||
<li>没有通用的对象右键菜单。唯一存在的是<strong>装配组件菜单</strong>:激活/停用、选择链接对象、选择该组件的关节、删除组件及依赖关节、刚性/柔性切换。</li>
|
||||
<li>测量任务会临时接管选择语义:点选进入测量列表,不改树高亮。</li>
|
||||
</ul>
|
||||
|
||||
<h3>5.3 任务对话框目录</h3>
|
||||
<p>任务面板以 <code><section></code>/<code><fieldset></code> 加 <code>aria-label</code> 的形式内联渲染,数量约 120 个(每个 <code>*-task.tsx</code> 一个)。主要几类:</p>
|
||||
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>对话框</th><th>触发</th><th>关键字段</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>CAM 任务 / CAM 作业偏好 / 路径显示偏好</td><td>CAM_Job 等</td><td>作业名、输出、刀具控制器、后处理器;Apply / Reset / Cancel</td></tr>
|
||||
<tr><td>CAM 区域 / CAM 仿真器</td><td>CAM_Area、CAM_Simulator</td><td>源对象、工作平面、公差;仿真回放控制</td></tr>
|
||||
<tr><td>草图绘制 / 草图约束 / 草图校验</td><td>进入草图编辑</td><td>几何工具选择、点合并、构造线开关、约束表(F2 重命名、Delete 删除)、元素列表框</td></tr>
|
||||
<tr><td>电子表格编辑器</td><td>选中 <code>Spreadsheet::Sheet</code></td><td>单元格网格;缩放、单元格属性、剪贴板、合并拆分、行列操作、文字样式、输出显示;绑定单元格、配置表、别名显示</td></tr>
|
||||
<tr><td>CSV 导入/导出</td><td>表格命令</td><td>文件名、分隔符、目标区域</td></tr>
|
||||
<tr><td>Show 剖切</td><td>Show_Clipping</td><td>逐对象剖切平面开关、草图剖切</td></tr>
|
||||
<tr><td>Part 导入 / 导出</td><td>Part_Import / Part_Export</td><td>导入:文件、保留颜色、目标文档;导出:文件名、格式、选择集</td></tr>
|
||||
<tr><td>视图任务</td><td>Std_ViewHome / FitSelection / DrawStyle 等</td><td>归属视图、绘制样式(原样/点/线框/隐藏线/无着色/着色/平面线框)、可见/可选开关、选择过滤器、框选模式与元素类型</td></tr>
|
||||
<tr><td>关于 / 命令行</td><td>Std_About 等</td><td>标题与正文、复制按钮;失败信息以 <code><pre role="alert"></code> 输出</td></tr>
|
||||
<tr><td>偏好设置</td><td>Edit ▸ Preferences</td><td>单位制、导航风格、主题、显示网格;存 localStorage</td></tr>
|
||||
<tr><td>命令面板</td><td>快捷键 / 菜单</td><td>按名称搜索 1492 条命令,可按当前工作台或全部过滤</td></tr>
|
||||
<tr><td>任务框架</td><td>外部工作台命令</td><td>全屏覆盖层,内嵌 <code>/workbench.html?module=…&command=…</code></td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<div class="note"><strong>对话框模式:</strong>大多数任务面板不是模态窗口,而是内联在舞台里;只有少量确认类(缩放级别、行高列宽、单元格属性、工作台切换警告、装配组件菜单)使用真正的模态 <code><dialog></code>。</div>
|
||||
|
||||
<h2 id="s6" class="anchor">6 · 视口交互</h2>
|
||||
|
||||
<p>视口由 <code>SceneViewport</code> 实现:three.js 的 <code>WebGLRenderer</code> + 45° 透视相机 + <code>OrbitControls</code>。它只负责<strong>绘制与拾取</strong>——几何、显示模式判定与放置仍由 WASM 内核持有。</p>
|
||||
|
||||
<h3>6.1 导航</h3>
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>操作</th><th>行为</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>中键拖动</td><td>平移</td></tr>
|
||||
<tr><td>滚轮</td><td>缩放</td></tr>
|
||||
<tr><td>中键 + 左键(或右键 + <kbd>Shift</kbd>)</td><td>旋转</td></tr>
|
||||
<tr><td>导航风格</td><td>支持 Blender / Revit / 触控板风格切换</td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<h3>6.2 视口工具条</h3>
|
||||
<p>视口上方固定一条工具条(<code>aria-label="3D display controls"</code>):</p>
|
||||
<div class="grid two">
|
||||
<div class="card" style="margin:0">
|
||||
<h4 style="margin-top:0">显示</h4>
|
||||
<ul style="margin:0;padding-left:18px;color:#cfdae2">
|
||||
<li>轴十字开关</li>
|
||||
<li>转台演示播放 + 速度滑杆</li>
|
||||
<li>重叠对象选择器(<em>选择重叠对象</em>)</li>
|
||||
<li>标准视图下拉:上/下/前/后/左/右/等轴测/二轴测/三轴测</li>
|
||||
<li>屏幕视图与命名视图的保存/调用</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="card" style="margin:0">
|
||||
<h4 style="margin-top:0">相机与样式</h4>
|
||||
<ul style="margin:0;padding-left:18px;color:#cfdae2">
|
||||
<li>放大 / 缩小 / 全显</li>
|
||||
<li>左转 / 右转</li>
|
||||
<li>导航风格、轨道风格(当前禁用)</li>
|
||||
<li>绘制样式:原样 / 点 / 线框 / 隐藏线 / 无着色 / 着色 / 平面线框</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="note"><strong>没有视图立方体(View Cube)。</strong>定向只能通过标准视图下拉与左右旋转按钮完成。</div>
|
||||
|
||||
<h3>6.3 选择与变换</h3>
|
||||
<ul style="color:#cfdae2">
|
||||
<li><strong>拾取</strong>:光线投射命中面、边、顶点与点,支持悬停反馈与重叠对象选择。</li>
|
||||
<li><strong>变换手柄</strong>:three.js <code>TransformControls</code>,模式为平移 / 旋转 / 关闭;工具条(<code>aria-label="Object transform"</code>)提供移动、旋转、锁定局部坐标与坐标读数。</li>
|
||||
<li><strong>回写</strong>:拖动手柄的结果会换算回内核的 <code>Placement</code>(位置数组 + 旋转),不是只改显示。</li>
|
||||
<li><strong>局部坐标系编辑器</strong>:独立对话框,输入位置与欧拉角。</li>
|
||||
</ul>
|
||||
|
||||
<h3>6.4 剖切</h3>
|
||||
<p>剖切由 <code>Show</code> 工作台提供,按文档维护一组 three.js 平面。FEM 视口与草图视图也会以局部裁剪模式打开剖切。</p>
|
||||
|
||||
<h3>6.5 精度与性能要点</h3>
|
||||
<div class="card">
|
||||
<p style="margin:0">网格化是交互延迟的最大来源,因此内核侧统一走「一次剖分、多处复用」:显示、面颜色、引用解析共享同一次剖分结果;边采样按边形状哈希缓存,挠度随包围盒对角线自适应。three.js 侧不做二次剖分,也不重新三角化——它拿到的就是内核交付的那份网格。</p>
|
||||
</div>
|
||||
|
||||
<h2 id="s7" class="anchor">7 · 文件与 OPFS</h2>
|
||||
<p class="lead">Web 版没有本地文件系统权限,所有文档与导出都落在浏览器 OPFS(Origin Private File System)里。下载到本地必须由用户显式操作。</p>
|
||||
|
||||
<h3>7.1 目录契约</h3>
|
||||
<p>存储根目录为 <code>freecad-1-2</code>,下面按用途分目录:</p>
|
||||
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>目录</th><th>内容</th><th>约束</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td class="num">freecad-documents/</td><td>文档(<code>.FCStd</code>)</td><td>只接受 <code>.FCStd</code>;写入失败会回滚</td></tr>
|
||||
<tr><td class="num">freecad-exports/</td><td>导出件(STEP / IGES / BREP / STL / GLB …)</td><td>文件名必须带扩展名;导出<b>不会</b>自动下载</td></tr>
|
||||
<tr><td class="num">freecad-plot-images/</td><td>绘图输出</td><td>只接受 <code>.svg</code></td></tr>
|
||||
<tr><td class="num">freecad-macros/</td><td>宏</td><td>只接受 <code>.FCMacro</code> / <code>.py</code></td></tr>
|
||||
<tr><td class="num">(原始 STEP 缓存)</td><td>STEP 导入的中间产物</td><td>可读/写/删/列</td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<h3>7.2 界面上的文件操作</h3>
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>操作</th><th>位置</th><th>行为</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>保存 FCStd 到 OPFS</td><td>Files 菜单</td><td>写 <code>freecad-documents/</code>,并广播文档持久化事件</td></tr>
|
||||
<tr><td>下载 native FCStd</td><td>Files 菜单</td><td><b>唯一</b>会触发浏览器下载的文档操作</td></tr>
|
||||
<tr><td>导出选中对象</td><td>Files 菜单</td><td>格式下拉(STL/STEP/IGES/BREP/glTF/glb),写入 OPFS</td></tr>
|
||||
<tr><td>OPFS 导出件</td><td>Files 菜单</td><td>下拉选择 + 从 OPFS 导入 + 刷新</td></tr>
|
||||
<tr><td>OPFS 文档</td><td>Files 菜单</td><td>下拉选择 + 打开 + 刷新</td></tr>
|
||||
<tr><td>Part 导出的下载</td><td>Part 导出任务</td><td>导出任务生成 Blob 并触发下载</td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<div class="warnbox"><strong>自动下载属于缺陷。</strong>除了上述显式入口,任何代码路径都不应调用浏览器下载。历史上把导出误做成自动下载,是明确的验收缺口。</div>
|
||||
|
||||
<h3>7.3 内核内的临时文件</h3>
|
||||
<p>WASM 内核有自己的虚拟文件系统(MEMFS)。导出流程是:内核先写 <code>/tmp/…</code>,再把字节读出来转入 OPFS。<strong>内核的 <code>/tmp</code> 与宿主机的 <code>/tmp</code> 无关</strong>,也不能作为跨步骤的数据来源——它只是暂存。</p>
|
||||
|
||||
<!-- ============================ 8 ============================ -->
|
||||
<h2 id="s8" class="anchor">8 · 键盘与可访问性</h2>
|
||||
<p>界面所有主要区域都有稳定的 <code>aria-label</code>,这既是无障碍支持,也是自动化测试选择元素的方式。</p>
|
||||
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>选择器</th><th>对应区域</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td class="num">aria-label="Model tree"</td><td>Objects 树</td></tr>
|
||||
<tr><td class="num">aria-label="Object Properties"</td><td>属性面板</td></tr>
|
||||
<tr><td class="num">aria-label="Tasks"</td><td>任务区</td></tr>
|
||||
<tr><td class="num">aria-label="Status bar"</td><td>状态栏</td></tr>
|
||||
<tr><td class="num">aria-label="Application menus"</td><td>菜单栏</td></tr>
|
||||
<tr><td class="num">aria-label="Imported native 3D view"</td><td>3D 视口</td></tr>
|
||||
<tr><td class="num">aria-label="Object transform"</td><td>视口上方的变换工具条</td></tr>
|
||||
<tr><td class="num">aria-label="Placement values"</td><td>Placement 数值组</td></tr>
|
||||
<tr><td class="num">aria-label="Resize tree panel / Resize properties panel / Resize property name column"</td><td>三条分隔条</td></tr>
|
||||
<tr><td class="num">role="tablist" aria-label="Documents"</td><td>底部文档页签</td></tr>
|
||||
<tr><td class="num">aria-label="Bottom dock" / Selection view / Report view / Python console</td><td>底部坞及其页签</td></tr>
|
||||
<tr><td class="num">role="dialog" aria-label="<Module> task: <Command>"</td><td>任务框架</td></tr>
|
||||
<tr><td class="num">aria-label="Top/Left/Right/Bottom toolbar dock"</td><td>四个工具栏坞</td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<h4>键盘</h4>
|
||||
<ul style="color:#cfdae2">
|
||||
<li>分隔条:<kbd>←</kbd>/<kbd>→</kbd> 步进 20 px,<kbd>Home</kbd>/<kbd>End</kbd> 到 180/420 px</li>
|
||||
<li>菜单栏使用原生 <code><details></code>,可用 <kbd>Tab</kbd> 聚焦、<kbd>Enter</kbd> 展开、<kbd>Esc</kbd> 收起</li>
|
||||
<li>文档页签左右各有滚动按钮,页签多时按需出现</li>
|
||||
<li>命令面板与快捷键编辑器在覆盖层中提供(见第 5 节)</li>
|
||||
</ul>
|
||||
|
||||
<div class="warnbox"><strong>无 toast 通知区。</strong>外壳里没有独立的通知/气泡组件:临时反馈走状态栏的 <code>role="status"</code>,进度走内联 <code><progress role="status"></code>。设计新功能时应沿用这条通道,不要另造一套提示。</div>
|
||||
|
||||
<!-- ============================ 9 ============================ -->
|
||||
<h2 id="s9" class="anchor">9 · 响应式</h2>
|
||||
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>断点</th><th>行为</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td class="num">≤1100 px</td><td>三栏收窄为 <code>210px 5px 270px 5px 1fr</code>,属性分隔条重新启用</td></tr>
|
||||
<tr><td class="num">≤900 px</td><td>草图任务面板取消高度上限</td></tr>
|
||||
<tr><td class="num">≤800 px</td><td>布局改为纵向 flex;分隔条隐藏;各 <code>aside</code> 最高 45vh;视口高 340 px</td></tr>
|
||||
<tr><td class="num">≤650 px</td><td>单列;下拉菜单改为 <code>position:fixed</code> 左右各留 12 px;页签条滚动;提示文字 10 px</td></tr>
|
||||
<tr><td class="num">子应用 ≤920 / ≤720 px</td><td>三列 → 两列 → 单列,舞台最小高 55vh</td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<p>移动端不做抽屉或汉堡菜单,面板直接纵向堆叠;页面最小宽度 320 px。</p>
|
||||
|
||||
<!-- ============================ 10 ============================ -->
|
||||
<h2 id="s10" class="anchor">10 · 与桌面 FreeCAD 的差异</h2>
|
||||
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>方面</th><th>桌面 FreeCAD</th><th>Web 版</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>菜单</td><td>原生 Qt 菜单栏</td><td>HTML 菜单栏;末项随工作台变化</td></tr>
|
||||
<tr><td>文档页签</td><td>MDI 子窗口 / 顶部页签</td><td>主工作区底部页签条</td></tr>
|
||||
<tr><td>停靠面板</td><td>Qt DockWidget 可任意停靠</td><td>固定三栏 + 顶部/左/右/底四个工具栏坞</td></tr>
|
||||
<tr><td>文件</td><td>本地文件系统</td><td>OPFS 为默认存储;下载到本地必须显式触发</td></tr>
|
||||
<tr><td>Python</td><td>内嵌控制台,可访问完整本地环境</td><td>Python 控制台(底部坞),运行在 WASM 解释器内</td></tr>
|
||||
<tr><td>OpenSCAD</td><td>有工作台</td><td>整体不实现,不在注册表中出现</td></tr>
|
||||
<tr><td>GUI 相关 API</td><td>FreeCADGui 完整</td><td>由 React 视图/属性面板承接,<code>FreeCADGui</code> 桩在无 GUI 时返回 <code>None</code></td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<!-- ============================ 11 ============================ -->
|
||||
<!--{{IMPLEMENTATION_MAPPING}}-->
|
||||
|
||||
<!--{{GAP_REGISTER}}-->
|
||||
|
||||
<h2 id="s11" class="anchor">11 · 附录:结构速查</h2>
|
||||
|
||||
<h4>渲染树(简化)</h4>
|
||||
<pre><code><div class="desktop-workspace">
|
||||
<header class="top"> ② 品牌栏
|
||||
<dialog> Start 启动面板(覆盖层)
|
||||
<nav role="menubar"> ③ 菜单栏
|
||||
<PersistentToolbarWorkspace> ④ 工具栏区(自身 grid)
|
||||
├─ 可见性 / 排列 ④a
|
||||
├─ Top dock ④b
|
||||
├─ Left dock · content · Right dock
|
||||
└─ Bottom dock
|
||||
<div class="layout"> 内层 grid
|
||||
├─ <aside aria-label="Model tree"> ⑤
|
||||
├─ separator
|
||||
├─ <aside aria-label="Object Properties"> ⑥
|
||||
├─ separator
|
||||
└─ <main class="stage"> ⑦
|
||||
├─ h2 文档标题
|
||||
├─ .viewport (aria-label="Imported native 3D view")
|
||||
├─ role=toolbar aria-label="Object transform"
|
||||
├─ 任务面板 / 外部工作台 iframe / 诊断
|
||||
└─ role=tablist aria-label="Documents"(底部)
|
||||
<footer class="desktop-status-bar"> ⑧
|
||||
<BottomDock> ⑨
|
||||
<TaskFrame> ⑩
|
||||
</div></code></pre>
|
||||
|
||||
<h4>布局状态</h4>
|
||||
<div class="table-scroll"><table>
|
||||
<thead><tr><th>状态</th><th>默认值</th><th>作用</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td class="num">treeWidth</td><td>240</td><td>树列宽(180–420)</td></tr>
|
||||
<tr><td class="num">propertyWidth</td><td>300</td><td>属性列宽(180–420)</td></tr>
|
||||
<tr><td class="num">startVisible</td><td>按 <code>?start</code> 参数</td><td>Start 覆盖层</td></tr>
|
||||
<tr><td class="num">bottomDockOpen</td><td>false</td><td>底部坞</td></tr>
|
||||
<tr><td class="num">workbenches</td><td>按文档记录</td><td>每个文档独立记住当前工作台</td></tr>
|
||||
<tr><td class="num">developerMode</td><td>false</td><td>开发者诊断区</td></tr>
|
||||
</tbody></table></div>
|
||||
|
||||
<!--{{PANEL_CATALOG}}-->
|
||||
|
||||
<!--{{MODAL_DIALOG_CATALOG}}-->
|
||||
|
||||
<!--{{PREFERENCES_CATALOG}}-->
|
||||
|
||||
<!--{{COMMAND_APPENDIX}}-->
|
||||
|
||||
</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
77
docs/current/web-freecad-manual-gaps.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# Web FreeCAD 手册与界面文档 · 缺口与边界账本
|
||||
|
||||
> 本文件由 `web/tools/manual/generate-gaps-doc.mjs` 从真实产物派生,**不要手改**。
|
||||
> 输入:`web/manual/data/final-status.json`、`web/manual/data/gap-ledger.json`、`docs/current/ui-design/data/gap-register.json`。
|
||||
> 复核:`node web/tools/manual/generate-gaps-doc.mjs --check`。
|
||||
|
||||
## 口径
|
||||
|
||||
- 模块数 **31**(不含已整体摘除的 OpenSCAD)。
|
||||
- 命令矩阵 **1573** 条,原生承接 **378** 条。
|
||||
- 手工验证命令 **12** 条;已知边界 **11** 条。
|
||||
- 手册 **17** 章(正文 15 章 + 附录章)、页面截图引用 **130** 处、磁盘 PNG **128** 个。
|
||||
- UI 表面 **333** 项:。
|
||||
- 表面状态:implemented 330 / partial 3 / gap **0**。
|
||||
|
||||
## 已实现的界面覆盖(不是缺口)
|
||||
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 界面设计文档 | `docs/current/web-freecad-ui-layout-and-functions.html`,17 章 + 命令附录 |
|
||||
| 手册 | `web/teaching/manual.html`,15 章 164 节 |
|
||||
| 截图 | 页面引用 130 处;磁盘 128 个 PNG;采集报告 26 份 |
|
||||
| 浏览器校验 | 桌面 overflow 0 / 移动 overflow 0 / 破图 0 |
|
||||
|
||||
## 已知边界(11 条)
|
||||
|
||||
| ID | 模块 | 边界 | 状态 |
|
||||
|---|---|---|---|
|
||||
| `b-techdraw-worker` | TechDraw | 页面 Worker 未持有目标文档,TechDraw_PageDefault 报 Document does not exist;SVG 回退不是 TechDraw 输出。 | boundary |
|
||||
| `b-fem-native` | Fem | FemMeshObject/FemResultObject 未随包发布,结果停留在 Worker;VTK 显示为 three.js 近似。 | boundary |
|
||||
| `b-cam-opencamlib` | CAM | Adaptive/Surface/Waterline 依赖 OpenCAMLib 与完整 ToolBit/G-code 栈,WASM 包未提供。 | boundary |
|
||||
| `b-gltf-native` | Import | OCCT WASM 构建 USE_RAPIDJSON=OFF,RWGltf 无法读写;当前仅 three.js 查看。 | boundary |
|
||||
| `b-cloud-remote` | Cloud | Save/Restore 需要远程 S3 凭据与服务;本地 OPFS 不受影响。 | boundary |
|
||||
| `b-material-sparse` | Material | Material 原生 API 对稀疏数组/单位处理不完整,部分命令为边界。 | boundary |
|
||||
| `b-bim-no-creation` | BIM | BIM 命令停靠区只有 BIM_Nudge_Up / BIM_Unclone / BIM_Ungroup;Arch_Site / Arch_Wall / BIM_Slab 等创建命令一律无任务面板。实测可用的只有 BIM_Views、BIM_Library、BIM_Setup、BIM_Material 四个非创建类命令。 | boundary |
|
||||
| `b-mesh-frompartshape` | Mesh | 实体转网格的标准入口 Mesh_FromPartShape 在 Web 端没有任务面板。可用替代是 Mesh_BuildRegularSolid,实测返回 nativeOperationCompleted=true、typeId=Mesh::Cube。 | boundary |
|
||||
| `b-draft-needs-viewport` | Draft | Draft_Rectangle 面板填满数值后仍提示 Pick first corner,图元要求先在三维视口取点;工作台壳层页面没有 canvas,取不了点。Draft_Line / Draft_Wire / Draft_Array 连面板都没有。 | boundary |
|
||||
| `b-robot-no-model` | Robot | Robot_CreateRobot 面板六个分组齐全,但 Joint angles 分组固定显示 Home: Not set — use Set Home;点 Set Home 与点动按钮后文本与数值均不变。 | boundary |
|
||||
| `b-plot-no-canvas` | Plot | Plot_Axes 面板五个分组齐全,但点 New figure 与 Add axes 后页面既不新增 svg 也不新增 canvas,在 Download SVG 之前没有可视化反馈。 | boundary |
|
||||
|
||||
## 手工验证的用例
|
||||
|
||||
共 **12** 条(台账 `web/manual/data/gap-ledger.json`)。
|
||||
- 草图编辑器已从右侧属性栏移到主舞台(project-shell 的 .stage-sketch-task),命令按宽度自动排成多列,1440 宽窗口下为 3 列;ch03 截图已按新布局重采。
|
||||
- 项目页 Part 文档切换 PartDesign 需要 ownership handoff;教程改用 partdesign.html。
|
||||
- Mesh/BIM/TechDraw/FEM 模块页显示 boundary/no-worker,教程按模块页实际任务与边界编写。
|
||||
- 两套页面壳不可互换:project.html 能新建 Document 且工作台下拉给 30 个工作台;workbench.html?module=X 对多数模块绑定固定文档 id workbench-document,既不能新建也不能打开文档。
|
||||
- 字段面板能填写并提交但缺父对象文档的失败属前置未满足,不记为产品回归。
|
||||
|
||||
## 界面表面审计(333 项,问题 0 项)
|
||||
|
||||
| 表面 | 分类 | 状态 | 注释 |
|
||||
|---|---|---|---|
|
||||
| — | menu | partial | — |
|
||||
| — | menu | partial | — |
|
||||
| — | toolbar | partial | — |
|
||||
|
||||
审计命令:`node web/tools/manual/audit-ui-gaps.mjs --check`。
|
||||
|
||||
## 复现命令
|
||||
|
||||
```bash
|
||||
R="/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD"
|
||||
node "$R/tools/fcweb/ui-surface-inventory.mjs" --check
|
||||
node "$R/tools/fcweb/build-ui-doc.mjs" --check
|
||||
node "$R/web/tools/manual/audit-ui-gaps.mjs" --check
|
||||
node "$R/web/tools/manual/generate-gaps-doc.mjs" --check
|
||||
cd "$R/web" && npm run build:manual && npm run check:manual
|
||||
```
|
||||
|
||||
## 边界判定口径
|
||||
|
||||
- 前置未满足(缺文档、缺 Worker、缺原生对象)记边界并保留产品原始错误文本,不写成产品回归。
|
||||
- GUI 控件缺口用 React 组件补齐,不以 GUI-only 名义留作 blocked。
|
||||
- 空白或占位截图不得入库;空白工具栏裁剪由 `build-ui-doc.mjs` 的 1024 字节门槛自动跳过。
|
||||
- 生成物(本文件、第 16 章、`final-status.json`)一律由脚本产出并带 `--check`。
|
||||
|
||||
BIN
docs/current/web-freecad-ui-assets/ui-desktop-1600.png
Normal file
|
After Width: | Height: | Size: 126 KiB |
BIN
docs/current/web-freecad-ui-assets/ui-mobile-390.png
Normal file
|
After Width: | Height: | Size: 78 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Architecture.png
Normal file
|
After Width: | Height: | Size: 156 KiB |
|
After Width: | Height: | Size: 18 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Assembly.png
Normal file
|
After Width: | Height: | Size: 176 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/BIM-toolbars.png
Normal file
|
After Width: | Height: | Size: 49 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/BIM.png
Normal file
|
After Width: | Height: | Size: 190 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/CAM-toolbars.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/CAM.png
Normal file
|
After Width: | Height: | Size: 170 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Cloud.png
Normal file
|
After Width: | Height: | Size: 156 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Draft.png
Normal file
|
After Width: | Height: | Size: 157 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Fem-toolbars.png
Normal file
|
After Width: | Height: | Size: 115 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Fem.png
Normal file
|
After Width: | Height: | Size: 235 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Help.png
Normal file
|
After Width: | Height: | Size: 156 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Import.png
Normal file
|
After Width: | Height: | Size: 157 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Inspection.png
Normal file
|
After Width: | Height: | Size: 158 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/JtReader.png
Normal file
|
After Width: | Height: | Size: 157 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Material.png
Normal file
|
After Width: | Height: | Size: 158 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Measure.png
Normal file
|
After Width: | Height: | Size: 157 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Mesh-toolbars.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Mesh.png
Normal file
|
After Width: | Height: | Size: 210 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/MeshPart.png
Normal file
|
After Width: | Height: | Size: 160 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Part.png
Normal file
|
After Width: | Height: | Size: 126 KiB |
|
After Width: | Height: | Size: 13 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/PartDesign.png
Normal file
|
After Width: | Height: | Size: 131 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Points.png
Normal file
|
After Width: | Height: | Size: 161 KiB |
|
After Width: | Height: | Size: 4.7 KiB |
|
After Width: | Height: | Size: 164 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Robot.png
Normal file
|
After Width: | Height: | Size: 159 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Sandbox.png
Normal file
|
After Width: | Height: | Size: 158 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Sketcher.png
Normal file
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 12 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Spreadsheet.png
Normal file
|
After Width: | Height: | Size: 121 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Start.png
Normal file
|
After Width: | Height: | Size: 156 KiB |
|
After Width: | Height: | Size: 6.9 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Surface.png
Normal file
|
After Width: | Height: | Size: 182 KiB |
|
After Width: | Height: | Size: 90 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/TechDraw.png
Normal file
|
After Width: | Height: | Size: 230 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Test-toolbars.png
Normal file
|
After Width: | Height: | Size: 4.1 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Test.png
Normal file
|
After Width: | Height: | Size: 152 KiB |
BIN
docs/current/web-freecad-ui-assets/workbenches/Tux.png
Normal file
|
After Width: | Height: | Size: 156 KiB |
5243
docs/current/web-freecad-ui-layout-and-functions.html
Normal file
125
tools/fcweb/README.md
Normal 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
@@ -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;
|
||||
}
|
||||
480
tools/fcweb/build-ui-doc.mjs
Normal 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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
}
|
||||
|
||||
const MENU_TEXT = text => String(text ?? "").replace(/&(?![a-z]+;|#\d+;)/g, "&");
|
||||
|
||||
// ------------------------------------------------------------------ seed --
|
||||
if (args.includes("--seed")) {
|
||||
if (fs.existsSync(sourcePath)) fail(`--seed refused: ${sourcePath} already exists`, 1);
|
||||
if (!fs.existsSync(outPath)) fail(`--seed: previous document not found at ${outPath}`, 1);
|
||||
let html = fs.readFileSync(outPath, "utf8");
|
||||
// Keep the shell prose; insert the two generated markers.
|
||||
const anchor = '<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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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);
|
||||
336
tools/fcweb/ui-inventory.mjs
Normal 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));
|
||||
62
tools/fcweb/ui-surface-inventory.mjs
Normal 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,
|
||||
}));
|
||||
562
tools/fcweb/ui-surface-scan.mjs
Normal 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 };
|
||||
@@ -1,6 +1,6 @@
|
||||
# Web FreeCAD 全功能初学者教案 · 接续点
|
||||
|
||||
更新:2026-11-15
|
||||
更新:2026-11-22
|
||||
计划:`/home/mes123456/.claude/plans/sleepy-whistling-journal.md`(完全重写)
|
||||
|
||||
## 目标
|
||||
@@ -8,6 +8,30 @@
|
||||
单页中文 HTML 教案,两层结构:入门主线(第 0–7 章)+ 全模块速查(第 8–13 章 + 附录)。
|
||||
图文并茂,内容完全对标语实测的软件功能;缺口按实测记账,不虚报。
|
||||
|
||||
## 本轮增量(2026-11-22)
|
||||
|
||||
- 新增权威 UI 表面清单:`tools/fcweb/ui-surface-inventory.mjs` → `tools/fcweb/out/ui-surface-inventory.json`(333 项 / 9 类,implemented 330、partial 3、gap 0)。
|
||||
- 新增第 16 章「全功能面板索引与实现映射」:由 `web/tools/manual/generate-panel-index.mjs` 从清单生成,含 8 张真实截图(`scenarios/ch16-shell-surfaces.json`)。
|
||||
- 核心与专业章新增「面板与任务面板」小节:ch02、ch03、ch04、ch05、ch08、ch09、ch10、ch11、ch12。
|
||||
- 修复手册分页器一次性塞入全部章节链接造成的桌面 583px 横向溢出(改为每章两链接,`build-manual.mjs` + `template.html`)。
|
||||
- 修复壳层 Tools/Windows/Help 菜单项点击冒泡导致菜单重新打开(`web/src/shell/utility-menus.tsx`,已 `vite build`)。
|
||||
- 新增缺口审计:`web/tools/manual/audit-ui-gaps.mjs` → `docs/current/ui-design/data/gap-register.json`(333 项,0 问题)。
|
||||
- 新增 `web/tools/manual/generate-final-status.mjs`,`final-status.json` 改由真实产物派生。
|
||||
- 第二批截图(2026-11-22):新增 `scenarios/ch04-partdesign-panels.json`,在 Pad 之后采集边缘特征(Fillet / Chamfer 两种形态)、Thickness、Body 布尔四个面板(4 张,最 6.5 KB)。ch04 新增「边缘特征面板」「Thickness 抽壳」「Body 布尔」三小节,正文引用全部 4 张。
|
||||
- 验证:`build-ui-doc.mjs --check` 通过;`check-ui-design-doc.mjs` 双视口 ok;`check:manual` ok(17 章、164 节、76 处图片引用 / 75 个 PNG、双视口 overflow 0)。
|
||||
- 注:`manual-assets/ch10/cam-job/01-cam-job.png` 在正文被引用两次,所以页面图片数比磁盘 PNG 多 1。
|
||||
- 界面设计文档:`build-ui-doc.mjs` 在「工具栏」表后插入该工作台的 `<id>-toolbars.png`(16 个工作台命中),文档图片 30 → 46,体积 1 113 323 字节,`--check` 通过;`check-ui-design-doc.mjs` 双视口 ok、overflow 0。
|
||||
- 空白工具栏裁剪已解决:Cloud/Help/Import/Inspection/JtReader/Measure/Sandbox/Sketcher/Start/Tux/Draft 的 `-toolbars.png` 实测都是 195 字节空白条(Web 壳层在这些工作台没有工具栏渲染)。`build-ui-doc.mjs` 增加 1024 字节门槛:小于该值的裁剪不复制、不插入,并清理上一轮遗留的空白文件;本轮输出 `blankToolbarCrops: 11`,文档图片 46 → 45,资源目录 54 → 43 个文件,`--check` 通过。
|
||||
- ch04 追加 Body Tip 与 Gear/Sprocket 两张截图(`08-body-tip`、`09-gear-panel`)。Gear 面板在 `details.design-task-group` 里默认折叠,必须先点 summary 展开;此前判定「面板未渲染」是选择器只匹配 fieldset 而面板在折叠 details 内,属场景缺陷不是产品缺陷。
|
||||
- 第三批截图(2026-11-22):新增 10 个场景,采 46 张面板图并全部写入正文——ch02 `part-task-panels`(5)、ch03 `sketcher-constraints-panels`(4)、ch04 `partdesign-dressup-panels`(6)、ch05 `assembly-task-panels`(5)、ch06 `measure-inspection-panels`(6)、ch07 `import-export-panels`(4)、ch09 `bim-task-panels`(5)、ch10 `cam-task-panels`(5)、ch11 `techdraw-task-panels`(5)、ch12 `fem-task-panels`(6)、ch13 `specialist-task-panels`(5)。
|
||||
- 手册页面图片引用 76 → 129,`check:manual` 双视口 overflow 0、0 破图、0 pageError;`final-status.json` 记 135 个 PNG(含 ch06 目录里 5 张早期失败运行留下的同名旧图,报告未引用,删除被权限策略拒绝,保留)。
|
||||
- 本轮实测记账的新边界:`Assembly_Tolerance` 只有触发按钮无表单;`Assembly_ActivateAssembly` 复用爆炸视图面板;`CAM_ToolController` / `CAM_Inspect` 无任务面板;`Inspection_InspectElement` 无面板(boundary · no worker);Measure 距离预览报 `native_protocol_error: Invalid native builder display geometry`,面积测量正常(10.00 cm²)。
|
||||
- 全链路复核:`ui-surface-inventory --check`(333 项 / gaps 0)、`audit-ui-gaps --check`、`build-ui-doc --check`(1 113 555 字节)、`check-ui-design-doc`(双视口 ok)、`check:manual`(129 图)全部通过。
|
||||
- 第三批采集报告回填后的正文修正(按报告实测文本,不按推断):TechDraw 页面面板实为 Drawing page stacking(Fill Template Fields / Redraw / Export SVG·PDF·DXF / Print All / Keep Updated / Hatches);`TechDraw_View` 提交报 `invalid request: Select source objects in the current document`(capabilityId `TechDraw.desktop:TechDraw_View`);`TechDraw_ProjectionGroup` 的 Use current selection 禁用且状态栏 `restricted: command is not runnable`;`FEM_SolverRun` 报 `invalid_request: Select exactly one FEM solver`;`MeshNetgenFromShape` 无文档时参数为空;`Surface_Filling` 报 `Error: Part document envelope is invalid`;Spreadsheet `A1` 输入 `=2+2` 后结果 4;Draft 工具栏实图在 project.html(Creation / Modification / Utility / Snap 四行)已补入 ch13(`02-draft-toolbars`)。
|
||||
- 新增实测缺口记录:`BIM_Wall` 无任务面板;`TechDraw_Dimension` / `TechDraw_Annotation` 不渲染面板,`TechDraw_Balloon` 只有禁用 Load selection;`FEM_MeshGmshFromShape` 无面板;`Import` 模块 0 task panels;`Draft` 模块页无任务面板(须在 project 页看工具栏)。
|
||||
- 清理:`web/manual/assets/ch06/measure-inspection-panels/` 删除 8 张早期失败运行的同名旧图,仅保留报告引用的 6 张;`final-status.json` PNG 计数 135 → 128,页面图片引用 130 处。
|
||||
- 复跑结果:`build:manual` 1 128 823 字节,`check:manual` 双视口 ok(130 图、overflow 0、破图 0),`generate-final-status` state complete。
|
||||
|
||||
## 本轮重写范围(2026-11-15)
|
||||
|
||||
### 截图:33 张 → 63 张
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Web FreeCAD 全功能初学者图文教案
|
||||
|
||||
单页中文 HTML 教案:32 个模块、1492 条命令索引、核心模块分步截图、专业模块工作流与边界说明。
|
||||
单页中文 HTML 教案:31 个模块、1573 条命令索引、17 章(含全功能面板索引)、129 处真实运行截图引用(页面计数)、专业模块工作流与边界说明。
|
||||
|
||||
## 目录
|
||||
|
||||
|
||||
BIN
web/manual/assets/ch02/part-task-panels/01-shape-builder.png
Normal file
|
After Width: | Height: | Size: 26 KiB |
BIN
web/manual/assets/ch02/part-task-panels/02-fillet.png
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
web/manual/assets/ch02/part-task-panels/03-chamfer.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
web/manual/assets/ch02/part-task-panels/04-boolean.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
web/manual/assets/ch02/part-task-panels/05-check-geometry.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 6.1 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 19 KiB |
BIN
web/manual/assets/ch04/partdesign-dressup-panels/08-body-tip.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 31 KiB |
BIN
web/manual/assets/ch05/assembly-task-panels/04-joints.png
Normal file
|
After Width: | Height: | Size: 28 KiB |
BIN
web/manual/assets/ch05/assembly-task-panels/05-new-part.png
Normal file
|
After Width: | Height: | Size: 32 KiB |
BIN
web/manual/assets/ch05/assembly-task-panels/06-simulation.png
Normal file
|
After Width: | Height: | Size: 73 KiB |
BIN
web/manual/assets/ch05/assembly-task-panels/07-exploded.png
Normal file
|
After Width: | Height: | Size: 86 KiB |
BIN
web/manual/assets/ch05/assembly-task-panels/08-bom.png
Normal file
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 395 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 13 KiB |
BIN
web/manual/assets/ch07/import-export-panels/01-file-tools.png
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
web/manual/assets/ch07/import-export-panels/02-opfs-browser.png
Normal file
|
After Width: | Height: | Size: 104 KiB |
|
After Width: | Height: | Size: 71 KiB |
BIN
web/manual/assets/ch07/import-export-panels/04-import-result.png
Normal file
|
After Width: | Height: | Size: 78 KiB |
BIN
web/manual/assets/ch09/bim-task-panels/01-bim-views.png
Normal file
|
After Width: | Height: | Size: 148 KiB |
BIN
web/manual/assets/ch09/bim-task-panels/02-bim-library.png
Normal file
|
After Width: | Height: | Size: 14 KiB |