feat(web): panel scroll contract, layout probe and functional suite
- lock the three-column height chain on workbench/PartDesign pages so each side panel scrolls independently and the centre stage keeps its size - dock module task panels above the layout with their own scrollbar instead of letting them push the stage out of the viewport - add tools/layout-probe.mjs (page scroll, aside bounds, pane scrolling, stage stability) and CLI mode for tools/static-host.mjs with relative --root support - add the P0-P4 browser functional suite, manual scenarios and capture tooling; document it under docs/current/web-functional-suite Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
94
docs/current/web-functional-suite/README.md
Normal file
94
docs/current/web-functional-suite/README.md
Normal file
@@ -0,0 +1,94 @@
|
||||
# Web FreeCAD 有头功能测试套件
|
||||
|
||||
统一入口:`tools/web-freecad-functional-suite.mjs`。默认**有头**运行(`DISPLAY=:1` 上可见窗口),全自动无人值守;用例层按优先级分层,复用现有手册场景、工作台命令面与 OPFS 契约。
|
||||
|
||||
## 运行
|
||||
|
||||
```bash
|
||||
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD"
|
||||
DISPLAY=:1 node tools/web-freecad-functional-suite.mjs --priority P0 # 壳层冒烟
|
||||
DISPLAY=:1 node tools/web-freecad-functional-suite.mjs --priority P1 # 手册章节全流程
|
||||
DISPLAY=:1 node tools/web-freecad-functional-suite.mjs --priority P2 # 全模块冒烟(31 例)
|
||||
DISPLAY=:1 node tools/web-freecad-functional-suite.mjs --priority P3 # 交叉用例(导出/OPFS/回开/错误恢复)
|
||||
DISPLAY=:1 node tools/web-freecad-functional-suite.mjs --only MOD-Fem-01 --force
|
||||
DISPLAY=:1 node tools/web-freecad-functional-suite.mjs --legacy-ids all # 附带旧 53 例手册套件
|
||||
```
|
||||
|
||||
常用参数(完整列表见 `tools/functional-suite/cli.mjs`):
|
||||
|
||||
| 参数 | 作用 |
|
||||
|---|---|
|
||||
| `--only <ids>` | 逗号分隔的用例 id |
|
||||
| `--priority P0,P1,P2,P3` | 按层选择 |
|
||||
| `--module <names>` | 只跑指定模块的 `MOD-*` |
|
||||
| `--resume <dir>` / `--force` | 断点续跑;`--force` 重跑已完成用例 |
|
||||
| `--headless` / `--slow <ms>` / `--highlight` | 无头、放慢、高亮(观察用) |
|
||||
| `--screenshots fails\|all` | 失败截图(默认)或全量截图 |
|
||||
| `--out <dir>` | 证据根目录(默认 `docs/current/web-functional-suite`) |
|
||||
| `--prune <n>` | 只保留最近 n 次运行目录 |
|
||||
| `--legacy-ids <ids\|all>` | 以子进程运行 `tools/run_user_manual_tests.mjs` 并归一化为 `LEGACY-*` |
|
||||
| `--timeout-scale <x>` | 统一放大/缩小用例超时 |
|
||||
|
||||
退出码:0 = 全部 passed;1 = 存在 failed/running;2 = 没有选中任何用例。
|
||||
|
||||
## 用例分层
|
||||
|
||||
| 前缀 | 层 | 内容 | 来源 |
|
||||
|---|---|---|---|
|
||||
| `SHELL-0x` | P0 | 入口隔离(COOP/COEP)、Start 工作区、新建文档 + Cube、OPFS 可写、画布与图标渲染 | `cases/shell.mjs` |
|
||||
| `CH-<chapter>-<workflow>` | P1 | 手册 27 份场景 JSON 全动作执行 + 章末后置断言(pageerror、状态栏、画布) | `cases/chapters.mjs` → `web/manual/scenarios/*.json` |
|
||||
| `CH-ch14-*`、`CH-ch15-*` | P1 | 无场景 JSON 的两章用手写用例(生产线资产契约、Help/命令面板/偏好/快捷键) | `cases/handwritten.mjs` |
|
||||
| `MOD-<Module>-01` | P2 | 31 个模块:壳层挂载、模块坞选中、命令面注册、规范命令返回 `kind=result` | `cases/modules.mjs` → `feature-capability-registry.json` |
|
||||
| `X-*` | P3 | 五种导出格式落 OPFS、FCStd 存取哈希、保存后回开、坏文件错误恢复、viewport 无溢出、左右面板独立滚动(`X-panel-scroll`) | `cases/crosscut.mjs` |
|
||||
| `LEGACY-<id>` | P4 | 旧手册套件 53 例(仅 `--legacy-ids` 时运行) | `executors/legacy.mjs` |
|
||||
|
||||
场景动作解释器与 `web/tools/manual/capture.mjs` 共用同一份实现:`web/tools/manual/lib/actions.mjs`(18 种动作)。
|
||||
|
||||
## 前置顺序与失败分类
|
||||
|
||||
每个用例先准备前置(host/端口、fixture、文档与对象、命令状态、viewport),再执行产品断言。失败分类:
|
||||
|
||||
- **blocked / precondition**:入口、fixture、viewport、host/iframe、命令状态不满足——先补缺项,不记产品回归。
|
||||
- **failed / product-regression**:前置全部满足后的产品行为失败,写入 `gaps.ndjson` 与报告。
|
||||
- 前置类由 `blockedPrecondition(class, message)`(`gap-ledger.mjs`)显式抛出;其余按 `classifyFailure` 归类。
|
||||
|
||||
## 输出(每次运行一个目录)
|
||||
|
||||
`docs/current/web-functional-suite/run-<stamp>/`:
|
||||
|
||||
- `manifest.json`:origin、Chrome 版本、用例清单、dist 相对路径
|
||||
- `results.json` / `checkpoint.json`:逐案结果与断点(`--resume` 依据)
|
||||
- `report.md` / `junit.xml` / `index.html`:人读报告、CI 报告、浏览器索引
|
||||
- `gaps.ndjson`:缺口台账(caseId、classification、failureClass、evidence)
|
||||
- `cases/<id>/result.json`、`step-*.json`、`shots/*.png`、失败时 `failure.png` + `failure-canvas.png`
|
||||
|
||||
用例间用 `resetState` 隔离:回 `about:blank`、递归清空 OPFS、再进入口页;页面/控制台错误按用例清零,作为该用例的断言。
|
||||
|
||||
## 浏览器
|
||||
|
||||
Playwright + 系统 Chrome(`FREECAD_CHROME` 可覆盖,默认 `/usr/bin/google-chrome`)。固定 flags:`--no-sandbox --disable-dev-shm-usage --use-angle=swiftshader --enable-unsafe-swiftshader`,viewport 1440×1000;`--gpu` 仅供人工观察性能。静态服务用 `tools/static-host.mjs` 的临时端口(带 COOP/COEP),不占用 5180/5183 等固定端口。
|
||||
|
||||
## 配套工具(面板滚动排查沉淀)
|
||||
|
||||
- `tools/static-host.mjs`:既是共享模块,也可直接当 CLI 用——`node tools/static-host.mjs [--root <dist>] [--port <n>] [--document <file>]`,打印 `ORIGIN=` 后常驻,供 `web/tools/manual/capture.mjs --origin` 或临时探针复用。`--root` 支持相对路径(内部统一 `path.resolve`;此前传相对根会因路径守卫让所有请求 403)。
|
||||
- `tools/layout-probe.mjs`:三栏布局/滚动探针,替代逐个手写的临时脚本。默认对 `/project.html`、`/partdesign.html`、`workbench.html?module=Part|Robot|Mesh` 逐页断言:锁定页整页不可滚动、aside 全部在视口内、每个 aside 拥有可滚动 `.pane-scroll`(默认注入 2000px 占位块)、注入与滚动面板后中央舞台位移 ≤1px。全量报告用 `--json`,人工核对用 `--headed --pause` 拖动面板观察;`--url` 可重复指定页面,`--origin` 可复用已有 host。
|
||||
|
||||
## 已修复的缺口(套件落地过程中)
|
||||
|
||||
- 静态 host 的 `.svg` MIME 为 `application/octet-stream` 导致工具栏大面积无图标 → 补全 MIME 表,并在 SHELL-02 增加图标渲染断言。
|
||||
- `templatepymod.inspectSourceInventory` 路由到 python worker 导致 `invalid_request` → 生成器映射改到 `templatepymod.worker.ts` 并重生成。
|
||||
- Fem 探针 `fem.action` 报 `memory access out of bounds`:11 月 15 日旧产物与当前构建图不匹配(全局 `-pthread/-matomics` vs 预编译 vtk 无原子特性)→ 以 `-Wl,--no-check-features` 重新链接 `FreeCADWebFemGenericFamilyProbe`,逐步骤日志确认 newDocument/addObject/recompute/closeDocument 全通。
|
||||
- 手册第 15 章写 `Ctrl+K` 打开命令面板,壳层只实现 `Ctrl+Shift+P` → `project-shell.tsx` 同时支持两者。
|
||||
- ch05 场景 fixture 硬编码旧树路径 → 改为本树绝对路径。
|
||||
- 元素截图/章末画布采样在模态遮挡下 30s 超时 → `shot` 与 `canvasHash` 改为有界超时 + viewport/clip 回退(证据能力,不改变产品断言)。
|
||||
- `X-opfs-roundtrip` / `X-save-reopen` 报「120 s 内没有 .FCStd」:`cases/crosscut.mjs` 的 `listExports/readExport` 接受 `dirName` 却把硬编码 `EXPORTS` 传给 `page.evaluate`,始终只列 `freecad-exports` → 改传 `dirName`。产品行为正常,FCStd 一直落在 `freecad-documents`。
|
||||
- glTF/GLB 导出报 `glTF writer is unavailable - OCCT has been built without RapidJSON support`:OCCT WASM 以 `USE_RAPIDJSON=OFF` 配置 → `tools/rebuild-occt-rwgltf-rapidjson.sh` 用 `-DHAVE_RAPIDJSON` 单点重编 4 个 `RWGltf` 编译单元(RapidJSON 1.1.0 位于 `build-web/rapidjson/`)并替换 3 份 `libTKRWMesh.a`,再重链 `FreeCADWebDocumentProbe`、同步资产、重建 dist。**任何一次完整 OCCT 重建后用该脚本恢复**,否则会静默回退。
|
||||
- `ExportService` 白名单缺 `.gltf`/`.glb`,导出返回 `unsupported_extension` → `web/src/export-service.ts` 的 `EXTENSIONS` 补齐。
|
||||
- `MOD-Fem-01` 的 `fem.action` 报 `memory access out of bounds`:`web/tools/sync-assets.mjs` 固定从 `build-web/fem-wasm/bin` 复制 Fem 探针(11 月 14 日旧产物),覆盖了 `build-web/configure/bin` 里重新链好的版本 → 改为与 CAM 相同的「按 mtime 择新」策略,`buildProfileForProbe` 同步跟随实际来源。旧产物与当前构建图特性不一致,正是该 OOB 的已知根因。
|
||||
- 工作台 / PartDesign 整页滚动、面板无独立滚动条(左右面板改参数时三维视口被挤出):`web/src/panel-scroll.css` 统一三栏高度链(`html.stage-lock` / `html.stage-lock-pd` → `body` 100dvh → `#app`/根 div `flex:1 1 0%` → `.layout{grid-template-rows:minmax(0,1fr)}` → `aside{overflow:hidden}` → `.pane-scroll{overflow-y:auto}`),入口按页加根类;`X-panel-scroll` 逐页断言面板独立滚动且中央视口不动。注意 `flex-basis` 必须是 `0%`,用 `auto` 会让面板内容高度参与收缩并推移舞台。
|
||||
- 模块任务面板(Mesh 建规则网格、Robot 关节、Assembly、Draft…)渲染在 `.layout` 之前的文档流里,内容长高会把三栏布局顶出视口(Robot 页 `.layout` top≈1490、asides 仅 32px;Mesh 点 Create 后按钮跑到 y≈2131)→ `workbench-shell.tsx` 把这些面板(Start 工作区 iframe 除外)包进 `.module-task-dock`,由 `panel-scroll.css` 给其 `max-height:42dvh` + 自滚动。包装起点必须位于**所有**模块任务面板之前,只包后半段会让 Mesh 仍然塌陷。
|
||||
- 文档树里非 PartDesign 的 3D 对象图标 404(`/icons/partdesign/Part_3D_object.svg`):`project-shell.tsx` / `partdesign-workspace-component.tsx` 把 Part 图标拼进了 partdesign 目录,实际文件在 `/icons/part/Part_3D_object.svg` → 改回正确目录;`capture.mjs` 的 ch01 场景冒烟以此为断言。
|
||||
|
||||
## OPFS 目录契约(用例寻址口径)
|
||||
|
||||
- 保存的 FCStd 文档在 `freecad-documents`(`writeDocumentFile`),几何导出在 `freecad-exports`(`writeExportFile`),参数在 `freecad-parameters`。用例必须按目录分别轮询/回读,禁止跨目录假设;下载目录始终为空,导出不得自动下载。
|
||||
96
tools/functional-suite/cases/chapters.mjs
Normal file
96
tools/functional-suite/cases/chapters.mjs
Normal file
@@ -0,0 +1,96 @@
|
||||
// P1 chapter cases: every manual scenario JSON runs through the same action
|
||||
// interpreter the screenshot capture tool uses, with per-action step evidence.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createActionRunner } from "../../../web/tools/manual/lib/actions.mjs";
|
||||
import { canvasHash, pageState, root } from "../runtime.mjs";
|
||||
|
||||
const SCENARIO_DIR = path.join(root, "web", "manual", "scenarios");
|
||||
// Chapters that import/export large fixtures or drive slow workers need a
|
||||
// longer ceiling than the 10-minute default.
|
||||
const TIMEOUT_OVERRIDES = { ch07: 900000, ch09: 900000, ch10: 900000, ch12: 900000 };
|
||||
|
||||
function group(actions) {
|
||||
const groups = [];
|
||||
let waits = [];
|
||||
for (const action of actions) {
|
||||
if (action.type === "wait") { waits.push(action); continue; }
|
||||
groups.push({ action, waits });
|
||||
waits = [];
|
||||
}
|
||||
if (waits.length) groups.push({ action: null, waits });
|
||||
return groups;
|
||||
}
|
||||
|
||||
function describe(action) {
|
||||
if (!action) return "等待渲染";
|
||||
switch (action.type) {
|
||||
case "goto": return `打开 ${action.url}`;
|
||||
case "click": return `点击 ${action.selector ?? `${action.role}:${action.name}`}`;
|
||||
case "fill": return `填写 ${action.selector}`;
|
||||
case "select": return `选择 ${action.selector}`;
|
||||
case "selectIndex": return `选择 ${action.selector}[${action.index}]`;
|
||||
case "press": return `按键 ${action.key}`;
|
||||
case "shot": return `截图 ${action.name}`;
|
||||
case "save": return "保存 FCStd 到 OPFS";
|
||||
case "seed": return `注入样例 ${action.name ?? path.basename(action.file)}`;
|
||||
case "eval": return "执行页面脚本";
|
||||
case "drag": return `拖拽 ${action.selector}`;
|
||||
case "clickCanvas": return `点击画布 ${action.selector}`;
|
||||
case "waitFor": return `等待 ${action.selector ?? action.text}`;
|
||||
case "waitOptions": return `等待选项 ${action.selector}`;
|
||||
default: return `${action.type} ${action.selector ?? action.contains ?? ""}`.trim();
|
||||
}
|
||||
}
|
||||
|
||||
function expected(action) {
|
||||
if (!action) return "页面稳定";
|
||||
if (action.type === "assertText" || action.type === "assertAnyText") return `文本包含「${action.contains}」`;
|
||||
if (action.type === "assertValue") return `值为 ${action.value}`;
|
||||
if (action.type === "assertVisible") return "元素可见";
|
||||
if (action.type === "shot") return "截图非空(>1KB)";
|
||||
if (action.type === "save") return "OPFS 出现新的 .FCStd";
|
||||
return "动作成功执行";
|
||||
}
|
||||
|
||||
function loadScenarios() {
|
||||
return fs.readdirSync(SCENARIO_DIR).filter(name => name.endsWith(".json")).sort().map(name => {
|
||||
const scenario = JSON.parse(fs.readFileSync(path.join(SCENARIO_DIR, name), "utf8"));
|
||||
return { file: name, scenario };
|
||||
});
|
||||
}
|
||||
|
||||
export const chapterCases = loadScenarios().map(({ file, scenario }) => ({
|
||||
id: `CH-${scenario.chapter}-${scenario.workflow}`,
|
||||
title: `${scenario.title ?? scenario.workflow}(${scenario.chapter})`,
|
||||
priority: "P1",
|
||||
executor: "scenario",
|
||||
module: null,
|
||||
source: `web/manual/scenarios/${file}`,
|
||||
timeoutMs: TIMEOUT_OVERRIDES[scenario.chapter] ?? 600000,
|
||||
async run({ page, origin, step, ctx, caseDir }) {
|
||||
const runner = createActionRunner(page, {
|
||||
origin,
|
||||
shotDir: path.join(caseDir, "shots"),
|
||||
shotPrefix: `${scenario.chapter}/${scenario.workflow}/`,
|
||||
});
|
||||
let index = 0;
|
||||
for (const { action, waits } of group(scenario.actions)) {
|
||||
index += 1;
|
||||
const label = action ? `${index}. ${describe(action)}` : `${index}. ${describe(null)}`;
|
||||
await step(label, expected(action), async () => {
|
||||
for (const wait of waits) await page.waitForTimeout(wait.ms ?? 500);
|
||||
if (action) await runner.run(action);
|
||||
return { type: action?.type ?? "wait", waits: waits.length };
|
||||
});
|
||||
}
|
||||
await step("章末后置断言", "无 pageerror、状态栏无 Error、画布可渲染", async () => {
|
||||
if (ctx.session.pageErrors.length) throw new Error(`page errors: ${JSON.stringify(ctx.session.pageErrors.slice(0, 3))}`);
|
||||
const state = await pageState(page);
|
||||
if (state.status && /^\s*Error:/.test(state.status)) throw new Error(`status bar reports ${state.status}`);
|
||||
const canvas = await canvasHash(page);
|
||||
if (canvas && canvas.bytes < 1024) throw new Error(`canvas screenshot too small: ${canvas.bytes}`);
|
||||
return { status: state.status, canvas: canvas ? { bytes: canvas.bytes, sha256: canvas.sha256 } : null };
|
||||
});
|
||||
},
|
||||
}));
|
||||
344
tools/functional-suite/cases/crosscut.mjs
Normal file
344
tools/functional-suite/cases/crosscut.mjs
Normal file
@@ -0,0 +1,344 @@
|
||||
// P3 cross-cutting cases: export formats, the OPFS contract, save/reopen and
|
||||
// error recovery. Each case prepares its own document from the project shell.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { assertNoPageErrors } from "../../ui-parity-preflight.mjs";
|
||||
import { canvasHash, openRoute, root, VIEWPORT } from "../runtime.mjs";
|
||||
import { closeStartDialog, closeTaskPanel, openFileMenu, waitCubeEnabled } from "./shell.mjs";
|
||||
|
||||
const fail = message => { throw new Error(message); };
|
||||
// storage.ts keeps the two OPFS contracts separate: geometry exports land in
|
||||
// freecad-exports, saved FCStd documents in freecad-documents.
|
||||
const EXPORTS = "freecad-exports";
|
||||
const DOCUMENTS = "freecad-documents";
|
||||
|
||||
async function listExports(page, dirName = EXPORTS) {
|
||||
return page.evaluate(async dirName => {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
let dir;
|
||||
try { dir = await root.getDirectoryHandle(dirName); } catch { return []; }
|
||||
const out = [];
|
||||
for await (const [name, handle] of dir.entries()) {
|
||||
if (handle.kind !== "file") continue;
|
||||
const file = await handle.getFile();
|
||||
out.push({ name, size: file.size });
|
||||
}
|
||||
return out;
|
||||
}, dirName);
|
||||
}
|
||||
|
||||
async function readExport(page, name, dirName = EXPORTS) {
|
||||
return page.evaluate(async ([dirName, fileName]) => {
|
||||
const root = await navigator.storage.getDirectory();
|
||||
const dir = await root.getDirectoryHandle(dirName);
|
||||
const handle = await dir.getFileHandle(fileName);
|
||||
const file = await handle.getFile();
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
let hash = 0x811c9dc5;
|
||||
for (const byte of bytes) { hash ^= byte; hash = Math.imul(hash, 0x01000193) >>> 0; }
|
||||
return { size: bytes.length, hash, head: Array.from(bytes.slice(0, 16)) };
|
||||
}, [dirName, name]);
|
||||
}
|
||||
|
||||
// Export/save controls live inside a collapsed <details>; the shell's menu item
|
||||
// just sets .open, so the case does the same before touching them.
|
||||
async function openFileTools(page) {
|
||||
await page.evaluate(() => { const panel = document.querySelector("details.file-tools"); if (panel) panel.open = true; });
|
||||
await page.waitForTimeout(200);
|
||||
}
|
||||
|
||||
async function openProjectWithCube(page, origin) {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
await closeStartDialog(page);
|
||||
const menu = await openFileMenu(page);
|
||||
await menu.locator("button.action", { hasText: "新建 Document" }).first().click();
|
||||
await waitCubeEnabled(page);
|
||||
await page.getByRole("toolbar", { name: "Solids" }).getByRole("button", { name: "Cube", exact: true }).click();
|
||||
await closeTaskPanel(page);
|
||||
await page.waitForFunction(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? "") > 0, null, { timeout: 120000 });
|
||||
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
|
||||
if (Math.abs(volume - 1000) > 1e-6) fail(`precondition: cube volume ${volume} != 1000`);
|
||||
await openFileTools(page);
|
||||
return { volume };
|
||||
}
|
||||
|
||||
async function selectCube(page) {
|
||||
// The export button only enables for a selected Part:: object.
|
||||
const disabled = await page.locator('button[aria-label="导出选中对象"]').isDisabled();
|
||||
if (disabled) await page.locator('[role="treeitem"]').first().click();
|
||||
await page.waitForTimeout(200);
|
||||
}
|
||||
|
||||
async function exportFormat(page, format) {
|
||||
const before = new Set((await listExports(page)).map(item => item.name));
|
||||
await page.locator('select[aria-label="Native export format"]').selectOption(format);
|
||||
await selectCube(page);
|
||||
await page.locator('button[aria-label="导出选中对象"]').click();
|
||||
const deadline = Date.now() + 120000;
|
||||
while (Date.now() < deadline) {
|
||||
const fresh = (await listExports(page)).filter(item => !before.has(item.name) && item.size > 0);
|
||||
if (fresh.length) return fresh[0];
|
||||
await page.waitForTimeout(400);
|
||||
}
|
||||
throw new Error(`export ${format} produced no OPFS file within 120 s`);
|
||||
}
|
||||
|
||||
export const crosscutCases = [
|
||||
{
|
||||
id: "X-export-formats",
|
||||
title: "五种导出格式全部落 OPFS 且字节非空",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "manual ch07 / OPFS 铁律",
|
||||
timeoutMs: 600000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("准备:新建文档并创建 Cube", "体积 1000 mm³", async () => openProjectWithCube(page, origin));
|
||||
const formats = [["stl", /\.stl$/i], ["step", /\.(step|stp)$/i], ["iges", /\.(iges|igs)$/i], ["brep", /\.(brep|brp)$/i], ["glb", /\.glb$/i]];
|
||||
for (const [format, pattern] of formats) {
|
||||
await step(`导出 ${format.toUpperCase()} 到 OPFS`, `freecad-exports 出现匹配 ${pattern} 的非空文件`, async () => {
|
||||
const file = await exportFormat(page, format);
|
||||
if (!pattern.test(file.name)) fail(`${format} export produced ${file.name}`);
|
||||
return file;
|
||||
});
|
||||
}
|
||||
await step("全程未触发浏览器下载", "downloads 目录为空(下载必须显式)", async () => {
|
||||
const downloads = path.join(ctx.output, "downloads");
|
||||
const files = fs.existsSync(downloads) ? fs.readdirSync(downloads) : [];
|
||||
if (files.length) fail(`unexpected downloads: ${files.join(", ")}`);
|
||||
return { downloads: 0 };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "X-opfs-roundtrip",
|
||||
title: "FCStd 保存到 OPFS、列目录、回读哈希一致",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "manual ch15 / storage.ts 契约",
|
||||
timeoutMs: 300000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("准备:新建文档并创建 Cube", "体积 1000 mm³", async () => openProjectWithCube(page, origin));
|
||||
await step("保存 FCStd 到 OPFS", "freecad-documents 出现 .FCStd 文件", async () => {
|
||||
const before = new Set((await listExports(page, DOCUMENTS)).map(item => item.name));
|
||||
await page.getByRole("button", { name: "保存 FCStd 到 OPFS" }).click();
|
||||
const deadline = Date.now() + 120000;
|
||||
while (Date.now() < deadline) {
|
||||
const fresh = (await listExports(page, DOCUMENTS)).filter(item => !before.has(item.name) && /\.fcstd$/i.test(item.name));
|
||||
if (fresh.length) return fresh[0];
|
||||
await page.waitForTimeout(400);
|
||||
}
|
||||
const present = (await listExports(page, DOCUMENTS)).map(item => item.name);
|
||||
throw new Error(`save produced no .FCStd file in OPFS within 120 s; freecad-documents=[${present.join(", ")}]`);
|
||||
});
|
||||
await step("OPFS 文档下拉列出该文件", "select[aria-label=\"OPFS document\"] 含保存项", async () => {
|
||||
const options = await page.locator('select[aria-label="OPFS document"] option').evaluateAll(nodes => nodes.map(node => node.value).filter(Boolean));
|
||||
const saved = (await listExports(page, DOCUMENTS)).find(item => /\.fcstd$/i.test(item.name));
|
||||
if (!saved) fail("no .FCStd file to verify");
|
||||
if (!options.includes(saved.name)) fail(`OPFS document select missing ${saved.name}: ${JSON.stringify(options)}`);
|
||||
return { saved: saved.name, options };
|
||||
});
|
||||
await step("两次回读哈希一致", "FNV 哈希与字节长度稳定", async () => {
|
||||
const saved = (await listExports(page, DOCUMENTS)).find(item => /\.fcstd$/i.test(item.name));
|
||||
const first = await readExport(page, saved.name, DOCUMENTS);
|
||||
const second = await readExport(page, saved.name, DOCUMENTS);
|
||||
if (second.size !== first.size || second.hash !== first.hash) fail(`unstable readback: ${first.size}/${first.hash} vs ${second.size}/${second.hash}`);
|
||||
if (!(first.size > 0)) fail("saved FCStd is empty");
|
||||
return first;
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "X-save-reopen",
|
||||
title: "保存后刷新页面可从 OPFS 重新打开文档",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "manual ch15 / OPFS 铁律",
|
||||
timeoutMs: 360000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("准备:新建文档、创建 Cube 并保存", "体积 1000 mm³ 且 OPFS 中存在 .FCStd", async () => {
|
||||
await openProjectWithCube(page, origin);
|
||||
const before = new Set((await listExports(page, DOCUMENTS)).map(item => item.name));
|
||||
await page.getByRole("button", { name: "保存 FCStd 到 OPFS" }).click();
|
||||
const deadline = Date.now() + 120000;
|
||||
while (Date.now() < deadline) {
|
||||
const fresh = (await listExports(page, DOCUMENTS)).filter(item => !before.has(item.name) && /\.fcstd$/i.test(item.name));
|
||||
if (fresh.length) return fresh[0];
|
||||
await page.waitForTimeout(400);
|
||||
}
|
||||
throw new Error("save produced no .FCStd file within 120 s");
|
||||
});
|
||||
await step("刷新后从 OPFS 重新打开", "文档树恢复且体积回到 1000 mm³", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
await closeStartDialog(page);
|
||||
await openFileTools(page);
|
||||
const saved = (await listExports(page, DOCUMENTS)).find(item => /\.fcstd$/i.test(item.name));
|
||||
if (!saved) fail("OPFS lost the saved document across reload");
|
||||
await page.locator('select[aria-label="OPFS document"]').selectOption(saved.name);
|
||||
await page.getByRole("button", { name: "打开 OPFS 文档" }).click();
|
||||
await page.waitForFunction(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? "") > 0, null, { timeout: 180000 });
|
||||
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
|
||||
const tree = await page.evaluate(() => [...document.querySelectorAll('[role="treeitem"]')].map(node => node.textContent.trim()));
|
||||
if (!tree.length) fail("document tree empty after reopen");
|
||||
if (Math.abs(volume - 1000) > 1e-6) fail(`reopened volume ${volume} != 1000`);
|
||||
return { volume, tree: tree.slice(0, 5) };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "X-error-recovery",
|
||||
title: "导入损坏 STEP 报错且文档保持完好",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "manual ch07 / 错误恢复",
|
||||
timeoutMs: 300000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("准备:新建文档并创建 Cube", "体积 1000 mm³", async () => openProjectWithCube(page, origin));
|
||||
await step("导入损坏的 STEP 文件", "状态栏报告失败且体积仍为 1000 mm³", async () => {
|
||||
const input = page.locator('input[aria-label="Import JT, PLMXML, STEPZ, 3MF or shape files"]');
|
||||
await input.setInputFiles({ name: "broken.step", mimeType: "text/plain", buffer: Buffer.from("ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=CARTESIAN_POINT('',(0,0));\nENDSEC;\nEND-ISO-10303-21;\n") });
|
||||
await page.waitForFunction(() => {
|
||||
const status = document.querySelector(".desktop-status-bar [role=status]")?.textContent ?? "";
|
||||
return /fail|error|失败|不支持|无法|invalid/i.test(status);
|
||||
}, null, { timeout: 120000 });
|
||||
const status = await page.evaluate(() => document.querySelector(".desktop-status-bar [role=status]")?.textContent ?? "");
|
||||
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
|
||||
if (!(Math.abs(volume - 1000) < 1e-6)) fail(`document changed after failed import: volume ${volume}`);
|
||||
return { status: status.slice(0, 160), volume };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "X-viewport",
|
||||
title: "工程页与工作台页均无横向溢出且画布在视口内",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "manual ch01",
|
||||
timeoutMs: 180000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("工程页无横向溢出", "scrollWidth 不超过 clientWidth", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
const metrics = await page.evaluate(() => ({ scrollWidth: document.scrollingElement.scrollWidth, clientWidth: document.scrollingElement.clientWidth, viewport: innerWidth }));
|
||||
if (metrics.scrollWidth > metrics.clientWidth + 1) fail(`project page overflows: ${metrics.scrollWidth} > ${metrics.clientWidth}`);
|
||||
if (metrics.viewport !== VIEWPORT.width) fail(`viewport ${metrics.viewport} != ${VIEWPORT.width}`);
|
||||
return metrics;
|
||||
});
|
||||
await step("画布哈希可采样", "canvas 至少 1024 字节", async () => {
|
||||
const hash = await canvasHash(page);
|
||||
if (!hash || hash.bytes < 1024) fail(`canvas hash too small: ${JSON.stringify(hash)}`);
|
||||
return hash;
|
||||
});
|
||||
await step("工作台页无横向溢出", "workbench scrollWidth 不超过 clientWidth", async () => {
|
||||
await openRoute(page, { origin }, "/workbench.html?module=Part");
|
||||
const metrics = await page.evaluate(() => ({ scrollWidth: document.scrollingElement.scrollWidth, clientWidth: document.scrollingElement.clientWidth }));
|
||||
if (metrics.scrollWidth > metrics.clientWidth + 1) fail(`workbench overflows: ${metrics.scrollWidth} > ${metrics.clientWidth}`);
|
||||
return metrics;
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "X-panel-scroll",
|
||||
title: "所有页面三栏布局的左右面板独立滚动且中间舞台不动",
|
||||
priority: "P3",
|
||||
executor: "functional",
|
||||
source: "布局需求:左右面板各自滚动,三维视口保持可见",
|
||||
timeoutMs: 300000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
// Injects a tall spacer into every side-pane scroller, so overflow is a
|
||||
// property of the layout rather than of whatever content happens to be
|
||||
// loaded; then scrolls both panes and checks the centre stage did not move.
|
||||
const probe = () => page.evaluate(() => {
|
||||
const layout = document.querySelector(".layout, .design-layout");
|
||||
const asides = layout ? [...layout.querySelectorAll(":scope > aside")].filter(node => node.getClientRects().length) : [];
|
||||
const main = layout?.querySelector(":scope > main");
|
||||
const stageBefore = main?.getBoundingClientRect();
|
||||
const panes = [];
|
||||
const scrollers = [];
|
||||
asides.forEach((aside, index) => {
|
||||
const pane = aside.querySelector(":scope > .pane-scroll");
|
||||
const entry = { index, asideOverflow: getComputedStyle(aside).overflow, asideHeight: aside.clientHeight, asideBottom: Math.round(aside.getBoundingClientRect().bottom) };
|
||||
panes.push(entry);
|
||||
if (!pane) { entry.error = "missing .pane-scroll"; return; }
|
||||
const spacer = document.createElement("div");
|
||||
spacer.style.height = "2000px";
|
||||
pane.appendChild(spacer);
|
||||
entry.overflowY = getComputedStyle(pane).overflowY;
|
||||
entry.clientHeight = pane.clientHeight;
|
||||
entry.scrollHeight = pane.scrollHeight;
|
||||
scrollers.push(pane);
|
||||
});
|
||||
for (const pane of scrollers) pane.scrollTop = 400;
|
||||
const stageAfter = main?.getBoundingClientRect();
|
||||
for (const pane of scrollers) { const spacer = pane.lastElementChild; if (spacer?.style.height === "2000px") spacer.remove(); }
|
||||
return {
|
||||
hasLayout: Boolean(layout), asideCount: asides.length, panes,
|
||||
viewportHeight: innerHeight,
|
||||
docScrollHeight: document.scrollingElement?.scrollHeight ?? 0,
|
||||
stageShift: stageBefore && stageAfter
|
||||
? Math.abs(stageAfter.top - stageBefore.top) + Math.abs(stageAfter.height - stageBefore.height) : null,
|
||||
};
|
||||
});
|
||||
const verify = (label, metrics) => {
|
||||
if (!metrics.hasLayout) fail(`${label}: three-column layout missing`);
|
||||
if (metrics.asideCount !== 2) fail(`${label}: expected 2 side panels, found ${metrics.asideCount}`);
|
||||
for (const pane of metrics.panes) {
|
||||
if (pane.error) fail(`${label}: side panel ${pane.index} ${pane.error}`);
|
||||
if (pane.overflowY !== "auto") fail(`${label}: side panel ${pane.index} overflow-y ${pane.overflowY}`);
|
||||
if (!(pane.scrollHeight > pane.clientHeight + 1)) fail(`${label}: side panel ${pane.index} does not scroll (${pane.scrollHeight} <= ${pane.clientHeight})`);
|
||||
if (pane.asideOverflow !== "hidden") fail(`${label}: side panel ${pane.index} overflow ${pane.asideOverflow}`);
|
||||
if (pane.asideBottom > metrics.viewportHeight + 1) fail(`${label}: side panel ${pane.index} bottom ${pane.asideBottom} exceeds viewport ${metrics.viewportHeight}`);
|
||||
}
|
||||
if (metrics.docScrollHeight > metrics.viewportHeight + 1) fail(`${label}: page still scrolls (${metrics.docScrollHeight} > ${metrics.viewportHeight})`);
|
||||
if (metrics.stageShift === null || metrics.stageShift > 1) fail(`${label}: centre stage moved while scrolling panels (${metrics.stageShift})`);
|
||||
};
|
||||
await step("工程页左右面板独立滚动", "两个 aside 各自滚动,整页不滚动,舞台不动", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
await page.waitForSelector(".layout > aside");
|
||||
const metrics = await probe();
|
||||
verify("project.html", metrics);
|
||||
return metrics;
|
||||
});
|
||||
await step("PartDesign 页左右面板独立滚动", "树面板与属性面板各自滚动,视口不动", async () => {
|
||||
await openRoute(page, { origin }, "/partdesign.html");
|
||||
await page.waitForSelector(".design-layout > aside");
|
||||
const metrics = await probe();
|
||||
verify("partdesign.html", metrics);
|
||||
return metrics;
|
||||
});
|
||||
await step("全部工作台模块三栏独立滚动", "每个 module 页两个面板均可滚动", async () => {
|
||||
const registry = JSON.parse(fs.readFileSync(path.join(root, "docs", "current", "feature-capability-registry.json"), "utf8"));
|
||||
const modules = registry.modules.map(meta => meta.module);
|
||||
const checked = [];
|
||||
const failures = [];
|
||||
for (const name of modules) {
|
||||
await openRoute(page, { origin }, `/workbench.html?module=${encodeURIComponent(name)}`);
|
||||
await page.waitForSelector(".layout > aside");
|
||||
const metrics = await probe();
|
||||
try { verify(`workbench:${name}`, metrics); checked.push(name); }
|
||||
catch (error) { failures.push(String(error.message ?? error)); }
|
||||
}
|
||||
if (failures.length) fail(`${failures.length}/${modules.length} module layouts failed: ${failures.slice(0, 5).join(" | ")}`);
|
||||
return { modules: checked.length };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
];
|
||||
96
tools/functional-suite/cases/handwritten.mjs
Normal file
96
tools/functional-suite/cases/handwritten.mjs
Normal file
@@ -0,0 +1,96 @@
|
||||
// Hand-written chapter cases for the chapters that ship no scenario JSON.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { dismissStartWorkspace, openRoute, root } from "../runtime.mjs";
|
||||
import { runCommand, selectModule } from "./modules.mjs";
|
||||
|
||||
const COURSE = path.join(root, "web", "tools", "line-course");
|
||||
const MEDIA = path.join(root, "web", "teaching", "media", "line-course");
|
||||
|
||||
export const handwrittenCases = [
|
||||
{
|
||||
id: "CH-ch14-production-line",
|
||||
title: "生产线课程:规格表、收口证据与媒体资产",
|
||||
priority: "P1",
|
||||
executor: "assets",
|
||||
source: "web/manual/content/ch14-production-line.md",
|
||||
timeoutMs: 60000,
|
||||
async run({ step }) {
|
||||
await step("line-spec 规格表可解析", "27 个模型 / 88 个部件 / 三角面 > 0 / 6 分量包围盒", async () => {
|
||||
const spec = JSON.parse(fs.readFileSync(path.join(COURSE, "line-spec.json"), "utf8"));
|
||||
const bbox = spec.sceneBBox;
|
||||
if (spec.modelCount !== 27) throw new Error(`modelCount ${spec.modelCount} != 27`);
|
||||
if (spec.partCount !== 88) throw new Error(`partCount ${spec.partCount} != 88`);
|
||||
if (!(spec.triangleCount > 0)) throw new Error(`triangleCount ${spec.triangleCount} is not positive`);
|
||||
if (!Array.isArray(bbox) || bbox.length !== 6 || !bbox.every(value => typeof value === "number" && Number.isFinite(value))) throw new Error(`sceneBBox is not 6 finite numbers: ${JSON.stringify(bbox)}`);
|
||||
return { modelCount: spec.modelCount, partCount: spec.partCount, triangleCount: spec.triangleCount, bbox };
|
||||
});
|
||||
await step("收口证据可解析", "final-status.json 含 state 与 knownBoundaries", async () => {
|
||||
const status = JSON.parse(fs.readFileSync(path.join(COURSE, "evidence", "final-status.json"), "utf8"));
|
||||
if (!status.state) throw new Error("final-status.json has no state");
|
||||
if (!("knownBoundaries" in status)) throw new Error("final-status.json has no knownBoundaries");
|
||||
return { state: status.state, keys: Object.keys(status).length };
|
||||
});
|
||||
await step("媒体目录非空", "至少一集视频或截图", async () => {
|
||||
const count = fs.readdirSync(MEDIA).length;
|
||||
if (count < 1) throw new Error("media directory is empty");
|
||||
return { files: count };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "CH-ch15-help-start",
|
||||
title: "帮助、命令面板、偏好与快捷键(第 15 章)",
|
||||
priority: "P1",
|
||||
executor: "functional",
|
||||
source: "web/manual/content/ch15-help-start.md",
|
||||
timeoutMs: 240000,
|
||||
async run({ page, origin, step }) {
|
||||
await step("Help 工作台源码清点可执行", "help.inspectSourceInventory 返回 kind=result", async () => {
|
||||
await openRoute(page, { origin }, "/workbench.html?module=Help");
|
||||
await dismissStartWorkspace(page);
|
||||
await selectModule(page, "Help");
|
||||
const response = await runCommand(page, "help.inspectSourceInventory");
|
||||
if (response?.kind !== "result") throw new Error(`help.inspectSourceInventory: ${JSON.stringify(response?.error ?? response).slice(0, 240)}`);
|
||||
return { kind: response.kind };
|
||||
});
|
||||
await step("Ctrl+K 打开命令面板并检索到命令", "面板可见且 Part_Box 出现在结果中", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
await page.keyboard.press("Control+k");
|
||||
const palette = page.locator('[role="dialog"][aria-label="Command palette"]');
|
||||
await palette.waitFor({ state: "visible", timeout: 15000 });
|
||||
await palette.getByLabel("Search commands").fill("Part_Box");
|
||||
const hit = palette.locator("button", { has: page.locator("code", { hasText: "Part_Box" }) }).first();
|
||||
await hit.waitFor({ state: "visible", timeout: 15000 });
|
||||
await palette.getByLabel("Close command palette").click();
|
||||
await palette.waitFor({ state: "detached", timeout: 10000 });
|
||||
return { palette: "opened", match: (await hit.count()) > 0 };
|
||||
});
|
||||
await step("偏好对话框可从 Tools 菜单打开", "Preferences 对话框含单位/主题控件", async () => {
|
||||
await page.locator(".utility-menus > button", { hasText: "Tools" }).first().click();
|
||||
await page.locator('[role="menu"][aria-label="Tools"] button', { hasText: "Preferences…" }).click();
|
||||
const dialog = page.locator('[role="dialog"][aria-label="Preferences"]');
|
||||
await dialog.waitFor({ state: "visible", timeout: 15000 });
|
||||
const units = await dialog.getByLabel("Unit system").count();
|
||||
const theme = await dialog.getByLabel("Theme").count();
|
||||
if (!units || !theme) throw new Error(`preferences controls missing: units=${units} theme=${theme}`);
|
||||
await dialog.getByLabel("Close preferences").click();
|
||||
await dialog.waitFor({ state: "detached", timeout: 10000 });
|
||||
return { units, theme };
|
||||
});
|
||||
await step("快捷键管理器可从 Tools 菜单打开", "Customize shortcuts 对话框可搜索命令", async () => {
|
||||
await page.locator(".utility-menus > button", { hasText: "Tools" }).first().click();
|
||||
await page.locator('[role="menu"][aria-label="Tools"] button', { hasText: "Customize shortcuts…" }).click();
|
||||
const dialog = page.locator('[role="dialog"][aria-label="Customize shortcuts"]');
|
||||
await dialog.waitFor({ state: "visible", timeout: 15000 });
|
||||
await dialog.getByLabel("Search shortcuts").fill("Part_Box");
|
||||
await page.waitForTimeout(300);
|
||||
const rows = await dialog.locator("tbody tr").count();
|
||||
if (!rows) throw new Error("shortcut search returned no rows for Part_Box");
|
||||
await dialog.getByLabel("Close shortcut editor").click();
|
||||
await dialog.waitFor({ state: "detached", timeout: 10000 });
|
||||
return { rows };
|
||||
});
|
||||
},
|
||||
},
|
||||
];
|
||||
12
tools/functional-suite/cases/index.mjs
Normal file
12
tools/functional-suite/cases/index.mjs
Normal file
@@ -0,0 +1,12 @@
|
||||
// Case registry. Cross-cutting cases register here as they land.
|
||||
import { chapterCases } from "./chapters.mjs";
|
||||
import { crosscutCases } from "./crosscut.mjs";
|
||||
import { handwrittenCases } from "./handwritten.mjs";
|
||||
import { moduleCases } from "./modules.mjs";
|
||||
import { shellCases } from "./shell.mjs";
|
||||
|
||||
export const CASE_LAYERS = { shell: shellCases, chapters: [...chapterCases, ...handwrittenCases], modules: moduleCases, crosscut: crosscutCases };
|
||||
|
||||
export function allCases() {
|
||||
return [...CASE_LAYERS.shell, ...CASE_LAYERS.chapters, ...CASE_LAYERS.modules, ...CASE_LAYERS.crosscut];
|
||||
}
|
||||
112
tools/functional-suite/cases/modules.mjs
Normal file
112
tools/functional-suite/cases/modules.mjs
Normal file
@@ -0,0 +1,112 @@
|
||||
// P2 module smoke: every registered module must load its shell, expose its
|
||||
// command surface and answer one canonical worker command.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { root } from "../runtime.mjs";
|
||||
import { blockedPrecondition } from "../gap-ledger.mjs";
|
||||
import { dismissStartWorkspace, openRoute } from "../runtime.mjs";
|
||||
|
||||
const REGISTRY = path.join(root, "docs", "current", "feature-capability-registry.json");
|
||||
// Web FreeCAD ships without OpenSCAD (project iron rule) and AddonManager has no
|
||||
// interactive command, so neither is a functional module under test here.
|
||||
const SKIP = new Set(["OpenSCAD", "AddonManager"]);
|
||||
// Read-only commands come first: they exercise worker + registry without
|
||||
// depending on selection state or parameters, so a failure means the module
|
||||
// really is broken rather than under-specified by the smoke.
|
||||
const PREFERRED_SUFFIXES = ["inspectSourceInventory", "inspectPythonApi", "inspectRegistry", "pythonApi", "measurementApi", "navigationBoundary", "serverContract", "createRecompute"];
|
||||
// The Web module has no worker route for serverContract (browser-native module);
|
||||
// its persistence boundary command is the one that actually dispatches.
|
||||
const CANONICAL_OVERRIDES = { Web: "web.saveReopenBoundary" };
|
||||
|
||||
function loadModules() {
|
||||
const registry = JSON.parse(fs.readFileSync(REGISTRY, "utf8"));
|
||||
const byModule = new Map();
|
||||
for (const record of registry.records) {
|
||||
if (!byModule.has(record.module)) byModule.set(record.module, []);
|
||||
byModule.get(record.module).push(record);
|
||||
}
|
||||
const modules = [];
|
||||
for (const meta of registry.modules) {
|
||||
if (SKIP.has(meta.module)) continue;
|
||||
const records = byModule.get(meta.module) ?? [];
|
||||
const interactive = records.filter(record => record.uiStatus === "interactive" && record.implementationStatus === "routed");
|
||||
const override = CANONICAL_OVERRIDES[meta.module];
|
||||
const canonical = (override ? interactive.find(record => record.command === override) : null)
|
||||
?? PREFERRED_SUFFIXES.map(suffix => interactive.find(record => record.command.endsWith(suffix))).find(Boolean)
|
||||
?? interactive[0] ?? null;
|
||||
modules.push({ name: meta.module, interactive: interactive.length, canonical: canonical?.command ?? null });
|
||||
}
|
||||
return modules;
|
||||
}
|
||||
|
||||
export const MODULES = loadModules();
|
||||
|
||||
const escapeRe = text => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
export async function selectModule(page, name) {
|
||||
// Anchor the match: "Part" is a substring of "MeshPart" and "PartDesign".
|
||||
const exact = new RegExp(`^\\s*${escapeRe(name)}\\s*$`);
|
||||
const button = page.locator("button.module").filter({ has: page.locator("strong", { hasText: exact }) }).first();
|
||||
if (!(await button.count())) throw blockedPrecondition("entry", `module ${name} is not exposed in the module dock`);
|
||||
await button.click();
|
||||
// Module labels are capitalised ("Assembly") while command ids are lowercase
|
||||
// ("assembly.createRecompute"), so compare case-insensitively.
|
||||
await page.waitForFunction(expected => [...document.querySelectorAll("button.command span")].some(span => String(span.textContent).toLowerCase().startsWith(`${expected}.`)), name.toLowerCase(), { timeout: 60000 });
|
||||
}
|
||||
|
||||
export async function runCommand(page, name) {
|
||||
const exact = new RegExp(`^\\s*${escapeRe(name)}\\s*$`);
|
||||
const command = page.locator("button.command").filter({ has: page.locator("span", { hasText: exact }) }).first();
|
||||
await command.waitFor({ state: "visible", timeout: 60000 });
|
||||
await command.click();
|
||||
// The panel prefills the payload the worker expects; overwriting it with "{}"
|
||||
// is what makes an otherwise valid command fail with invalid_request.
|
||||
const args = page.getByLabel("命令 JSON 参数");
|
||||
let payload = "";
|
||||
if (await args.count()) {
|
||||
payload = (await args.inputValue()).trim();
|
||||
if (!payload) { payload = "{}"; await args.fill(payload); }
|
||||
}
|
||||
const run = page.getByRole("button", { name: "执行选中命令", exact: true });
|
||||
await run.waitFor({ state: "visible", timeout: 30000 });
|
||||
await run.click();
|
||||
await page.waitForFunction(() => window.__freecadWorkbenchState?.response?.kind === "result" || window.__freecadWorkbenchState?.response?.kind === "error", null, { timeout: 180000 });
|
||||
return page.evaluate(() => window.__freecadWorkbenchState.response);
|
||||
}
|
||||
|
||||
export const moduleCases = MODULES.map(meta => ({
|
||||
id: `MOD-${meta.name}-01`,
|
||||
title: `${meta.name} 模块冒烟:壳层、命令面与规范动作`,
|
||||
priority: "P2",
|
||||
executor: "functional",
|
||||
module: meta.name,
|
||||
source: "feature-capability-registry.json",
|
||||
timeoutMs: 240000,
|
||||
async run({ page, origin, step }) {
|
||||
await step("打开模块工作台", "模块壳层挂载且隔离头生效", async () => {
|
||||
const isolation = await openRoute(page, { origin }, `/workbench.html?module=${encodeURIComponent(meta.name)}`);
|
||||
await dismissStartWorkspace(page);
|
||||
return isolation;
|
||||
});
|
||||
await step(`${meta.name} 模块在模块坞中可选中`, "button.module 存在且被选中", async () => {
|
||||
await selectModule(page, meta.name);
|
||||
const selected = await page.evaluate(() => document.querySelector("button.module[aria-current], button.module.selected")?.textContent?.trim().slice(0, 40) ?? null);
|
||||
return { module: meta.name, selected };
|
||||
});
|
||||
await step("命令面已注册", "该模块至少注册一条命令", async () => {
|
||||
await page.waitForFunction(() => document.querySelectorAll("button.command").length > 0, null, { timeout: 60000 });
|
||||
const count = await page.locator("button.command").count();
|
||||
if (count < 1) throw new Error(`${meta.name} exposes no commands`);
|
||||
return { commands: count, registered: meta.interactive };
|
||||
});
|
||||
if (!meta.canonical) throw blockedPrecondition("command-state", `${meta.name} has no interactive routed command`);
|
||||
await step(`规范动作 ${meta.canonical}`, "原生返回 kind=result 且无 sceneError", async () => {
|
||||
const response = await runCommand(page, meta.canonical);
|
||||
if (response?.kind === "error") throw new Error(`command error: ${JSON.stringify(response.error).slice(0, 300)}`);
|
||||
const row = response?.result?.records?.[0];
|
||||
const result = row?.result ?? response?.result;
|
||||
if (result?.sceneError) throw new Error(`scene refresh failed: ${result.sceneError}`);
|
||||
return { kind: response?.kind, command: meta.canonical, hasRow: Boolean(row) };
|
||||
});
|
||||
},
|
||||
}));
|
||||
202
tools/functional-suite/cases/shell.mjs
Normal file
202
tools/functional-suite/cases/shell.mjs
Normal file
@@ -0,0 +1,202 @@
|
||||
// P0 shell cases: entry/isolation, project shell, first document, OPFS contract,
|
||||
// viewport and canvas. These are the preconditions every later case builds on.
|
||||
import { assertNoPageErrors, prepareProjectShell, prepareWorkbenchShell } from "../../ui-parity-preflight.mjs";
|
||||
import { VIEWPORT, canvasHash, dismissStartWorkspace, openRoute, pageState } from "../runtime.mjs";
|
||||
|
||||
const fail = message => { throw new Error(message); };
|
||||
|
||||
export async function waitCubeEnabled(page, timeout = 120000) {
|
||||
await page.waitForFunction(() => {
|
||||
const toolbar = document.querySelector('[role="toolbar"][aria-label="Solids"]');
|
||||
const button = toolbar ? [...toolbar.querySelectorAll("button")].find(node => node.getAttribute("aria-label") === "Cube") : undefined;
|
||||
return Boolean(button && !button.disabled);
|
||||
}, null, { timeout });
|
||||
}
|
||||
|
||||
// The application menu is a <details>/<summary> list, so the item buttons are
|
||||
// not visible until their own menu is opened — role locators never match them.
|
||||
export async function openFileMenu(page) {
|
||||
const menu = page.locator("nav.application-menus details").filter({ has: page.locator("button.action", { hasText: "新建 Document" }) }).first();
|
||||
if (!(await menu.count())) fail("File menu not found");
|
||||
await menu.locator("summary").first().click();
|
||||
await page.waitForTimeout(200);
|
||||
return menu;
|
||||
}
|
||||
|
||||
export async function closeTaskPanel(page) {
|
||||
if (await page.locator('fieldset[aria-label="Task: Box dimensions"]').count()) await page.keyboard.press("Escape");
|
||||
await page.waitForTimeout(300);
|
||||
}
|
||||
|
||||
export async function closeStartDialog(page) {
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
if (await page.locator("dialog[open]").count()) { await page.keyboard.press("Escape"); await page.waitForTimeout(250); continue; }
|
||||
await page.waitForTimeout(300);
|
||||
if ((await page.locator("dialog[open]").count()) === 0) return;
|
||||
}
|
||||
}
|
||||
|
||||
export const shellCases = [
|
||||
{
|
||||
id: "SHELL-01",
|
||||
title: "入口、COOP/COEP 隔离与工作台壳层",
|
||||
priority: "P0",
|
||||
executor: "functional",
|
||||
source: "manual ch00/ch01",
|
||||
timeoutMs: 120000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("打开 Part 工作台并确认隔离头生效", "crossOriginIsolated 且 SharedArrayBuffer 可用", async () => {
|
||||
const isolation = await openRoute(page, { origin }, "/workbench.html?module=Part");
|
||||
return isolation;
|
||||
});
|
||||
await step("工作台壳层可见且无横向溢出", ".dock-workbench 可测量、在视口内", async () => {
|
||||
const { state } = await prepareWorkbenchShell(page, { origin, path: "/workbench.html?module=Part", viewport: VIEWPORT });
|
||||
return state;
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "SHELL-02",
|
||||
title: "工程壳层与 Start 对话框",
|
||||
priority: "P0",
|
||||
executor: "functional",
|
||||
source: "manual ch01",
|
||||
timeoutMs: 120000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("打开工程页并确认工具栏就绪", ".desktop-workspace 与 Solids 工具栏可见", async () => {
|
||||
const { state } = await prepareProjectShell(page, { origin, path: "/project.html", viewport: VIEWPORT, toolbarName: "Solids", minDropdowns: 0 });
|
||||
return state;
|
||||
});
|
||||
await step("Start 对话框可关闭且不拦截操作", "dialog[open] 数量为 0", async () => {
|
||||
await closeStartDialog(page);
|
||||
await dismissStartWorkspace(page);
|
||||
const open = await page.locator("dialog[open]").count();
|
||||
if (open) fail(`Start dialog still open: ${open}`);
|
||||
return { openDialogs: 0 };
|
||||
});
|
||||
await step("工具栏图标全部渲染", "img 均 complete 且 naturalWidth > 0", async () => {
|
||||
// SVG icons 404/sniff-blocked by a wrong static-host MIME show up here
|
||||
// as naturalWidth === 0 while still returning HTTP 200.
|
||||
const icons = await page.evaluate(() => ({ total: document.images.length, broken: [...document.images].filter(image => !image.complete || image.naturalWidth === 0).map(image => image.getAttribute("src")).slice(0, 10) }));
|
||||
if (!icons.total) fail("no icon images rendered");
|
||||
if (icons.broken.length) fail(`broken icons: ${icons.broken.join(", ")}`);
|
||||
return icons;
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "SHELL-03",
|
||||
title: "新建文档、创建 Cube 并显示体积",
|
||||
priority: "P0",
|
||||
executor: "functional",
|
||||
source: "manual ch01/ch02",
|
||||
timeoutMs: 240000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
await step("关闭 Start 并新建 Document", "Solids/Cube 命令可用", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
await closeStartDialog(page);
|
||||
const menu = await openFileMenu(page);
|
||||
await menu.locator("button.action", { hasText: "新建 Document" }).first().click();
|
||||
await waitCubeEnabled(page);
|
||||
await closeStartDialog(page);
|
||||
return { cubeEnabled: true };
|
||||
});
|
||||
await step("执行 Cube 命令", "文档树出现对象且体积为 1000 mm³(默认 10mm 立方体)", async () => {
|
||||
await waitCubeEnabled(page);
|
||||
await page.getByRole("toolbar", { name: "Solids" }).getByRole("button", { name: "Cube", exact: true }).click();
|
||||
await closeTaskPanel(page);
|
||||
await page.waitForFunction(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? "") > 0, null, { timeout: 120000 });
|
||||
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
|
||||
const tree = await page.evaluate(() => [...document.querySelectorAll('[role="treeitem"]')].map(node => node.textContent.trim()));
|
||||
if (tree.length < 1) fail("document tree is empty after Cube");
|
||||
if (Math.abs(volume - 1000) > 1e-6) fail(`volume ${volume} != 1000`);
|
||||
return { volume, tree: tree.slice(0, 5) };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "SHELL-04",
|
||||
title: "OPFS 导出目录可写可读",
|
||||
priority: "P0",
|
||||
executor: "functional",
|
||||
source: "OPFS contract (web/src/storage.ts:67)",
|
||||
timeoutMs: 60000,
|
||||
async run({ page, origin, step }) {
|
||||
await step("进入同源页面", "应用挂载", async () => {
|
||||
await openRoute(page, { origin }, "/workbench.html?module=Part");
|
||||
return true;
|
||||
});
|
||||
await step("freecad-exports 目录写入、列出、回读、删除", "四步全部成功", async () => {
|
||||
const result = await page.evaluate(async () => {
|
||||
const name = `functional-suite-probe-${Date.now()}.txt`;
|
||||
const payload = new TextEncoder().encode("freecad-web-suite");
|
||||
const rootDir = await navigator.storage.getDirectory();
|
||||
const exportsDir = await rootDir.getDirectoryHandle("freecad-exports", { create: true });
|
||||
const handle = await exportsDir.getFileHandle(name, { create: true });
|
||||
const writer = await handle.createWritable();
|
||||
await writer.write(payload);
|
||||
await writer.close();
|
||||
const names = [];
|
||||
for await (const [entry] of exportsDir.entries()) names.push(entry);
|
||||
const text = await (await (await exportsDir.getFileHandle(name)).getFile()).text();
|
||||
await exportsDir.removeEntry(name);
|
||||
const after = [];
|
||||
for await (const [entry] of exportsDir.entries()) after.push(entry);
|
||||
return { bytes: payload.byteLength, listed: names.includes(name), text, removed: !after.includes(name) };
|
||||
});
|
||||
if (!result.listed) fail("probe file missing from listing");
|
||||
if (result.text !== "freecad-web-suite") fail(`read-back mismatch: ${result.text}`);
|
||||
if (!result.removed) fail("probe file was not removed");
|
||||
return result;
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "SHELL-05",
|
||||
title: "视口尺寸、画布与场景渲染",
|
||||
priority: "P0",
|
||||
executor: "functional",
|
||||
source: "manual ch01 viewport",
|
||||
timeoutMs: 120000,
|
||||
async run({ page, origin, step, ctx }) {
|
||||
// The 3D canvas lives in the project shell; the module shell only renders
|
||||
// the command browser (no canvas by design, verified in the DOM probe).
|
||||
await step("打开工程页并确认视口", "1440x1000 且无横向溢出", async () => {
|
||||
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
|
||||
const state = await page.evaluate(() => ({
|
||||
width: innerWidth, height: innerHeight,
|
||||
overflow: document.documentElement.scrollWidth > document.documentElement.clientWidth,
|
||||
}));
|
||||
if (state.width !== VIEWPORT.width || state.height !== VIEWPORT.height) fail(`viewport ${state.width}x${state.height}`);
|
||||
if (state.overflow) fail("horizontal overflow");
|
||||
return state;
|
||||
});
|
||||
await step("画布存在且有内容", "canvas 尺寸非零、截图 hash 非空", async () => {
|
||||
const canvases = await page.evaluate(() => [...document.querySelectorAll("canvas")].map(canvas => ({ width: canvas.width, height: canvas.height })));
|
||||
if (!canvases.length) fail("no canvas");
|
||||
if (!canvases.some(item => item.width > 0 && item.height > 0)) fail("canvas has zero size");
|
||||
const hash = await canvasHash(page);
|
||||
if (!hash || hash.bytes < 1024) fail(`canvas screenshot too small: ${hash?.bytes ?? 0}`);
|
||||
return { canvases, hash };
|
||||
});
|
||||
await step("页面无未捕获错误", "pageerror 为空", async () => {
|
||||
assertNoPageErrors(ctx.session.pageErrors);
|
||||
return { pageErrors: 0 };
|
||||
});
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export { pageState };
|
||||
83
tools/functional-suite/cli.mjs
Normal file
83
tools/functional-suite/cli.mjs
Normal file
@@ -0,0 +1,83 @@
|
||||
// CLI contract for the headed Web FreeCAD functional suite.
|
||||
// Every option has an env equivalent so CI wrappers can stay script-free.
|
||||
|
||||
export const USAGE = `Web FreeCAD functional suite (headed by default)
|
||||
|
||||
node tools/web-freecad-functional-suite.mjs [options]
|
||||
|
||||
--only <ids> comma separated case ids (e.g. SHELL-01,CH02-part)
|
||||
--priority <list> comma separated priorities: P0,P1,P2,P3 (default all)
|
||||
--module <list> comma separated module names for MOD-* cases
|
||||
--resume <dir> continue a previous run directory (skip completed ids)
|
||||
--force with --resume, re-run completed cases
|
||||
--headless hide the browser window (default is headed)
|
||||
--gpu drop swiftshader flags (manual perf observation only)
|
||||
--slow <ms> Playwright slowMo pacing for live observation
|
||||
--highlight outline the acted element before each action
|
||||
--screenshots <s> "fails" (default) or "all"
|
||||
--jobs <n> browser workers (1 = single headed window, default 1)
|
||||
--out <dir> evidence root (default docs/current/web-functional-suite)
|
||||
--prune <n> keep only the newest n run directories
|
||||
--legacy-ids <ids> also run tools/run_user_manual_tests.mjs ids (all = 53 cases)
|
||||
--timeout-scale <x> multiply per-case timeouts (default 1)
|
||||
|
||||
With no selection flags every non-legacy case runs.`;
|
||||
|
||||
const list = value => String(value ?? "").split(",").map(item => item.trim()).filter(Boolean);
|
||||
|
||||
export function parseArgs(argv = process.argv.slice(2)) {
|
||||
const options = {
|
||||
only: list(process.env.FREECAD_SUITE_ONLY),
|
||||
priority: list(process.env.FREECAD_SUITE_PRIORITY),
|
||||
module: list(process.env.FREECAD_SUITE_MODULE),
|
||||
resume: null, force: false,
|
||||
headless: process.env.HEADLESS === "1",
|
||||
gpu: false, slow: Number(process.env.FREECAD_SLOWMO ?? 0) || 0, highlight: false,
|
||||
screenshots: process.env.FREECAD_SUITE_SCREENSHOTS === "all" ? "all" : "fails",
|
||||
jobs: 1, out: null, prune: null, legacyIds: [], timeoutScale: 1,
|
||||
};
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const flag = argv[index];
|
||||
const value = () => argv[index + 1] ?? "";
|
||||
switch (flag) {
|
||||
case "--only": options.only = list(value()); index += 1; break;
|
||||
case "--priority": options.priority = list(value()).map(item => item.toUpperCase()); index += 1; break;
|
||||
case "--module": options.module = list(value()); index += 1; break;
|
||||
case "--resume": options.resume = value(); index += 1; break;
|
||||
case "--force": options.force = true; break;
|
||||
case "--headless": options.headless = true; break;
|
||||
case "--headed": options.headless = false; break;
|
||||
case "--gpu": options.gpu = true; break;
|
||||
case "--slow": options.slow = Number(value()) || 0; index += 1; break;
|
||||
case "--highlight": options.highlight = true; break;
|
||||
case "--screenshots": options.screenshots = value() === "all" ? "all" : "fails"; index += 1; break;
|
||||
case "--jobs": options.jobs = Math.max(1, Number(value()) || 1); index += 1; break;
|
||||
case "--out": options.out = value(); index += 1; break;
|
||||
case "--prune": options.prune = Math.max(1, Number(value()) || 1); index += 1; break;
|
||||
case "--legacy-ids": options.legacyIds = list(value()); index += 1; break;
|
||||
case "--timeout-scale": options.timeoutScale = Math.max(0.1, Number(value()) || 1); index += 1; break;
|
||||
case "--help": case "-h": options.help = true; break;
|
||||
default: throw new Error(`unknown option ${flag}\n\n${USAGE}`);
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
export function selectCases(cases, options) {
|
||||
let selected = cases;
|
||||
if (options.only.length) {
|
||||
const ids = new Set(options.only);
|
||||
selected = selected.filter(item => ids.has(item.id));
|
||||
const missing = [...ids].filter(id => !cases.some(item => item.id === id));
|
||||
if (missing.length) throw new Error(`unknown case ids: ${missing.join(", ")}`);
|
||||
}
|
||||
if (options.priority.length) {
|
||||
const priorities = new Set(options.priority);
|
||||
selected = selected.filter(item => priorities.has(item.priority));
|
||||
}
|
||||
if (options.module.length) {
|
||||
const modules = new Set(options.module.map(item => item.toLowerCase()));
|
||||
selected = selected.filter(item => !item.module || modules.has(item.module.toLowerCase()));
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
56
tools/functional-suite/executors/legacy.mjs
Normal file
56
tools/functional-suite/executors/legacy.mjs
Normal file
@@ -0,0 +1,56 @@
|
||||
// Runs the untouched manual runner (tools/run_user_manual_tests.mjs) as a child
|
||||
// process and folds its results into the functional-suite report as LEGACY-*.
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { root } from "../runtime.mjs";
|
||||
import { persist } from "../report.mjs";
|
||||
|
||||
const MAP = {
|
||||
passed: { status: "passed", classification: "none", failureClass: null },
|
||||
blocked: { status: "blocked", classification: "precondition", failureClass: "fixture" },
|
||||
failed: { status: "failed", classification: "product-regression", failureClass: "product-regression" },
|
||||
};
|
||||
|
||||
export async function runLegacyCases(options, ctx) {
|
||||
const ids = options.legacyIds.includes("all") ? "" : options.legacyIds.join(",");
|
||||
const env = { ...process.env };
|
||||
if (ids) env.FREECAD_MANUAL_IDS = ids;
|
||||
const child = spawn(process.execPath, [path.join(root, "tools", "run_user_manual_tests.mjs")], {
|
||||
cwd: root, env, stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", chunk => { stdout += chunk; process.stdout.write(chunk); });
|
||||
child.stderr.on("data", chunk => { stderr += chunk; });
|
||||
const code = await new Promise(resolve => child.on("close", resolve));
|
||||
|
||||
const lastJson = [...stdout.trim().split("\n")].reverse().find(line => line.startsWith("{") && line.includes('"output"'));
|
||||
if (!lastJson) {
|
||||
const message = `legacy runner exited ${code} without a result line: ${(stderr || stdout).slice(-400)}`;
|
||||
console.error(message);
|
||||
ctx.results.push({ id: "LEGACY-RUNNER", title: "Legacy manual runner", priority: "P4", executor: "legacy", status: "blocked", classification: "precondition", failureClass: "fixture", steps: [], seconds: 0, error: message, startedAt: new Date().toISOString(), artifacts: {} });
|
||||
persist(ctx);
|
||||
return [];
|
||||
}
|
||||
const { output: legacyDir } = JSON.parse(lastJson);
|
||||
const legacy = JSON.parse(fs.readFileSync(path.join(legacyDir, "results.json"), "utf8"));
|
||||
const imported = [];
|
||||
for (const item of legacy.results ?? []) {
|
||||
const mapped = MAP[item.status] ?? MAP.failed;
|
||||
const result = {
|
||||
id: `LEGACY-${item.id}`, title: item.title ?? item.id, priority: "P4", executor: "legacy",
|
||||
module: null, source: path.relative(root, legacyDir) + "/results.json",
|
||||
status: mapped.status, classification: mapped.classification, failureClass: mapped.failureClass,
|
||||
steps: item.steps ?? [], seconds: item.seconds ?? 0, error: item.error ?? null,
|
||||
startedAt: item.startedAt ?? null, artifacts: { legacy: path.relative(root, legacyDir) },
|
||||
};
|
||||
ctx.results.push(result);
|
||||
imported.push(result);
|
||||
if (mapped.status !== "passed") {
|
||||
ctx.gaps.push({ caseId: result.id, status: mapped.status, classification: mapped.classification, failureClass: mapped.failureClass, message: result.error ?? mapped.status, evidence: result.artifacts.legacy });
|
||||
}
|
||||
}
|
||||
persist(ctx);
|
||||
return imported;
|
||||
}
|
||||
61
tools/functional-suite/gap-ledger.mjs
Normal file
61
tools/functional-suite/gap-ledger.mjs
Normal file
@@ -0,0 +1,61 @@
|
||||
// Failure classification for the functional suite.
|
||||
// Precondition failures become `blocked`; product failures become `failed`.
|
||||
// The ledger keeps them separate so a blocked preflight never masks a regression.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { UiParityPreflightError } from "../ui-parity-preflight.mjs";
|
||||
|
||||
const PRECONDITION_CLASSES = new Set([
|
||||
"preview/port", "entry", "fixture", "viewport", "host/iframe", "command-state", "tool-observation",
|
||||
]);
|
||||
|
||||
export function classifyFailure(error) {
|
||||
if (error?.blocked === true) {
|
||||
return { status: "blocked", classification: "precondition", failureClass: error.failureClass ?? "fixture", message: String(error.message ?? error) };
|
||||
}
|
||||
if (error instanceof UiParityPreflightError) {
|
||||
const failureClass = error.failureClass;
|
||||
if (PRECONDITION_CLASSES.has(failureClass)) {
|
||||
return { status: "blocked", classification: "precondition", failureClass, message: error.message };
|
||||
}
|
||||
return { status: "failed", classification: "product-regression", failureClass, message: error.message };
|
||||
}
|
||||
// Plain assertion errors come from product steps; cases may mark a known
|
||||
// unimplemented capability as a product gap instead of a regression.
|
||||
if (error?.productGap === true) {
|
||||
return { status: "failed", classification: "product-gap", failureClass: "product-gap", message: String(error.message ?? error) };
|
||||
}
|
||||
return { status: "failed", classification: "product-regression", failureClass: "product-regression", message: String(error?.message ?? error) };
|
||||
}
|
||||
|
||||
export function blockedPrecondition(failureClass, message) {
|
||||
const error = new Error(message);
|
||||
error.blocked = true;
|
||||
error.failureClass = failureClass;
|
||||
return error;
|
||||
}
|
||||
|
||||
export function createGapLedger(file) {
|
||||
const entries = [];
|
||||
return {
|
||||
record(entry) {
|
||||
const row = { at: new Date().toISOString(), status: "open", ...entry };
|
||||
entries.push(row);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.appendFileSync(file, `${JSON.stringify(row)}\n`);
|
||||
return row;
|
||||
},
|
||||
entries,
|
||||
};
|
||||
}
|
||||
|
||||
export function renderGapSections(entries) {
|
||||
const blocked = entries.filter(item => item.classification === "precondition");
|
||||
const product = entries.filter(item => item.classification !== "precondition");
|
||||
const line = item => `- \`${item.caseId}\` ${item.failureClass}: ${item.message.slice(0, 240)}${item.evidence ? ` — ${item.evidence}` : ""}`;
|
||||
return {
|
||||
blocked: blocked.length ? blocked.map(line).join("\n") : "- none",
|
||||
product: product.length ? product.map(line).join("\n") : "- none",
|
||||
counts: { blocked: blocked.length, product: product.length },
|
||||
};
|
||||
}
|
||||
126
tools/functional-suite/report.mjs
Normal file
126
tools/functional-suite/report.mjs
Normal file
@@ -0,0 +1,126 @@
|
||||
// Run artefacts: manifest, results, checkpoint, markdown/JUnit/HTML reports.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { renderGapSections } from "./gap-ledger.mjs";
|
||||
|
||||
const ISO_STAMP = () => new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const esc = value => String(value ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
export function createRunContext({ options, root, output, origin }) {
|
||||
return {
|
||||
schema: "freecad-web/functional-suite/v1",
|
||||
root, output, origin,
|
||||
startedAt: new Date().toISOString(),
|
||||
updatedAt: null,
|
||||
options,
|
||||
results: [],
|
||||
gaps: [],
|
||||
counts: { passed: 0, failed: 0, blocked: 0, reference_only: 0, running: 0 },
|
||||
manifest: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function newRunDir(base, resume) {
|
||||
if (resume) return path.resolve(resume);
|
||||
const dir = path.join(base, `run-${ISO_STAMP()}`);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
export function writeManifest(ctx, extra = {}) {
|
||||
ctx.manifest = {
|
||||
schema: "freecad-web/functional-suite-manifest/v1",
|
||||
generatedAt: new Date().toISOString(),
|
||||
origin: ctx.origin,
|
||||
platform: process.platform,
|
||||
node: process.version,
|
||||
display: process.env.DISPLAY ?? null,
|
||||
headless: ctx.options.headless,
|
||||
command: process.argv.join(" "),
|
||||
...extra,
|
||||
};
|
||||
fs.writeFileSync(path.join(ctx.output, "manifest.json"), `${JSON.stringify(ctx.manifest, null, 2)}\n`);
|
||||
}
|
||||
|
||||
export function recount(ctx) {
|
||||
const counts = { passed: 0, failed: 0, blocked: 0, reference_only: 0, running: 0 };
|
||||
for (const result of ctx.results) counts[result.status] = (counts[result.status] ?? 0) + 1;
|
||||
ctx.counts = counts;
|
||||
return counts;
|
||||
}
|
||||
|
||||
export function persist(ctx) {
|
||||
ctx.updatedAt = new Date().toISOString();
|
||||
recount(ctx);
|
||||
fs.writeFileSync(path.join(ctx.output, "results.json"), `${JSON.stringify({
|
||||
schema: ctx.schema, startedAt: ctx.startedAt, updatedAt: ctx.updatedAt, origin: ctx.origin,
|
||||
headless: ctx.options.headless, counts: ctx.counts, results: ctx.results,
|
||||
}, null, 2)}\n`);
|
||||
const completed = ctx.results.filter(item => item.status !== "running").map(item => ({ id: item.id, status: item.status, seconds: item.seconds }));
|
||||
fs.writeFileSync(path.join(ctx.output, "checkpoint.json"), `${JSON.stringify({
|
||||
schema: "freecad-web/functional-suite-checkpoint/v1", updatedAt: ctx.updatedAt,
|
||||
current: ctx.results.find(item => item.status === "running")?.id ?? null, completed,
|
||||
}, null, 2)}\n`);
|
||||
}
|
||||
|
||||
const statusCell = item => {
|
||||
if (item.status === "passed") return "passed";
|
||||
if (item.status === "blocked") return `blocked (${item.failureClass})`;
|
||||
return `${item.status} (${item.classification})`;
|
||||
};
|
||||
|
||||
export function writeMarkdown(ctx) {
|
||||
const gaps = renderGapSections(ctx.gaps);
|
||||
const rows = ctx.results.map(item =>
|
||||
`| ${item.id} | ${item.priority} | ${statusCell(item)} | ${Number(item.seconds ?? 0).toFixed(1)}s | ${item.steps.length} | ${item.error ? item.error.slice(0, 120).replace(/\|/g, "\\|") : ""} |`);
|
||||
return `# Web FreeCAD 功能测试(有头)\n\n` +
|
||||
`- 运行:${ctx.startedAt}\n- Origin:${ctx.origin}\n- 模式:${ctx.options.headless ? "headless" : "headed"}\n` +
|
||||
`- 计数:passed ${ctx.counts.passed} / failed ${ctx.counts.failed} / blocked ${ctx.counts.blocked} / reference_only ${ctx.counts.reference_only}\n\n` +
|
||||
`## 用例\n\n| id | 优先级 | 状态 | 耗时 | 步骤 | 错误 |\n|---|---|---|---|---|---|\n${rows.join("\n")}\n\n` +
|
||||
`## Blocked(前置未满足)\n\n${gaps.blocked}\n\n## Product(产品/UI 缺口)\n\n${gaps.product}\n`;
|
||||
}
|
||||
|
||||
export function writeJUnit(ctx) {
|
||||
const body = ctx.results.map(item => {
|
||||
const time = Number(item.seconds ?? 0).toFixed(3);
|
||||
const failure = item.status === "passed" ? "" :
|
||||
item.status === "blocked"
|
||||
? `\n <skipped message="${esc(item.failureClass)}: ${esc(item.error)}"/>`
|
||||
: `\n <failure message="${esc(item.classification)}">${esc(item.error)}</failure>`;
|
||||
return ` <testcase classname="${esc(item.priority)}" name="${esc(item.id)}" time="${time}">${failure}\n </testcase>`;
|
||||
});
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>\n<testsuite name="web-freecad-functional-suite" tests="${ctx.results.length}" failures="${ctx.counts.failed}" skipped="${ctx.counts.blocked}" time="${(ctx.results.reduce((sum, item) => sum + Number(item.seconds ?? 0), 0)).toFixed(3)}">\n${body.join("\n")}\n</testsuite>\n`;
|
||||
}
|
||||
|
||||
export function writeIndex(ctx) {
|
||||
const rows = ctx.results.map(item => {
|
||||
const color = item.status === "passed" ? "#137333" : item.status === "blocked" ? "#8a6d00" : "#a50e0e";
|
||||
return `<tr><td><a href="cases/${esc(item.id)}/">${esc(item.id)}</a></td><td>${esc(item.priority)}</td><td style="color:${color}">${esc(statusCell(item))}</td><td>${Number(item.seconds ?? 0).toFixed(1)}s</td><td>${esc(item.error ? item.error.slice(0, 160) : "")}</td></tr>`;
|
||||
});
|
||||
return `<!doctype html><meta charset="utf-8"><title>Web FreeCAD functional suite</title>
|
||||
<style>body{font:14px/1.5 system-ui,sans-serif;margin:24px}table{border-collapse:collapse}td,th{border:1px solid #ddd;padding:4px 8px;text-align:left}</style>
|
||||
<h1>Web FreeCAD 功能测试(有头)</h1>
|
||||
<p>${esc(ctx.startedAt)} · origin ${esc(ctx.origin)} · passed ${ctx.counts.passed} / failed ${ctx.counts.failed} / blocked ${ctx.counts.blocked}</p>
|
||||
<table><thead><tr><th>id</th><th>优先级</th><th>状态</th><th>耗时</th><th>错误</th></tr></thead><tbody>${rows.join("")}</tbody></table>
|
||||
<p><a href="report.md">report.md</a> · <a href="results.json">results.json</a> · <a href="junit.xml">junit.xml</a></p>`;
|
||||
}
|
||||
|
||||
export function finalize(ctx) {
|
||||
persist(ctx);
|
||||
fs.writeFileSync(path.join(ctx.output, "report.md"), writeMarkdown(ctx));
|
||||
fs.writeFileSync(path.join(ctx.output, "junit.xml"), writeJUnit(ctx));
|
||||
fs.writeFileSync(path.join(ctx.output, "index.html"), writeIndex(ctx));
|
||||
const gaps = renderGapSections(ctx.gaps);
|
||||
fs.writeFileSync(path.join(ctx.output, "GAPS.md"),
|
||||
`# Gap ledger\n\n## Blocked (preconditions): ${gaps.counts.blocked}\n\n${gaps.blocked}\n\n## Product regressions/gaps: ${gaps.counts.product}\n\n${gaps.product}\n`);
|
||||
}
|
||||
|
||||
export function pruneRuns(base, keep) {
|
||||
if (!fs.existsSync(base)) return [];
|
||||
const dirs = fs.readdirSync(base, { withFileTypes: true })
|
||||
.filter(entry => entry.isDirectory() && entry.name.startsWith("run-"))
|
||||
.map(entry => entry.name).sort();
|
||||
const removed = dirs.slice(0, Math.max(0, dirs.length - keep));
|
||||
for (const name of removed) fs.rmSync(path.join(base, name), { recursive: true, force: true });
|
||||
return removed;
|
||||
}
|
||||
176
tools/functional-suite/runtime.mjs
Normal file
176
tools/functional-suite/runtime.mjs
Normal file
@@ -0,0 +1,176 @@
|
||||
// Headed browser runtime: static host, page lifecycle, per-case isolation,
|
||||
// step recording and failure evidence.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { startStaticHost, findChrome } from "../static-host.mjs";
|
||||
import { UiParityPreflightError, capturePageErrors } from "../ui-parity-preflight.mjs";
|
||||
import { classifyFailure } from "./gap-ledger.mjs";
|
||||
import { persist } from "./report.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const root = path.resolve(here, "../..");
|
||||
export const webRoot = path.join(root, "web");
|
||||
export const distRoot = path.join(webRoot, "dist");
|
||||
const requireWeb = createRequire(path.join(webRoot, "package.json"));
|
||||
export const { chromium } = requireWeb("playwright");
|
||||
|
||||
export const VIEWPORT = { width: 1440, height: 1000 };
|
||||
|
||||
export function launchOptions(options) {
|
||||
const executablePath = findChrome();
|
||||
if (!executablePath) throw new Error(`Chrome not found; set FREECAD_CHROME (tried /usr/bin/google-chrome)`);
|
||||
const args = ["--no-sandbox", "--disable-dev-shm-usage", "--window-size=1600,1000"];
|
||||
// swiftshader keeps canvas hashes and meshes deterministic across headed runs;
|
||||
// --gpu is a manual-observation escape hatch only.
|
||||
if (!options.gpu) args.push("--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader");
|
||||
return { executablePath, headless: options.headless, slowMo: options.slow || undefined, args };
|
||||
}
|
||||
|
||||
export async function startHost() {
|
||||
if (!fs.existsSync(path.join(distRoot, "index.html"))) {
|
||||
throw new Error(`web/dist/index.html is missing; run "npx vite build" in web/ first`);
|
||||
}
|
||||
return startStaticHost(distRoot);
|
||||
}
|
||||
|
||||
export async function openBrowser(options) {
|
||||
return chromium.launch(launchOptions(options));
|
||||
}
|
||||
|
||||
export async function openPage(browser, ctx) {
|
||||
const context = await browser.newContext({ viewport: VIEWPORT, acceptDownloads: true });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
const pageErrors = capturePageErrors(page);
|
||||
const consoleErrors = [];
|
||||
page.on("console", message => { if (message.type() === "error") consoleErrors.push(message.text().slice(0, 300)); });
|
||||
const downloadsDir = path.join(ctx.output, "downloads");
|
||||
fs.mkdirSync(downloadsDir, { recursive: true });
|
||||
page.on("download", async download => {
|
||||
try { await download.saveAs(path.join(downloadsDir, download.suggestedFilename())); } catch { /* download cancelled */ }
|
||||
});
|
||||
return { context, page, pageErrors, consoleErrors };
|
||||
}
|
||||
|
||||
// Same-origin OPFS wipe between cases; keeps HTTP/WASM caches warm.
|
||||
export async function resetState(page, origin) {
|
||||
await page.goto(`${origin}/index.html`, { waitUntil: "domcontentloaded", timeout: 60000 });
|
||||
await page.evaluate(async () => {
|
||||
const rootDir = await navigator.storage.getDirectory();
|
||||
const names = [];
|
||||
for await (const [name] of rootDir.entries()) names.push(name);
|
||||
for (const name of names) await rootDir.removeEntry(name, { recursive: true }).catch(() => {});
|
||||
});
|
||||
await page.goto("about:blank");
|
||||
}
|
||||
|
||||
export async function openRoute(page, ctx, route, { timeout = 60000, dismissStart = false } = {}) {
|
||||
await page.goto(`${ctx.origin}${route}`, { waitUntil: "domcontentloaded", timeout });
|
||||
await page.waitForFunction(() => document.querySelectorAll("#app button").length > 0, null, { timeout });
|
||||
const isolation = await page.evaluate(() => ({ isolated: self.crossOriginIsolated, sab: typeof SharedArrayBuffer === "function" }));
|
||||
if (!isolation.isolated || !isolation.sab) throw new UiParityPreflightError("host/iframe", "COOP/COEP isolation missing");
|
||||
if (dismissStart) await dismissStartWorkspace(page);
|
||||
return isolation;
|
||||
}
|
||||
|
||||
export async function dismissStartWorkspace(page) {
|
||||
const button = page.getByRole("button", { name: "Dismiss Start", exact: true });
|
||||
if (await button.count()) { try { await button.first().click({ timeout: 3000 }); } catch { /* already gone */ } }
|
||||
await page.waitForTimeout(300);
|
||||
}
|
||||
|
||||
export async function pageState(page) {
|
||||
return page.evaluate(() => ({
|
||||
url: location.href,
|
||||
title: document.title,
|
||||
status: document.querySelector(".desktop-status-bar [role=status]")?.textContent ?? null,
|
||||
tree: [...document.querySelectorAll('[role="treeitem"]')].map(node => node.textContent.trim().slice(0, 60)).slice(0, 20),
|
||||
tabs: [...document.querySelectorAll('.document-tabs [role="tab"]')].map(node => ({ text: node.textContent.trim(), active: node.getAttribute("aria-selected") === "true" })),
|
||||
canvases: [...document.querySelectorAll("canvas")].map(canvas => ({ width: canvas.width, height: canvas.height })),
|
||||
appButtons: document.querySelectorAll("#app button").length,
|
||||
})).catch(error => ({ error: String(error) }));
|
||||
}
|
||||
|
||||
export async function canvasHash(page, selector = "canvas") {
|
||||
const locator = page.locator(selector).first();
|
||||
if ((await locator.count()) === 0) return null;
|
||||
let buffer = null;
|
||||
try {
|
||||
buffer = await locator.screenshot({ timeout: 20000 });
|
||||
} catch {
|
||||
// An element screenshot scrolls the canvas into view; a modal Start dialog
|
||||
// or a tall panel can keep that from ever settling. Clip a viewport shot to
|
||||
// the canvas box instead — the pixels are the same evidence.
|
||||
try {
|
||||
const box = await locator.boundingBox({ timeout: 5000 });
|
||||
if (box && box.width > 0 && box.height > 0) buffer = await page.screenshot({ clip: box, timeout: 20000 });
|
||||
} catch { /* canvas gone or unreachable */ }
|
||||
}
|
||||
if (!buffer) return null;
|
||||
return { selector, bytes: buffer.length, sha256: createHash("sha256").update(buffer).digest("hex") };
|
||||
}
|
||||
|
||||
async function captureFailure(page, caseDir, result, ctx) {
|
||||
const evidence = { at: new Date().toISOString(), ...(await pageState(page)), steps: result.steps };
|
||||
fs.writeFileSync(path.join(caseDir, "failure.json"), `${JSON.stringify(evidence, null, 2)}\n`);
|
||||
try { await page.screenshot({ path: path.join(caseDir, "failure.png"), fullPage: true }); } catch { /* page gone */ }
|
||||
const canvas = await canvasHash(page).catch(() => null);
|
||||
if (canvas && (await page.locator("canvas").count())) {
|
||||
try { await page.locator("canvas").first().screenshot({ path: path.join(caseDir, "failure-canvas.png") }); } catch { /* detached */ }
|
||||
}
|
||||
result.artifacts = { ...result.artifacts, failure: path.relative(ctx.output, path.join(caseDir, "failure.png")), canvas };
|
||||
}
|
||||
|
||||
export async function runCase(page, definition, ctx) {
|
||||
const caseDir = path.join(ctx.output, "cases", definition.id);
|
||||
fs.mkdirSync(caseDir, { recursive: true });
|
||||
const started = Date.now();
|
||||
const result = {
|
||||
id: definition.id, title: definition.title, priority: definition.priority,
|
||||
executor: definition.executor, module: definition.module ?? null, source: definition.source ?? null,
|
||||
status: "running", classification: "none", failureClass: null, steps: [], seconds: 0,
|
||||
error: null, startedAt: new Date().toISOString(), artifacts: {},
|
||||
};
|
||||
ctx.results.push(result);
|
||||
const step = async (name, expected, fn) => {
|
||||
const item = { number: result.steps.length + 1, name, expected, status: "running", startedAt: new Date().toISOString() };
|
||||
result.steps.push(item);
|
||||
persist(ctx);
|
||||
const begin = Date.now();
|
||||
try {
|
||||
item.actual = await fn();
|
||||
item.status = "passed";
|
||||
} catch (error) {
|
||||
item.status = "failed";
|
||||
item.error = String(error?.message ?? error);
|
||||
throw error;
|
||||
} finally {
|
||||
item.seconds = Number(((Date.now() - begin) / 1000).toFixed(3));
|
||||
persist(ctx);
|
||||
}
|
||||
};
|
||||
try {
|
||||
await definition.run({ page, origin: ctx.origin, step, ctx, caseDir, timeoutMs: Math.round((definition.timeoutMs ?? 120000) * ctx.options.timeoutScale) });
|
||||
result.status = "passed";
|
||||
} catch (error) {
|
||||
const verdict = classifyFailure(error);
|
||||
result.status = verdict.status;
|
||||
result.classification = verdict.classification;
|
||||
result.failureClass = verdict.failureClass;
|
||||
result.error = verdict.message;
|
||||
await captureFailure(page, caseDir, result, ctx);
|
||||
ctx.gaps.push({ caseId: result.id, ...verdict, evidence: path.relative(ctx.output, caseDir) });
|
||||
} finally {
|
||||
result.seconds = Number(((Date.now() - started) / 1000).toFixed(3));
|
||||
if (result.status === "passed" && ctx.options.screenshots === "all") {
|
||||
try { await page.screenshot({ path: path.join(caseDir, "pass.png"), fullPage: true }); } catch { /* page gone */ }
|
||||
}
|
||||
fs.writeFileSync(path.join(caseDir, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
|
||||
persist(ctx);
|
||||
}
|
||||
console.log(`${result.id}: ${result.status} (${result.seconds}s)${result.failureClass ? ` [${result.failureClass}]` : ""}`);
|
||||
return result;
|
||||
}
|
||||
314
tools/layout-probe.mjs
Normal file
314
tools/layout-probe.mjs
Normal file
@@ -0,0 +1,314 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Three-column layout / scroll probe for the built FreeCAD Web dist.
|
||||
*
|
||||
* Replaces the throwaway probes written while fixing panel scrolling (plus
|
||||
* module task panels pushing the centre stage out of the viewport). Every
|
||||
* pitfall hit back then is baked in here:
|
||||
* - tools/static-host.mjs is a module, not a CLI: start it via startStaticHost
|
||||
* (a standalone CLI now exists too, but this tool starts its own host);
|
||||
* - playwright resolves only from web/node_modules: require it through
|
||||
* web/package.json, never from /tmp or the repo root;
|
||||
* - the dist root is resolved inside startStaticHost, so relative roots work
|
||||
* (before, they made every request answer 403);
|
||||
* - output is never sliced JSON: the full report goes to --json and the
|
||||
* console gets a bounded summary.
|
||||
*
|
||||
* Per page it measures:
|
||||
* - page scroll: a height-locked page (html/body overflow hidden) must not
|
||||
* scroll as a document;
|
||||
* - side panels: every aside inside the layout stays inside the viewport and
|
||||
* owns a .pane-scroll that actually scrolls (a spacer is injected first by
|
||||
* default so sparse pages are measurable);
|
||||
* - stage stability: injecting panel content and scrolling the panels must
|
||||
* not move the centre stage (<=1px drift in x/y/width/height). This is the
|
||||
* exact regression class: a tall Robot/Mesh task panel pushed .layout down
|
||||
* or collapsed it to a few pixels.
|
||||
*
|
||||
* Checks fail the run (exit 1) unless --no-assert; a missing Chrome or dist
|
||||
* exits 2. Pages with no asides (Start, standalone tools) report the panel
|
||||
* checks as skipped (null) rather than failing.
|
||||
*
|
||||
* Usage
|
||||
* node tools/layout-probe.mjs
|
||||
* node tools/layout-probe.mjs --url '/workbench.html?module=Robot' --url /partdesign.html
|
||||
* node tools/layout-probe.mjs --headed --pause # manual scroll inspection
|
||||
* node tools/layout-probe.mjs --json /tmp/layout.json --screenshot '/tmp/{page}.png'
|
||||
* node tools/layout-probe.mjs --origin http://127.0.0.1:46059 # reuse a host
|
||||
*
|
||||
* Options
|
||||
* --url <path> repeatable page path (default: /project.html,
|
||||
* /partdesign.html, /workbench.html?module=Part|Robot|Mesh)
|
||||
* --root <dir> dist root to serve (default <repo>/web/dist)
|
||||
* --origin <url> probe an already running host instead of starting one
|
||||
* --wait-for <sel> ready selector (default: .layout, .design-layout or .pane-scroll)
|
||||
* --wait-ms <n> settle time after ready (default 1500)
|
||||
* --viewport <WxH> default 1440x1000
|
||||
* --headed show the browser (needs DISPLAY); --slow <ms> adds slowMo
|
||||
* --pause keep each headed page open until Enter (implies --headed)
|
||||
* --inject <px> spacer height used to test pane scrolling (default 2000, 0 disables)
|
||||
* --scroll-test <px> how far each pane is scrolled (default 400)
|
||||
* --screenshot <path> per-page PNG; "{page}" is replaced by a url slug
|
||||
* --json <path> write the full report here
|
||||
* --no-assert always exit 0
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { findChrome, startStaticHost } from "./static-host.mjs";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const require = createRequire(path.join(root, "web", "package.json"));
|
||||
const { chromium } = require("playwright");
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const option = (name, fallback) => { const i = argv.indexOf(name); return i >= 0 && i + 1 < argv.length ? argv[i + 1] : fallback; };
|
||||
const flag = (name) => argv.includes(name);
|
||||
|
||||
const urls = [];
|
||||
for (let i = 0; i < argv.length; i += 1) if (argv[i] === "--url" && i + 1 < argv.length) urls.push(argv[i + 1]);
|
||||
const DEFAULT_URLS = [
|
||||
"/project.html",
|
||||
"/partdesign.html",
|
||||
"/workbench.html?module=Part",
|
||||
"/workbench.html?module=Robot",
|
||||
"/workbench.html?module=Mesh",
|
||||
];
|
||||
const pages = urls.length ? urls : DEFAULT_URLS;
|
||||
const distRoot = path.resolve(option("--root", path.join(root, "web", "dist")));
|
||||
const externalOrigin = option("--origin", null);
|
||||
const waitFor = option("--wait-for", ".layout, .design-layout, .pane-scroll");
|
||||
const waitMs = Number(option("--wait-ms", "1500"));
|
||||
const [viewportW, viewportH] = option("--viewport", "1440x1000").split("x").map(Number);
|
||||
const headed = flag("--headed") || flag("--pause");
|
||||
const slowMo = Number(option("--slow", "0"));
|
||||
const injectPx = Number(option("--inject", "2000"));
|
||||
const scrollPx = Number(option("--scroll-test", "400"));
|
||||
const jsonPath = option("--json", null);
|
||||
const shotPath = option("--screenshot", null);
|
||||
const assertOn = !flag("--no-assert");
|
||||
|
||||
const slug = (url) => url.replace(/^\//, "").replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "index";
|
||||
const near = (a, b, tol = 1) => Math.abs(a - b) <= tol;
|
||||
|
||||
const executablePath = findChrome();
|
||||
if (!executablePath) { console.error("precondition: Google Chrome not found (set FREECAD_CHROME)"); process.exit(2); }
|
||||
if (!fs.existsSync(path.join(distRoot, "index.html")) && !fs.existsSync(path.join(distRoot, "project.html"))) {
|
||||
console.error(`precondition: ${distRoot} is missing a built dist; run npx vite build in web/`);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
let host = null;
|
||||
const origin = externalOrigin ?? (host = await startStaticHost(distRoot)).origin;
|
||||
const browser = await chromium.launch({
|
||||
executablePath,
|
||||
headless: !headed,
|
||||
slowMo: slowMo > 0 ? slowMo : undefined,
|
||||
args: ["--no-sandbox", "--disable-dev-shm-usage", "--use-angle=swiftshader", "--enable-unsafe-swiftshader"],
|
||||
});
|
||||
|
||||
const report = { origin, startedAt: new Date().toISOString(), viewport: { width: viewportW, height: viewportH }, injectPx, scrollPx, pages: [] };
|
||||
|
||||
async function probe(url) {
|
||||
const page = await browser.newPage({ viewport: { width: viewportW, height: viewportH } });
|
||||
const pageErrors = [];
|
||||
page.on("pageerror", (error) => { if (pageErrors.length < 20) pageErrors.push(String(error).slice(0, 300)); });
|
||||
|
||||
let ready = true;
|
||||
try {
|
||||
await page.goto(`${origin}${url}`, { waitUntil: "load", timeout: 60000 });
|
||||
await page.waitForSelector(waitFor, { timeout: 45000 });
|
||||
} catch {
|
||||
ready = false;
|
||||
}
|
||||
if (ready && waitMs > 0) await page.waitForTimeout(waitMs);
|
||||
|
||||
const diag = await page.evaluate(({ inject, scroll }) => {
|
||||
const round = (value) => Math.round(value * 10) / 10;
|
||||
const rect = (element) => {
|
||||
const r = element.getBoundingClientRect();
|
||||
return { x: round(r.x), y: round(r.y), w: round(r.width), h: round(r.height), right: round(r.right), bottom: round(r.bottom) };
|
||||
};
|
||||
const describe = (element) => ({ tag: element.tagName.toLowerCase(), cls: String(element.className || "").slice(0, 120), rect: rect(element) });
|
||||
|
||||
const scrolling = document.scrollingElement || document.documentElement;
|
||||
const htmlStyle = getComputedStyle(document.documentElement);
|
||||
const bodyStyle = getComputedStyle(document.body);
|
||||
const locked = htmlStyle.overflowY === "hidden" || bodyStyle.overflowY === "hidden";
|
||||
|
||||
const layout = document.querySelector(".layout, .design-layout");
|
||||
const stage = document.querySelector(".layout > main, .design-layout > main, .stage");
|
||||
const asideElements = [...new Set(document.querySelectorAll(".layout > aside, .design-layout > aside, [data-dock-side], .tree-pane, .property-pane"))];
|
||||
const asideRecords = asideElements.map((aside) => {
|
||||
const paneElements = [...aside.querySelectorAll(".pane-scroll")];
|
||||
const containers = paneElements.length
|
||||
? paneElements
|
||||
: (getComputedStyle(aside).overflowY !== "visible" ? [aside] : []);
|
||||
return {
|
||||
desc: describe(aside),
|
||||
side: aside.dataset.dockSide ?? null,
|
||||
panel: aside.dataset.dockPanel ?? null,
|
||||
source: paneElements.length ? "pane-scroll" : "aside",
|
||||
panes: containers.map((pane) => ({ element: pane, overflowY: getComputedStyle(pane).overflowY, rect: rect(pane) })),
|
||||
};
|
||||
});
|
||||
|
||||
const stageBeforeInject = stage ? rect(stage) : null;
|
||||
const spacers = [];
|
||||
if (inject > 0) {
|
||||
for (const aside of asideRecords) for (const pane of aside.panes) {
|
||||
const spacer = document.createElement("div");
|
||||
spacer.dataset.layoutProbeSpacer = "1";
|
||||
spacer.style.cssText = `height:${inject}px;flex:0 0 auto;`;
|
||||
pane.element.appendChild(spacer);
|
||||
spacers.push(spacer);
|
||||
}
|
||||
void document.body.offsetHeight; // reflow before measuring
|
||||
}
|
||||
const stageAfterInject = stage ? rect(stage) : null;
|
||||
const scrollBefore = window.scrollY;
|
||||
|
||||
for (const aside of asideRecords) for (const pane of aside.panes) pane.element.scrollTop = scroll;
|
||||
const stageAfterScroll = stage ? rect(stage) : null;
|
||||
const scrollAfter = window.scrollY;
|
||||
const scrollTops = asideRecords.map((aside) => aside.panes.map((pane) => Math.round(pane.element.scrollTop)));
|
||||
|
||||
const asides = asideRecords.map((aside) => ({
|
||||
...aside.desc,
|
||||
side: aside.side,
|
||||
panel: aside.panel,
|
||||
source: aside.source,
|
||||
panes: aside.panes.map((pane) => ({
|
||||
overflowY: pane.overflowY,
|
||||
rect: pane.rect,
|
||||
clientH: pane.element.clientHeight,
|
||||
scrollH: pane.element.scrollHeight,
|
||||
scrollable: pane.element.scrollHeight > pane.element.clientHeight + 1,
|
||||
})),
|
||||
}));
|
||||
|
||||
for (const spacer of spacers) spacer.remove();
|
||||
for (const aside of asideRecords) for (const pane of aside.panes) pane.element.scrollTop = 0;
|
||||
|
||||
const shift = (from, to) => (from && to ? { dx: round(to.x - from.x), dy: round(to.y - from.y), dw: round(to.w - from.w), dh: round(to.h - from.h) } : null);
|
||||
return {
|
||||
htmlClass: document.documentElement.className,
|
||||
locked,
|
||||
viewport: { width: window.innerWidth, height: window.innerHeight },
|
||||
body: rect(document.body),
|
||||
doc: { clientH: scrolling.clientHeight, scrollH: scrolling.scrollHeight },
|
||||
scrollY: { before: scrollBefore, after: scrollAfter },
|
||||
layout: layout ? describe(layout) : null,
|
||||
stage: stageAfterInject,
|
||||
injectShift: shift(stageBeforeInject, stageAfterInject),
|
||||
scrollShift: shift(stageAfterInject, stageAfterScroll),
|
||||
scrollTops,
|
||||
asides,
|
||||
};
|
||||
}, { inject: injectPx, scroll: scrollPx });
|
||||
|
||||
if (shotPath) {
|
||||
const target = shotPath.includes("{page}") ? shotPath.replaceAll("{page}", slug(url)) : path.join(shotPath, `${slug(url)}.png`);
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
await page.screenshot({ path: target, fullPage: false });
|
||||
}
|
||||
|
||||
const checks = [];
|
||||
checks.push({ name: "ready", ok: ready, detail: ready ? undefined : `selector ${JSON.stringify(waitFor)} never appeared` });
|
||||
if (diag.locked) {
|
||||
const fits = diag.doc.scrollH <= diag.viewport.height + 1;
|
||||
checks.push({
|
||||
name: "page-scroll",
|
||||
ok: fits && diag.scrollY.after === 0,
|
||||
detail: `doc ${diag.doc.scrollH}px vs viewport ${diag.viewport.height}px; scrollY ${diag.scrollY.before}->${diag.scrollY.after}`,
|
||||
});
|
||||
} else {
|
||||
checks.push({ name: "page-scroll", ok: null, detail: "page is not height-locked (reference only)" });
|
||||
}
|
||||
if (diag.asides.length === 0) {
|
||||
checks.push({ name: "aside-bounds", ok: null, detail: "no side panels on this page" });
|
||||
checks.push({ name: "aside-scrolls", ok: null, detail: "no side panels on this page" });
|
||||
} else {
|
||||
const outside = diag.asides.filter((aside) => aside.rect.y < -1 || aside.rect.bottom > diag.viewport.height + 1);
|
||||
checks.push({
|
||||
name: "aside-bounds",
|
||||
ok: outside.length === 0,
|
||||
detail: outside.length ? outside.map((aside) => `${aside.side ?? aside.cls}: y=${aside.rect.y} bottom=${aside.rect.bottom}`).join("; ") : undefined,
|
||||
});
|
||||
const unscrollable = diag.asides.filter((aside) => !aside.panes.some((pane) => pane.scrollable && /auto|scroll/.test(pane.overflowY)));
|
||||
checks.push({
|
||||
name: "aside-scrolls",
|
||||
ok: unscrollable.length === 0,
|
||||
detail: unscrollable.length
|
||||
? unscrollable.map((aside) => {
|
||||
const pane = aside.panes[0];
|
||||
return `${aside.side ?? aside.cls}: ${pane ? `overflowY=${pane.overflowY} ${pane.scrollH}/${pane.clientH}` : "no .pane-scroll"}`;
|
||||
}).join("; ")
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
const stable = (m) => !m || (near(m.dx, 0) && near(m.dy, 0) && near(m.dw, 0) && near(m.dh, 0));
|
||||
checks.push({
|
||||
name: "stage-stable",
|
||||
ok: diag.stage ? stable(diag.injectShift) && stable(diag.scrollShift) : null,
|
||||
detail: diag.stage
|
||||
? `inject ${JSON.stringify(diag.injectShift)} scroll ${JSON.stringify(diag.scrollShift)}`
|
||||
: "no centre stage on this page",
|
||||
});
|
||||
|
||||
await page.close();
|
||||
const ok = ready && checks.every((check) => check.ok !== false);
|
||||
return {
|
||||
url,
|
||||
ok,
|
||||
checks,
|
||||
pageErrors,
|
||||
htmlClass: diag.htmlClass,
|
||||
locked: diag.locked,
|
||||
doc: diag.doc,
|
||||
layout: diag.layout,
|
||||
stage: diag.stage,
|
||||
asides: diag.asides.map(({ panes, ...aside }) => ({ ...aside, panes: panes.length, scrollable: panes.some((pane) => pane.scrollable), firstPane: panes[0] ?? null })),
|
||||
scrollTops: diag.scrollTops,
|
||||
};
|
||||
}
|
||||
|
||||
let failures = 0;
|
||||
for (const url of pages) {
|
||||
let result;
|
||||
try {
|
||||
result = await probe(url);
|
||||
} catch (error) {
|
||||
result = { url, ok: false, checks: [{ name: "probe", ok: false, detail: String(error).slice(0, 400) }], pageErrors: [] };
|
||||
}
|
||||
if (!result.ok) failures += 1;
|
||||
report.pages.push(result);
|
||||
const summary = {
|
||||
url: result.url,
|
||||
ok: result.ok,
|
||||
checks: Object.fromEntries(result.checks.map((check) => [check.name, check.ok === null ? "skip" : check.ok])),
|
||||
layout: result.layout?.rect ?? null,
|
||||
stage: result.stage ?? null,
|
||||
asides: result.asides?.map((aside) => ({ side: aside.side, panel: aside.panel, rect: aside.rect, scrollable: aside.scrollable })),
|
||||
problems: result.checks.filter((check) => check.ok === false).map((check) => `${check.name}: ${check.detail}`),
|
||||
pageErrors: result.pageErrors,
|
||||
};
|
||||
console.log(JSON.stringify(summary));
|
||||
if (flag("--pause")) {
|
||||
await new Promise((resolve) => {
|
||||
process.stdout.write(`[${url}] inspect the page, then press Enter to continue... `);
|
||||
process.stdin.once("data", resolve);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
if (host) host.close();
|
||||
if (jsonPath) {
|
||||
fs.mkdirSync(path.dirname(path.resolve(jsonPath)), { recursive: true });
|
||||
fs.writeFileSync(path.resolve(jsonPath), `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(`report=${path.resolve(jsonPath)}`);
|
||||
}
|
||||
console.log(`pages=${pages.length} failures=${failures}`);
|
||||
process.exit(assertOn && failures > 0 ? 1 : 0);
|
||||
@@ -1,7 +1,15 @@
|
||||
/** Shared static host + Chrome discovery for browser runners and the MCP session. */
|
||||
/**
|
||||
* Shared static host + Chrome discovery for browser runners and the MCP session.
|
||||
*
|
||||
* CLI (for probes and for web/tools/manual/capture.mjs --origin):
|
||||
* node tools/static-host.mjs [--root <dist>] [--port <n>] [--document <file>]
|
||||
* Prints ORIGIN=http://127.0.0.1:<port> and stays up until killed. --root may
|
||||
* be relative (to the current directory) or absolute; it is resolved here.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export const CHROME_CANDIDATES = ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/opt/google/chrome/google-chrome"];
|
||||
|
||||
@@ -16,24 +24,53 @@ export const ISOLATION_HEADERS = {
|
||||
"cross-origin-embedder-policy": "require-corp",
|
||||
};
|
||||
|
||||
const CONTENT_TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css", ".json": "application/json", ".wasm": "application/wasm", ".png": "image/png" };
|
||||
// Chrome refuses to render <img src="*.svg"> when the response is octet-stream,
|
||||
// so every type the shell actually loads has to be listed explicitly.
|
||||
const CONTENT_TYPES = {
|
||||
".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8", ".json": "application/json", ".wasm": "application/wasm",
|
||||
".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
|
||||
".webp": "image/webp", ".ico": "image/x-icon", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf",
|
||||
".txt": "text/plain; charset=utf-8", ".map": "application/json", ".md": "text/markdown; charset=utf-8",
|
||||
};
|
||||
|
||||
/**
|
||||
* Serve a built dist directory on an ephemeral loopback port with COOP/COEP.
|
||||
* Returns { server, origin, close }.
|
||||
*/
|
||||
export async function startStaticHost(distRoot, defaultDocument = "index.html") {
|
||||
if (!fs.existsSync(path.join(distRoot, defaultDocument))) throw new Error(`web/dist/${defaultDocument} is missing; run npm run build first`);
|
||||
export async function startStaticHost(distRoot, defaultDocument = "index.html", port = 0) {
|
||||
// Resolve once: with a relative root the traversal guard below compared an
|
||||
// absolute file path against a relative prefix and answered 403 for every
|
||||
// request.
|
||||
const resolvedRoot = path.resolve(distRoot);
|
||||
if (!fs.existsSync(path.join(resolvedRoot, defaultDocument))) throw new Error(`${resolvedRoot}/${defaultDocument} is missing; run npm run build first`);
|
||||
const server = http.createServer((request, response) => {
|
||||
const requestPath = decodeURIComponent(new URL(request.url ?? "/", "http://127.0.0.1").pathname);
|
||||
if (requestPath === "/favicon.ico") { response.writeHead(204, ISOLATION_HEADERS); response.end(); return; }
|
||||
const relative = requestPath === "/" ? defaultDocument : requestPath.replace(/^\/+/, "");
|
||||
const filePath = path.resolve(distRoot, relative);
|
||||
if (filePath !== distRoot && !filePath.startsWith(`${distRoot}${path.sep}`)) { response.writeHead(403); response.end("forbidden"); return; }
|
||||
const filePath = path.resolve(resolvedRoot, relative);
|
||||
if (filePath !== resolvedRoot && !filePath.startsWith(`${resolvedRoot}${path.sep}`)) { response.writeHead(403); response.end("forbidden"); return; }
|
||||
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) { response.writeHead(404); response.end("not found"); return; }
|
||||
response.writeHead(200, { "content-type": CONTENT_TYPES[path.extname(filePath)] ?? "application/octet-stream", "cache-control": "no-store", ...ISOLATION_HEADERS });
|
||||
fs.createReadStream(filePath).pipe(response);
|
||||
});
|
||||
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); });
|
||||
return { server, origin: `http://127.0.0.1:${server.address().port}`, close: () => server.close() };
|
||||
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(port, "127.0.0.1", resolve); });
|
||||
return { server, origin: `http://127.0.0.1:${server.address().port}`, root: resolvedRoot, close: () => server.close() };
|
||||
}
|
||||
|
||||
/* --- CLI ---------------------------------------------------------------- */
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const argv = process.argv.slice(2);
|
||||
const option = (name, fallback) => { const i = argv.indexOf(name); return i >= 0 && i + 1 < argv.length ? argv[i + 1] : fallback; };
|
||||
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const distRoot = option("--root", path.join(repoRoot, "web", "dist"));
|
||||
const document = option("--document", "index.html");
|
||||
const port = Number(option("--port", "0"));
|
||||
const host = await startStaticHost(distRoot, document, port);
|
||||
console.log(`ORIGIN=${host.origin}`);
|
||||
console.log(`ROOT=${host.root}`);
|
||||
console.log(`DOCUMENT=${document}`);
|
||||
const stop = () => { host.close(); process.exit(0); };
|
||||
process.on("SIGINT", stop);
|
||||
process.on("SIGTERM", stop);
|
||||
}
|
||||
|
||||
98
tools/web-freecad-functional-suite.mjs
Normal file
98
tools/web-freecad-functional-suite.mjs
Normal file
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env node
|
||||
// Headed Web FreeCAD functional suite.
|
||||
// node tools/web-freecad-functional-suite.mjs --priority P0
|
||||
// See tools/functional-suite/cli.mjs for the full option contract.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { parseArgs, selectCases, USAGE } from "./functional-suite/cli.mjs";
|
||||
import { allCases } from "./functional-suite/cases/index.mjs";
|
||||
import { createRunContext, finalize, newRunDir, persist, pruneRuns, writeManifest } from "./functional-suite/report.mjs";
|
||||
import { openBrowser, openPage, resetState, root, runCase, startHost } from "./functional-suite/runtime.mjs";
|
||||
import { runLegacyCases } from "./functional-suite/executors/legacy.mjs";
|
||||
|
||||
const options = parseArgs();
|
||||
if (options.help) { console.log(USAGE); process.exit(0); }
|
||||
|
||||
const selected = selectCases(allCases(), options);
|
||||
if (!selected.length) { console.error("no cases selected"); process.exit(2); }
|
||||
|
||||
const base = options.out ? path.resolve(options.out) : path.join(root, "docs", "current", "web-functional-suite");
|
||||
const output = newRunDir(base, options.resume);
|
||||
|
||||
let previous = [];
|
||||
if (options.resume) {
|
||||
const resultsFile = path.join(output, "results.json");
|
||||
if (fs.existsSync(resultsFile)) {
|
||||
const payload = JSON.parse(fs.readFileSync(resultsFile, "utf8"));
|
||||
previous = (payload.results ?? []).filter(item => item.status !== "running");
|
||||
}
|
||||
}
|
||||
const completed = new Map(previous.map(item => [item.id, item]));
|
||||
|
||||
let host;
|
||||
let browser;
|
||||
let session;
|
||||
const ctx = createRunContext({ options, root, output, origin: "" });
|
||||
|
||||
const shutdown = async () => {
|
||||
try { await session?.context.close(); } catch { /* already closed */ }
|
||||
try { await browser?.close(); } catch { /* already closed */ }
|
||||
try { host?.close(); } catch { /* already closed */ }
|
||||
};
|
||||
|
||||
try {
|
||||
host = await startHost();
|
||||
ctx.origin = host.origin;
|
||||
browser = await openBrowser(options);
|
||||
session = await openPage(browser, ctx);
|
||||
ctx.session = session;
|
||||
writeManifest(ctx, {
|
||||
chrome: browser.version(),
|
||||
cases: selected.map(item => ({ id: item.id, priority: item.priority, executor: item.executor })),
|
||||
disk: { dist: path.relative(root, path.join(root, "web", "dist")) },
|
||||
});
|
||||
|
||||
for (const definition of selected) {
|
||||
const prior = completed.get(definition.id);
|
||||
if (prior && !options.force) {
|
||||
ctx.results.push(prior);
|
||||
persist(ctx);
|
||||
console.log(`${definition.id}: skipped (resume, ${prior.status})`);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await resetState(session.page, ctx.origin);
|
||||
// Errors are a per-case assertion, so previous cases must not leak in.
|
||||
session.pageErrors.length = 0;
|
||||
session.consoleErrors.length = 0;
|
||||
} catch (error) {
|
||||
// A broken page cannot host the next case; surface it on the case record.
|
||||
const failed = { id: definition.id, title: definition.title, priority: definition.priority, executor: definition.executor, status: "blocked", classification: "precondition", failureClass: "fixture", steps: [], seconds: 0, error: `resetState failed: ${String(error?.message ?? error)}`, startedAt: new Date().toISOString(), artifacts: {} };
|
||||
ctx.results.push(failed);
|
||||
ctx.gaps.push({ caseId: definition.id, status: "blocked", classification: "precondition", failureClass: "fixture", message: failed.error, evidence: "" });
|
||||
persist(ctx);
|
||||
console.log(`${definition.id}: blocked (resetState failed)`);
|
||||
continue;
|
||||
}
|
||||
await runCase(session.page, definition, ctx);
|
||||
}
|
||||
|
||||
if (options.legacyIds.length) {
|
||||
const results = await runLegacyCases(options, ctx, { base });
|
||||
console.log(`legacy: ${results.length} case(s) imported`);
|
||||
}
|
||||
|
||||
finalize(ctx);
|
||||
if (options.prune) pruneRuns(base, options.prune);
|
||||
} catch (error) {
|
||||
fs.mkdirSync(output, { recursive: true });
|
||||
fs.writeFileSync(path.join(output, "fatal.json"), `${JSON.stringify({ at: new Date().toISOString(), error: String(error?.stack ?? error) }, null, 2)}\n`);
|
||||
console.error(`fatal: ${String(error?.message ?? error)}`);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await shutdown();
|
||||
}
|
||||
|
||||
const counts = ctx.counts;
|
||||
console.log(JSON.stringify({ output, counts, gaps: ctx.gaps.length }));
|
||||
if (counts.failed > 0 || counts.running > 0) process.exitCode = 1;
|
||||
@@ -14,7 +14,7 @@
|
||||
},
|
||||
{
|
||||
"type": "seed",
|
||||
"file": "/home/mes123456/FreeCADWasmDev/working/FreeCAD/web/tools/line-course/checkpoints/E03.FCStd",
|
||||
"file": "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/tools/line-course/checkpoints/E03.FCStd",
|
||||
"name": "manual-assembly-source.FCStd"
|
||||
},
|
||||
{
|
||||
|
||||
153
web/src/document-tree.tsx
Normal file
153
web/src/document-tree.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Tree, type NodeApi, type NodeRendererProps, type RowRendererProps } from "react-arborist";
|
||||
|
||||
// Desktop FreeCAD's TreeWidget is a three-column QTreeWidget
|
||||
// (src/Gui/Tree.cpp: `headerItem()->setText(0, "Labels & Attributes")`,
|
||||
// "Description", "Internal name") whose first column carries a visibility
|
||||
// icon (TreeParams::getVisibilityIcon default true) preceded by the object
|
||||
// icon, with error / touched / external overlays composited on top. This
|
||||
// component reproduces that row model so every workbench can share one tree
|
||||
// instead of its own ad-hoc list.
|
||||
|
||||
export interface DocumentTreeNode {
|
||||
id: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
internalName: string;
|
||||
type: string;
|
||||
icon?: string;
|
||||
visible?: boolean;
|
||||
toggleable?: boolean;
|
||||
error?: boolean;
|
||||
touched?: boolean;
|
||||
external?: boolean;
|
||||
children?: DocumentTreeNode[];
|
||||
}
|
||||
|
||||
const ROW_HEIGHT = 24;
|
||||
|
||||
function Row(
|
||||
{ node, data, onSelectObject, onToggleVisibility, busy }: {
|
||||
node: NodeApi<DocumentTreeNode>;
|
||||
data: DocumentTreeNode;
|
||||
onSelectObject: (id: string) => void;
|
||||
onToggleVisibility?: (id: string, visible: boolean) => void;
|
||||
busy: boolean;
|
||||
},
|
||||
) {
|
||||
const arrow = node.isLeaf ? null : (
|
||||
<button type="button" className="fc-tree-arrow" aria-label={node.isOpen ? "Collapse" : "Expand"}
|
||||
onClick={event => { event.stopPropagation(); node.isOpen ? node.close() : node.open(); }}>
|
||||
{node.isOpen ? "▾" : "▸"}
|
||||
</button>
|
||||
);
|
||||
return <>
|
||||
{arrow}
|
||||
<div className="fc-tree-col fc-tree-col-label">
|
||||
{data.toggleable !== false
|
||||
? <input type="checkbox" className="fc-tree-visibility" aria-label={`Visible ${data.label}`}
|
||||
checked={data.visible !== false} disabled={busy}
|
||||
onClick={event => event.stopPropagation()}
|
||||
onChange={event => onToggleVisibility?.(data.id, event.target.checked)} />
|
||||
: <span className="fc-tree-visibility-spacer" aria-hidden="true" />}
|
||||
{data.icon
|
||||
? <img className="fc-tree-icon" src={data.icon} alt="" aria-hidden="true" />
|
||||
: <span className="fc-tree-icon" aria-hidden="true" />}
|
||||
{data.error ? <img className="fc-tree-overlay" src="/icons/tree/overlay_error.svg" alt="" aria-hidden="true" />
|
||||
: data.touched ? <img className="fc-tree-overlay" src="/icons/tree/overlay_recompute.svg" alt="" aria-hidden="true" /> : null}
|
||||
<span className="fc-tree-text">{data.label}</span>
|
||||
{data.external ? <img className="fc-tree-overlay" src="/icons/tree/LinkOverlay.svg" alt="" aria-hidden="true" /> : null}
|
||||
</div>
|
||||
<div className="fc-tree-col fc-tree-col-description">{data.description ?? ""}</div>
|
||||
<div className="fc-tree-col fc-tree-col-internal">{data.internalName}</div>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function DocumentTree({ nodes, selected, onSelect, onToggleVisibility, busy = false, label }: {
|
||||
nodes: DocumentTreeNode[];
|
||||
selected: string;
|
||||
onSelect: (id: string) => void;
|
||||
onToggleVisibility?: (id: string, visible: boolean) => void;
|
||||
busy?: boolean;
|
||||
label: string;
|
||||
}) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const [width, setWidth] = useState(240);
|
||||
useEffect(() => {
|
||||
const element = host.current;
|
||||
if (!element) return;
|
||||
const measure = () => setWidth(Math.max(120, element.clientWidth));
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(element);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const flat = useMemo(() => {
|
||||
let count = 0;
|
||||
const walk = (rows: DocumentTreeNode[]) => { for (const row of rows) { count++; if (row.children?.length) walk(row.children); } };
|
||||
walk(nodes);
|
||||
return count;
|
||||
}, [nodes]);
|
||||
|
||||
// react-window virtualizes by a fixed pixel height. The tree pane scrolls as a
|
||||
// whole, so the viewport is sized to the content and every row stays mounted;
|
||||
// otherwise row counts and off-screen selections would differ from desktop.
|
||||
const height = Math.max(ROW_HEIGHT * Math.max(flat, 1) + 2, 40);
|
||||
|
||||
// react-arborist treats `renderRow` / `children` as component types. A new
|
||||
// function identity on every render therefore remounts every row, which drops
|
||||
// DOM focus to <body> while the tree still believes that row is focused; the
|
||||
// next re-render (e.g. a debounced property commit) then pulls focus into the
|
||||
// row and steals it from the field being typed in. Keep both renderers stable
|
||||
// and route the live callbacks through a ref instead of new closures.
|
||||
const callbacks = useRef({ onSelect, onToggleVisibility, busy });
|
||||
callbacks.current = { onSelect, onToggleVisibility, busy };
|
||||
const renderRow = useCallback(({ node, attrs, innerRef, children }: RowRendererProps<DocumentTreeNode>) => (
|
||||
<div {...attrs} ref={innerRef} role="treeitem" aria-selected={node.isSelected ? "true" : "false"} data-design-object={node.data.id} onClick={event => { node.handleClick(event); }}>
|
||||
{children}
|
||||
</div>
|
||||
), []);
|
||||
const renderNode = useCallback(({ node }: NodeRendererProps<DocumentTreeNode>) => (
|
||||
<Row node={node} data={node.data} onSelectObject={id => callbacks.current.onSelect(id)}
|
||||
onToggleVisibility={(id, visible) => callbacks.current.onToggleVisibility?.(id, visible)} busy={callbacks.current.busy} />
|
||||
), []);
|
||||
|
||||
return <div ref={host} className="fc-tree" data-tree-rows={flat}>
|
||||
<style>{`.fc-tree{width:100%}.fc-tree-header,.fc-tree [role=treeitem]{display:grid;grid-template-columns:minmax(0,1.6fr) minmax(0,1fr) minmax(0,1fr);align-items:center;box-sizing:border-box;font-size:12px;line-height:${ROW_HEIGHT}px}
|
||||
.fc-tree-header{height:${ROW_HEIGHT}px;padding:0 4px;border-bottom:1px solid #3c4246;color:#a4b2b9;font-weight:600}
|
||||
.fc-tree [role=treeitem]{padding:0 4px;border-left:3px solid transparent;cursor:pointer;color:#fff;white-space:nowrap}
|
||||
.fc-tree [role=treeitem]:hover{background:#3a4348}
|
||||
.fc-tree [role=treeitem][aria-selected=true]{background:#29444b;border-left-color:#8ed4dc}
|
||||
.fc-tree-col{display:flex;align-items:center;gap:5px;min-width:0;overflow:hidden;padding-right:6px}
|
||||
.fc-tree-col-description,.fc-tree-col-internal{color:#9fb0ba}
|
||||
.fc-tree-text{overflow:hidden;text-overflow:ellipsis}
|
||||
.fc-tree-icon{width:16px;height:16px;flex:none;object-fit:contain}
|
||||
.fc-tree-overlay{width:10px;height:10px;flex:none}
|
||||
.fc-tree-visibility{margin:0;width:13px;height:13px;flex:none;accent-color:#8ed4dc}
|
||||
.fc-tree-visibility-spacer{display:inline-block;width:13px;flex:none}
|
||||
.fc-tree-arrow{all:unset;cursor:pointer;width:12px;position:absolute;transform:translateX(-12px);color:#b1b9bf}
|
||||
.fc-tree [role=treeitem]{position:relative}`}</style>
|
||||
<div className="fc-tree-header" role="row">
|
||||
<div>Labels & Attributes</div><div>Description</div><div>Internal name</div>
|
||||
</div>
|
||||
<Tree<DocumentTreeNode>
|
||||
data={nodes}
|
||||
aria-label={label}
|
||||
width={width}
|
||||
height={height}
|
||||
rowHeight={ROW_HEIGHT}
|
||||
indent={14}
|
||||
openByDefault
|
||||
disableDrag
|
||||
disableDrop
|
||||
disableEdit
|
||||
selection={selected || undefined}
|
||||
onSelect={rows => { const first = rows[0]; if (first) onSelect(first.id); }}
|
||||
onActivate={node => onSelect(node.id)}
|
||||
renderRow={renderRow}
|
||||
>
|
||||
{renderNode}
|
||||
</Tree>
|
||||
</div>;
|
||||
}
|
||||
30
web/src/export-service.ts
Normal file
30
web/src/export-service.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { downloadBytes, type AppServiceResult } from "./app-services.js";
|
||||
import { readExportFile, writeExportFile } from "./storage.js";
|
||||
import { ProjectSessionStore } from "./project-session.js";
|
||||
|
||||
const EXTENSIONS = new Set([".csg", ".scad", ".fcstd", ".step", ".stp", ".brep", ".brp", ".iges", ".igs", ".stl", ".gltf", ".glb", ".obj", ".ply", ".svg", ".dxf", ".csv"]);
|
||||
|
||||
export interface NativeByteResult { module: string; format: string; fileName: string; bytes: ArrayBuffer; }
|
||||
|
||||
function extension(fileName: string): string { const index = fileName.lastIndexOf("."); return index >= 0 ? fileName.slice(index).toLowerCase() : ""; }
|
||||
|
||||
export class ExportService {
|
||||
constructor(private readonly project?: ProjectSessionStore) {}
|
||||
|
||||
async downloadToLocal(fileName: string, mime = "application/octet-stream"): Promise<AppServiceResult<{ fileName: string; bytes: number }>> {
|
||||
const bytes = await readExportFile(fileName);
|
||||
return downloadBytes(fileName, bytes, mime);
|
||||
}
|
||||
|
||||
download(native: Partial<NativeByteResult>): AppServiceResult<{ fileName: string; bytes: number }> {
|
||||
const fileName = native.fileName ?? "FreeCAD-export";
|
||||
const bytes = native.bytes;
|
||||
const ext = extension(fileName);
|
||||
if (!bytes || !(bytes instanceof ArrayBuffer)) return { schema: "freecad-web-app-service-result/v1", service: "file.download", status: "error", error: { code: "native_bytes_unavailable", message: "Native Worker response did not include export bytes" } };
|
||||
if (!EXTENSIONS.has(ext)) return { schema: "freecad-web-app-service-result/v1", service: "file.download", status: "error", error: { code: "unsupported_extension", message: `Unsupported CAD export extension ${ext || "(none)"}` } };
|
||||
// Web FreeCAD works entirely inside OPFS; downloadBytes runs only through
|
||||
// download() below, which the UI calls when the user explicitly asks.
|
||||
void writeExportFile(fileName, bytes).then(() => this.project?.touchFile({ path: fileName, module: native.module ?? "", format: native.format ?? ext, updatedAt: new Date().toISOString() }));
|
||||
return { schema: "freecad-web-app-service-result/v1", service: "file.download", status: "ok", value: { fileName, bytes: bytes.byteLength } };
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,10 @@ export class ImportRenderBridge {
|
||||
private gizmoMeshId: string | null = null;
|
||||
private gizmoTargetBase: THREE.Matrix4 | null = null;
|
||||
private gizmoHandleBase: THREE.Matrix4 | null = null;
|
||||
// Placement editors preview a not-yet-committed transform by writing only the
|
||||
// mesh matrix. The base matrix is captured on the first preview call so the
|
||||
// kernel-republished mesh (identity today) is never assumed.
|
||||
private transformPreview: { key: string; object: THREE.Object3D; base: THREE.Matrix4 } | null = null;
|
||||
// A committed placement rebuilds the mesh, so the object captured at drag
|
||||
// start can be replaced mid-flight. Look the target up by document id at the
|
||||
// moment of use instead of trusting a cached reference.
|
||||
@@ -530,6 +534,47 @@ export class ImportRenderBridge {
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
// Placement editors call this while the user types: the mesh takes the world
|
||||
// delta between the committed placement (`from`) and the typed one (`to`)
|
||||
// without re-meshing the shape or involving the kernel. The kernel commit that
|
||||
// follows republishes the authoritative geometry and clears the preview.
|
||||
previewTransform(documentId: string, object: string, to: { position: number[]; axis?: number[]; angle?: number },
|
||||
from: { position: number[]; axis?: number[]; angle?: number }, meshId?: string): void {
|
||||
const entry = this.scenes.objects(documentId).find(item => item.id === (meshId ?? object));
|
||||
const target = entry?.object;
|
||||
if (!target) return;
|
||||
const key = `${documentId}:${meshId ?? object}`;
|
||||
if (!this.transformPreview || this.transformPreview.key !== key || this.transformPreview.object !== target)
|
||||
this.transformPreview = { key, object: target, base: target.matrix.clone() };
|
||||
const deltaPosition = new THREE.Vector3().fromArray(to.position).sub(new THREE.Vector3().fromArray(from.position));
|
||||
const deltaQuaternion = this.orientationFrom(to.axis, to.angle).multiply(this.orientationFrom(from.axis, from.angle).invert());
|
||||
const delta = new THREE.Matrix4().compose(deltaPosition, deltaQuaternion, new THREE.Vector3(1, 1, 1));
|
||||
target.matrix.copy(delta).multiply(this.transformPreview.base);
|
||||
target.matrixAutoUpdate = false;
|
||||
target.matrixWorldNeedsUpdate = true;
|
||||
target.updateMatrixWorld(true);
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
clearTransformPreview(): void {
|
||||
const preview = this.transformPreview;
|
||||
if (!preview) return;
|
||||
preview.object.matrix.copy(preview.base);
|
||||
preview.object.matrixAutoUpdate = true;
|
||||
preview.object.matrixWorldNeedsUpdate = true;
|
||||
this.transformPreview = null;
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
private orientationFrom(axis?: number[], angle?: number): THREE.Quaternion {
|
||||
const orientation = new THREE.Quaternion();
|
||||
if (!axis || axis.length !== 3 || !Number.isFinite(angle)) return orientation;
|
||||
const length = Math.hypot(axis[0], axis[1], axis[2]);
|
||||
if (length > 0) orientation.setFromAxisAngle(new THREE.Vector3(axis[0] / length, axis[1] / length, axis[2] / length),
|
||||
THREE.MathUtils.degToRad(angle ?? 0));
|
||||
return orientation;
|
||||
}
|
||||
|
||||
// SolidWorks-style selection display: the triad and focus box come from the
|
||||
// shared SelectionDecoration; this wrapper only feeds it the camera frame.
|
||||
private updateSelectionAxes(): void {
|
||||
|
||||
@@ -332,6 +332,7 @@ export function getWebModuleWorkerForCommand(module: string, command: string): s
|
||||
case "TechDraw:techdraw.pythonApi": return "techdraw-python.worker.ts";
|
||||
case "TechDraw:techdraw.pythonFamilyBatch": return "techdraw-python.worker.ts";
|
||||
case "TechDraw:techdraw.pythonMethod": return "techdraw-python.worker.ts";
|
||||
case "TemplatePyMod:templatepymod.inspectSourceInventory": return "templatepymod.worker.ts";
|
||||
case "TemplatePyMod:templatepymod.pythonApi": return "templatepymod-python.worker.ts";
|
||||
case "Web:web.dockOverlay": return "web-dock-overlay.worker.ts";
|
||||
case "Web:web.saveReopenBoundary": return "web-persistence.worker.ts";
|
||||
|
||||
212
web/src/panel-scroll.css
Normal file
212
web/src/panel-scroll.css
Normal file
@@ -0,0 +1,212 @@
|
||||
/* Shared three-column scroll contract for the standalone workbench and
|
||||
PartDesign pages. Each page adds a root class (stage-lock / stage-lock-pd) to
|
||||
<html> from its entry module; the rules below then lock the document to the
|
||||
viewport so every side panel owns its own scrollbar and the centre stage
|
||||
keeps its size. Narrow widths are deliberately excluded: below the
|
||||
three-column breakpoints the page falls back to normal document scrolling.
|
||||
|
||||
The same .pane-scroll contract already drives /project.html (see
|
||||
project-shell.tsx), so panels look and behave identically everywhere. */
|
||||
|
||||
/* --- Workbench page (/workbench.html) — three columns from 721px up ------- */
|
||||
@media (min-width: 721px) {
|
||||
html.stage-lock,
|
||||
html.stage-lock body {
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
html.stage-lock body > #app,
|
||||
html.stage-lock body > .fc-workbench-embed {
|
||||
flex: 1 1 0%;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* The shell mounts its three-column layout inside a root div plus a
|
||||
display:contents wrapper, so both boxes must pass the height down. */
|
||||
html.stage-lock #app > div {
|
||||
flex: 1 1 0%;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
/* flex-basis:0 keeps the grid height independent of panel content, so
|
||||
injecting or removing panel rows never nudges the centre stage. */
|
||||
html.stage-lock .layout {
|
||||
flex: 1 1 0%;
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
html.stage-lock .layout > aside {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock .layout > aside > h2,
|
||||
html.stage-lock .layout > aside > .heading {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
html.stage-lock .layout > aside > .pane-scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
/* Module task panels (Robot joints, Assembly, Draft …) are docked above the
|
||||
layout. Cap them so their own scrollbar absorbs tall content instead of
|
||||
pushing the three-column layout past the viewport. */
|
||||
html.stage-lock .module-task-dock {
|
||||
flex: 0 1 auto;
|
||||
min-height: 0;
|
||||
max-height: 42dvh;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
html.stage-lock .layout > main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* Centre stage: keep its size, scroll its own content if a task panel is tall. */
|
||||
html.stage-lock .layout > main.stage {
|
||||
overflow: auto;
|
||||
}
|
||||
html.stage-lock .layout.dock-workbench {
|
||||
grid-template-rows: auto minmax(0, 1fr) auto;
|
||||
}
|
||||
html.stage-lock .layout.dock-workbench > [data-dock-side="left"],
|
||||
html.stage-lock .layout.dock-workbench > [data-dock-side="right"] {
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- PartDesign page (/partdesign.html) — three columns from 1051px up ---- */
|
||||
@media (min-width: 1051px) {
|
||||
html.stage-lock-pd,
|
||||
html.stage-lock-pd body {
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock-pd body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
html.stage-lock-pd body > #app {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock-pd .design-app {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock-pd .design-layout {
|
||||
flex: 1 1 auto;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
html.stage-lock-pd .design-layout > aside {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.stage-lock-pd .design-layout > aside > h2 {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
html.stage-lock-pd .design-layout > aside > .pane-scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
html.stage-lock-pd .design-layout > main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Embeds --------------------------------------------------------------- */
|
||||
/* Embedded workbenches live inside an already-locked host document, so the
|
||||
embed itself must clip and let the inner .pane-scroll elements scroll. */
|
||||
.fc-workbench-embed {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.fc-workbench-embed > .module-task-dock {
|
||||
flex: 0 1 auto;
|
||||
min-height: 0;
|
||||
max-height: 42dvh;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
.fc-workbench-embed > .layout {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
.fc-workbench-embed > .layout > aside {
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.fc-workbench-embed > .layout > aside > .pane-scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
/* PartDesign embedded in the workbench stage: give the nested three-column
|
||||
layout a bounded height so its panels scroll instead of the whole stage. */
|
||||
.stage .partdesign-stage {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: min(760px, calc(100dvh - 220px));
|
||||
min-height: 520px;
|
||||
}
|
||||
.stage .partdesign-stage .design-app {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.stage .partdesign-stage .design-layout {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
.stage .partdesign-stage .design-layout > aside {
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.stage .partdesign-stage .design-layout > aside > .pane-scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
1305
web/src/partdesign-workspace-component.tsx
Normal file
1305
web/src/partdesign-workspace-component.tsx
Normal file
File diff suppressed because it is too large
Load Diff
4
web/src/partdesign-workspace.css
Normal file
4
web/src/partdesign-workspace.css
Normal file
@@ -0,0 +1,4 @@
|
||||
:root{font-family:system-ui,sans-serif;color:#e7ebed;background:#171a1d;color-scheme:dark;font-synthesis:none;letter-spacing:0}*{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button,a,input,select{outline-offset:3px}button{cursor:pointer}button:disabled{opacity:.4;cursor:default}header{height:58px;display:flex;align-items:center;gap:14px;padding:0 18px;border-bottom:1px solid #3c4246;background:#212629}header a{display:grid;place-items:center;color:#e7ebed;width:32px;height:32px}header strong{color:#8ed4dc;font-size:18px}h1{font-size:20px;font-weight:600;margin:0}.active-name{margin-left:auto;font-size:13px;color:#b1b9bf;overflow-wrap:anywhere}.toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:5px;padding:7px 16px;border-bottom:1px solid #3c4246}.icon-button{display:inline-grid;place-items:center;width:34px;height:34px;flex:none;padding:0;border:1px solid #4a5156;border-radius:4px;background:#272d31;color:#e7ebed;position:relative}.icon-button:hover{background:#384348}.icon-button[aria-pressed=true]{border-color:#8ed4dc;background:#294950}.icon-button input[type=file]{position:absolute;inset:0;width:100%;opacity:0;cursor:pointer}.separator{height:22px;width:1px;margin:0 6px;background:#4a5156}.design-layout{display:grid;grid-template-columns:220px minmax(0,1fr)290px;min-height:0;height:100%}.design-layout>*{min-width:0}.tree-pane,.property-pane{padding:0;display:flex;flex-direction:column;min-height:0;overflow:hidden;background:#202528}.tree-pane>.pane-scroll,.property-pane>.pane-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;padding:16px}.design-layout>main{display:flex;flex-direction:column;min-height:0;overflow:hidden}.tree-pane{border-right:1px solid #3c4246}.property-pane{border-left:1px solid #3c4246}h2{font-size:15px;line-height:1.4;margin:5px 0 12px;font-weight:600;overflow-wrap:anywhere}.tree-pane h2:not(:first-child){margin-top:26px}select,input:not([type=checkbox],[type=file]){width:100%;min-width:0;border:1px solid #4a5156;border-radius:4px;background:#171b1e;color:#e7ebed;padding:7px 8px}label{display:grid;gap:6px;margin:12px 0;font-size:13px}fieldset{min-width:0;border:0;border-top:1px solid #3c4246;padding:14px 0 0;margin:18px 0 0}legend{font-size:14px;padding:0 8px 0 0}.segmented{display:flex;gap:4px}.coordinates{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:7px}.actions{display:flex;flex-wrap:wrap;gap:6px;margin-top:14px}.actions button,.text-command{display:flex;align-items:center;justify-content:center;gap:7px;font-size:13px;border:1px solid #4a5156;border-radius:4px;padding:8px;background:#2b353a;color:#e7ebed;min-height:35px}.text-command{margin:10px 0;width:100%}.check{display:flex;align-items:center;gap:8px}.object-summary{display:grid;grid-template-columns:54px minmax(0,1fr);gap:8px;font-size:12px;margin:0 0 14px}.object-summary dt{color:#b1b9bf}.object-summary dd{margin:0;overflow-wrap:anywhere}.design-viewport{flex:1 1 auto;height:auto;min-height:0;max-height:none;width:100%}.design-viewport canvas{display:block;max-width:100%;touch-action:none}.document-status{padding:12px 16px;min-height:46px;font-size:13px;color:#a9cec1;overflow-wrap:anywhere;border-top:1px solid #3c4246}.document-status[data-error=true]{color:#f4aaaa}ul[role=tree]{list-style:none;margin:0;padding:0}li[role=treeitem]{display:flex;align-items:center;gap:8px;min-height:44px;padding:7px;border-left:3px solid transparent;cursor:pointer;font-size:13px}li[role=treeitem][aria-selected=true]{background:#29444b;border-left-color:#8ed4dc}li[role=treeitem] input,li[role=treeitem] svg{flex:none}li[role=treeitem] span{min-width:0;overflow-wrap:anywhere}li[role=treeitem] small{display:block;color:#a4b2b9;font-size:11px;margin-top:3px}li.feature-node{padding-left:20px}@media(max-width:1050px){.design-layout{grid-template-columns:190px minmax(0,1fr);height:auto;min-height:calc(100vh - 107px)}.property-pane{grid-column:1/-1;border-left:0;border-top:1px solid #3c4246;max-height:45vh}.property-pane>.pane-scroll{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 22px}.property-pane>.pane-scroll>.object-summary{grid-column:1/-1}.design-viewport{height:520px;min-height:320px;flex:none}}@media(max-width:600px){header{gap:8px;padding:0 12px}header strong{font-size:15px}h1{font-size:18px}.active-name{font-size:11px}.toolbar{padding:7px 10px}.separator{margin:0 3px}.design-layout{grid-template-columns:minmax(0,1fr)}.tree-pane{border-right:0;border-bottom:1px solid #3c4246}.property-pane{grid-column:auto}.property-pane>.pane-scroll{display:block}.design-viewport{height:360px;min-height:300px}.tree-pane h2:not(:first-child){margin-top:16px}}
|
||||
:root .edge-selection{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 8px;max-height:180px;overflow:auto;margin-top:10px}.edge-selection .check{margin:4px 0;min-height:24px}
|
||||
:root .toolbar .export-format{width:90px;height:34px;flex:none;padding:4px}
|
||||
:root .segmented{flex-wrap:wrap}
|
||||
9
web/src/partdesign-workspace.tsx
Normal file
9
web/src/partdesign-workspace.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import React from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { PartDesignWorkspace } from "./partdesign-workspace-component.js";
|
||||
import "./panel-scroll.css";
|
||||
|
||||
// Lock the page to the viewport so the tree and property panes scroll on their
|
||||
// own and the 3D viewport keeps its size (see panel-scroll.css).
|
||||
document.documentElement.classList.add("stage-lock-pd");
|
||||
createRoot(document.querySelector<HTMLDivElement>("#app")!).render(<PartDesignWorkspace />);
|
||||
@@ -23,7 +23,7 @@ import type { MeasureSelection } from "./measure-document-adapter.js";
|
||||
import { SurfaceFillingTask } from "./surface-filling-task.js";
|
||||
import { SurfaceGeomFillTask } from "./surface-geomfill-task.js";
|
||||
import { SpreadsheetCsvPanel } from "./spreadsheet-csv-panel.js";
|
||||
import { SpreadsheetSheetEditor, type SheetCell, type SheetStructure, sheetColumn, sheetCoordinate } from "./spreadsheet-sheet-editor.js";
|
||||
import { type SheetCell, type SheetStructure, sheetColumn, sheetCoordinate } from "./spreadsheet-sheet-editor.js";
|
||||
import { PersistentToolbarWorkspace, ToolbarGroup } from "./persistent-toolbar-workspace.js";
|
||||
import { StartLaunchPanel } from "./start-launch-panel.js";
|
||||
import { startParameters } from "./start-preferences.js";
|
||||
@@ -68,9 +68,9 @@ import { installUiAccessibility } from "./ui-accessibility.js";
|
||||
import type { FacadeResponse } from "./facade-envelope.js";
|
||||
import { documentSessionReducer } from "./document-session.js";
|
||||
import { PART_DOCUMENT_COMMAND, PART_DOCUMENT_SCHEMA, PART_PRIMITIVE_FIELDS, documentObjectMesh, type PartPrimitive, type PartBoolean, type PartDocumentAction, type PartDocumentPayload, type PartDocumentResult } from "./part-document-facade.js";
|
||||
import { isOpfsSupported, listDocumentFiles, listExportFiles, readDocumentFile, readExportFile, writeDocumentFile } from "./storage.js";
|
||||
import { isOpfsSupported, listDocumentFiles, listExportFiles, readDocumentFile, readExportFile, writeDocumentFile, writeExportFile } from "./storage.js";
|
||||
import { ExportService } from "./export-service.js";
|
||||
import { DeltaReferencePanel, LineReferencePanel } from "./delta-reference-panel.js";
|
||||
import { Abb120ReferencePanel, DeltaReferencePanel, LineReferencePanel } from "./delta-reference-panel.js";
|
||||
import type { MeshPayload } from "./worker-protocol.js";
|
||||
import { ImportRenderBridge } from "./import-render-bridge.js";
|
||||
import { registerTestMdiHost } from "./test-desktop-adapter.js";
|
||||
@@ -89,10 +89,12 @@ import { formatLength, formatVolume, unitInfo } from "./shell/units.js";
|
||||
import { ShortcutEditor, ShortcutManager } from "./shell/shortcut-manager.js";
|
||||
import { BottomDock } from "./shell/bottom-dock.js";
|
||||
import { WorkbenchFrame, isExternalWorkbench } from "./shell/workbench-frame.js";
|
||||
import { SpreadsheetPanel, SpreadsheetEditorPanel as SpreadsheetSheetEditor } from "./workbenches/Spreadsheet/index.js";
|
||||
import { CommandPalette } from "./shell/command-palette.js";
|
||||
import { DesktopCommandDispatcher } from "./desktop-command-dispatcher.js";
|
||||
import type { WorkbenchCommandRecord } from "./workbench-command-facade.js";
|
||||
import { DocumentTree, type DocumentTreeNode } from "./document-tree.js";
|
||||
import { useDebouncedCommit } from "./use-debounced-commit.js";
|
||||
import { PARTDESIGN_DOCUMENT_COMMAND, PARTDESIGN_DOCUMENT_SCHEMA, type DesignAction, type DesignPayload, type DesignResult } from "./partdesign-document-facade.js";
|
||||
|
||||
const css = `:root{color-scheme:dark;font-family:Inter,system-ui,sans-serif;background:#10161d;color:#e7edf3}*{box-sizing:border-box}html{overflow-x:hidden}body{margin:0;min-width:320px;overflow-x:hidden}.top{align-items:center;background:#17212b;border-bottom:1px solid #2c3b48;display:flex;gap:14px;padding:14px 20px}.brand{background:#3b9db0;border-radius:5px;color:#071219;font-weight:800;padding:7px}.title{margin-left:auto}.layout{display:grid;grid-template-columns:260px minmax(0,1fr) 300px;min-height:calc(100vh - 56px)}aside{background:#17212b;padding:18px;overflow:auto}aside:first-child{border-right:1px solid #2c3b48}aside:last-child{border-left:1px solid #2c3b48}.stage{background:#0d1319;padding:24px}.viewport{background:#0d1319;border:1px solid #334854;height:330px;margin:12px 0}.viewport canvas{display:block;height:100%;width:100%}.tab,.action{background:#1d2a35;border:1px solid #435464;border-radius:5px;color:#e7edf3;cursor:pointer;display:block;font:inherit;margin:7px 0;padding:9px 11px;text-align:left;width:100%}.tab.active{background:#264b56;border-color:#66c7d5}.action:hover{border-color:#66b7c8}.action:disabled{opacity:.45}.status{color:#9cb6c2;line-height:1.5}.status.ok{color:#9ce0bd}.status.error{color:#ff9e9e}.stat{border-bottom:1px solid #2c3b48;padding:10px 0}.stat small{color:#8ea2ae;display:block;margin-top:4px}.result{font:12px ui-monospace,monospace;line-height:1.5;max-height:60vh;overflow:auto;white-space:pre-wrap;word-break:break-word}`;
|
||||
@@ -117,8 +119,13 @@ function App() {
|
||||
const navigationContext = useMemo(() => readNavigationContext(), []);
|
||||
const initialDocumentId = navigationContext.documentId ?? "project-document-1";
|
||||
const requestedWorkbench = new URLSearchParams(window.location.search).get("workbench");
|
||||
const initialWorkbench = ["Part", "Sketcher", "PartDesign", "Spreadsheet", "Surface", "Assembly", "Draft", "Architecture", "TechDraw", "CAM"].includes(requestedWorkbench ?? "")
|
||||
? requestedWorkbench as "Part" | "Sketcher" | "PartDesign" | "Spreadsheet" | "Surface" | "Assembly" | "Draft" | "Architecture" | "TechDraw" | "CAM" : undefined;
|
||||
// External workbenches mount in-process through <WorkbenchShell> by default.
|
||||
// ?nativeWorkbench=0 keeps the legacy /workbench.html iframe as a fallback.
|
||||
const nativeWorkbench = new URLSearchParams(window.location.search).get("nativeWorkbench") !== "0";
|
||||
// "Architecture" is the legacy start-page label; the module id is BIM.
|
||||
const requestedWorkbenchId = requestedWorkbench === "Architecture" ? "BIM" : requestedWorkbench;
|
||||
const initialWorkbench = ["Part", "Sketcher", "PartDesign", "Spreadsheet", "Surface", "Assembly", "Draft", "BIM", "TechDraw", "CAM", "Plot", "Show", "Web"].includes(requestedWorkbenchId ?? "")
|
||||
? requestedWorkbenchId as "Part" | "Sketcher" | "PartDesign" | "Spreadsheet" | "Surface" | "Assembly" | "Draft" | "BIM" | "TechDraw" | "CAM" | "Plot" | "Show" | "Web" : undefined;
|
||||
const store = useMemo(() => { const value = new ProjectSessionStore(); value.open(initialDocumentId, initialDocumentId); value.open("project-document-2", "Project Document 2"); value.switchTo(initialDocumentId); return value; }, [initialDocumentId]);
|
||||
const checkpoint = useMemo(() => new ProjectCheckpointStore("freecad-web-project-ui-checkpoint"), []);
|
||||
const recovery = useMemo(() => new RecoveryController(), []);
|
||||
@@ -230,6 +237,7 @@ function App() {
|
||||
const [exportFormat, setExportFormat] = useState("stl");
|
||||
const [referenceOpen, setReferenceOpen] = useState(false);
|
||||
const [lineReferenceOpen, setLineReferenceOpen] = useState(false);
|
||||
const [abbReferenceOpen, setAbbReferenceOpen] = useState(false);
|
||||
// SolidWorks-style direct manipulation: picking an object arms the translate
|
||||
// controller together with the local triad and selection focus. The toolbar
|
||||
// still lets the user switch to rotate or turn the handles off entirely.
|
||||
@@ -296,12 +304,16 @@ function App() {
|
||||
const designDocuments = useRef(new Set<string>());
|
||||
const [partSnapshots, setPartSnapshots] = useState<Record<string, PartDocumentResult>>({});
|
||||
const [designSnapshots, setDesignSnapshots] = useState<Record<string, DesignResult>>({});
|
||||
const [workbenches, setWorkbenches] = useState<Record<string, "Part" | "Sketcher" | "PartDesign" | "Spreadsheet" | "Surface" | "Assembly" | "Draft" | "Architecture" | "TechDraw" | "CAM">>(() => initialWorkbench ? { [initialDocumentId]: initialWorkbench } : {});
|
||||
const [workbenches, setWorkbenches] = useState<Record<string, "Part" | "Sketcher" | "PartDesign" | "Spreadsheet" | "Surface" | "Assembly" | "Draft" | "BIM" | "TechDraw" | "CAM" | "Plot" | "Show" | "Web">>(() => initialWorkbench ? { [initialDocumentId]: initialWorkbench } : {});
|
||||
const workbench = workbenches[active] ?? "Part";
|
||||
useEffect(() => { if (status) setReportLog(previous => previous[0] === status ? previous : [status, ...previous].slice(0, 50)); }, [status]);
|
||||
useEffect(() => {
|
||||
const palette = (event: KeyboardEvent) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key.toLowerCase() === "p") {
|
||||
// Manual chapter 15 documents Ctrl+K; Ctrl+Shift+P is the menu-labelled
|
||||
// alias. Both open the same palette.
|
||||
const accel = (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k" && !event.shiftKey && !event.altKey;
|
||||
const alias = (event.ctrlKey || event.metaKey) && event.shiftKey && event.key.toLowerCase() === "p";
|
||||
if (accel || alias) {
|
||||
event.preventDefault(); setPaletteOpen(true);
|
||||
}
|
||||
};
|
||||
@@ -352,6 +364,12 @@ function App() {
|
||||
useEffect(() => { setImportCommand(null); setImportFile(null); setReplaceImport(false); }, [active]);
|
||||
const [treeWidth, setTreeWidth] = useState(240);
|
||||
const [propertyWidth, setPropertyWidth] = useState(300);
|
||||
// Typing in a property field commits ~250 ms after the last keystroke so the
|
||||
// 3D view follows along, instead of waiting for blur like desktop FreeCAD.
|
||||
const propertyCommit = useDebouncedCommit();
|
||||
const propertyCommitSeq = useRef(0);
|
||||
// Placement editors coalesce live previews to one matrix write per frame.
|
||||
const placementPreviewFrame = useRef(0);
|
||||
const [propertyColumnWidth, setPropertyColumnWidth] = useState<number | null>(() => {
|
||||
try {
|
||||
const value = Number(window.localStorage.getItem("freecad.propertyEditor.firstColumnWidth"));
|
||||
@@ -388,9 +406,10 @@ function App() {
|
||||
const objects = Object.values(currentDocument?.objects ?? {});
|
||||
const treeNodes = useMemo<DocumentTreeNode[]>(() => objects.map(object => {
|
||||
const label = String(object.properties.Label ?? object.id);
|
||||
const iconSlug = object.type.startsWith("PartDesign::") ? `PartDesign_${object.type.replace("PartDesign::", "")}`
|
||||
: object.type === "Sketcher::SketchObject" ? "" : "Part_3D_object";
|
||||
const icon = object.type === "Sketcher::SketchObject" ? "/icons/part/Sketcher_NewSketch.svg" : `/icons/partdesign/${iconSlug}.svg`;
|
||||
// PartDesign icons live under icons/partdesign; the generic 3D-object icon
|
||||
// belongs to the Part icon set, which is where it actually ships.
|
||||
const icon = object.type.startsWith("PartDesign::") ? `/icons/partdesign/PartDesign_${object.type.replace("PartDesign::", "")}.svg`
|
||||
: object.type === "Sketcher::SketchObject" ? "/icons/part/Sketcher_NewSketch.svg" : "/icons/part/Part_3D_object.svg";
|
||||
return {
|
||||
id: object.id,
|
||||
label,
|
||||
@@ -935,21 +954,34 @@ function App() {
|
||||
window.parent.postMessage({ type: "freecad-project-ready" }, location.origin);
|
||||
return () => window.removeEventListener("message", receive);
|
||||
}, [active, importing, csvPanel, objects, workspaceTask, viewCommand]);
|
||||
const createOrEditBox = async (edit: boolean) => {
|
||||
const createOrEditBox = async (edit: boolean, options: { live?: boolean; dimensions?: [number, number, number] } = {}) => {
|
||||
if (!active || importing) return;
|
||||
setImporting(true);
|
||||
const dimensions = options.dimensions ?? boxDimensions;
|
||||
const token = options.live ? ++propertyCommitSeq.current : 0;
|
||||
if (token) {
|
||||
// Typing rarely changes the value it started from: a duplicate live commit
|
||||
// (blur right after the debounce fired) would cost a full re-mesh.
|
||||
const committed = selectedObject?.properties.dimensions;
|
||||
if (Array.isArray(committed) && committed.length === 3
|
||||
&& committed.every((value, index) => Number(value) === dimensions[index])) return;
|
||||
}
|
||||
if (!options.live) setImporting(true);
|
||||
try {
|
||||
if (!nativeDocuments.current.has(active)) await nativeRequest(active, "create");
|
||||
let name = edit ? String(selectedObject?.properties.NativeName ?? "") : "Box1";
|
||||
if (!edit) { let index = 1; while (currentDocument?.objects[`native:${name}`]) name = `Box${++index}`; }
|
||||
const result = await nativeRequest(active, "setBox", { object: name, dimensions: boxDimensions });
|
||||
const result = await nativeRequest(active, "setBox", { object: name, dimensions });
|
||||
// A newer keystroke already started its own commit: keep the fresher reply.
|
||||
if (token && token !== propertyCommitSeq.current) return;
|
||||
applyNativeDocument(active, result);
|
||||
setCommittedBoxDimensions([...boxDimensions]);
|
||||
setCommittedBoxDimensions([...dimensions]);
|
||||
setSelectedObjects(previous => ({ ...previous, [active]: `native:${name}` }));
|
||||
renderBridge.activateDocument(active); renderBridge.fitDocument();
|
||||
setStatus(`${name}: ${boxDimensions.join(" × ")}`);
|
||||
renderBridge.activateDocument(active);
|
||||
// Live commits must not reframe the camera on every keystroke.
|
||||
if (!token) renderBridge.fitDocument();
|
||||
setStatus(`${name}: ${dimensions.join(" × ")}`);
|
||||
} catch (error) { setStatus(String(error)); }
|
||||
finally { setImporting(false); }
|
||||
finally { if (!options.live) setImporting(false); }
|
||||
};
|
||||
const commitNativeLabel = async (labelValue?: string) => {
|
||||
if (!selectedObject?.properties.NativeName) return;
|
||||
@@ -970,21 +1002,55 @@ function App() {
|
||||
} catch (error) { setStatus(String(error)); }
|
||||
finally { setImporting(false); }
|
||||
};
|
||||
const createOrEditPrimitive = async (edit: boolean) => {
|
||||
const createOrEditPrimitive = async (edit: boolean, options: { live?: boolean; parameters?: Record<string, number> } = {}) => {
|
||||
if (!active || importing) return;
|
||||
const documentId = active;
|
||||
setImporting(true);
|
||||
const parameters = options.parameters ?? primitiveParameters;
|
||||
const token = options.live ? ++propertyCommitSeq.current : 0;
|
||||
if (token) {
|
||||
const committed = selectedObject?.properties.parameters as Record<string, unknown> | undefined;
|
||||
const fields = Object.keys(parameters);
|
||||
if (committed && fields.length === Object.keys(committed).length
|
||||
&& fields.every(field => Number(committed[field]) === parameters[field])) return;
|
||||
}
|
||||
if (!options.live) setImporting(true);
|
||||
try {
|
||||
if (!nativeDocuments.current.has(documentId)) await nativeRequest(documentId, "create");
|
||||
let name = edit ? String(selectedObject?.properties.NativeName ?? "") : `${primitive}1`;
|
||||
if (!edit) { let index = 1; while (currentDocument?.objects[`native:${name}`]) name = `${primitive}${++index}`; }
|
||||
const result = await nativeRequest(documentId, "setPrimitive", { object: name, primitive, parameters: primitiveParameters });
|
||||
const result = await nativeRequest(documentId, "setPrimitive", { object: name, primitive, parameters });
|
||||
// A newer keystroke already started its own commit: keep the fresher reply.
|
||||
if (token && token !== propertyCommitSeq.current) return;
|
||||
applyNativeDocument(documentId, result);
|
||||
setSelectedObjects(previous => ({ ...previous, [documentId]: `native:${name}` }));
|
||||
renderBridge.activateDocument(documentId); renderBridge.fitDocument();
|
||||
setStatus(`${name}: ${Object.entries(primitiveParameters).map(([key, value]) => `${key}=${value}`).join(", ")}`);
|
||||
renderBridge.activateDocument(documentId);
|
||||
if (!token) renderBridge.fitDocument();
|
||||
setStatus(`${name}: ${Object.entries(parameters).map(([key, value]) => `${key}=${value}`).join(", ")}`);
|
||||
} catch (error) { setStatus(String(error)); }
|
||||
finally { setImporting(false); }
|
||||
finally { if (!options.live) setImporting(false); }
|
||||
};
|
||||
// Committed placement of the selected object in the same shape the kernel
|
||||
// snapshot reports: primitives keep it on primitivePlacement, everything else
|
||||
// on rotation. Live previews diff the typed placement against this one.
|
||||
const selectedPlacement = () => {
|
||||
const rotation = selectedObject?.properties.rotation as { axis?: number[]; angle?: number } | undefined;
|
||||
const primitive = selectedObject?.properties.primitivePlacement as { position?: number[]; axis?: number[]; angle?: number } | undefined;
|
||||
const position = [primitive?.position, selectedObject?.properties.position].find(value => Array.isArray(value) && value.length === 3) as number[] | undefined;
|
||||
const axis = [rotation?.axis, primitive?.axis].find(value => Array.isArray(value) && value.length === 3) as number[] | undefined;
|
||||
const angle = typeof rotation?.angle === "number" ? rotation.angle : primitive?.angle;
|
||||
return { position: position ? [...position] : [0, 0, 0], axis: axis ? [...axis] : [0, 0, 1], angle: typeof angle === "number" ? angle : 0 };
|
||||
};
|
||||
const schedulePlacementPreview = (to: { position: number[]; axis?: number[]; angle?: number }) => {
|
||||
const object = String(selectedObject?.properties.NativeName ?? "");
|
||||
if (!active || !object || jtDocuments.current.has(active)) { renderBridge.clearTransformPreview(); return; }
|
||||
const from = selectedPlacement();
|
||||
window.cancelAnimationFrame(placementPreviewFrame.current);
|
||||
placementPreviewFrame.current = window.requestAnimationFrame(() => renderBridge.previewTransform(active, object, to, from));
|
||||
};
|
||||
const cancelPlacementPreview = () => {
|
||||
window.cancelAnimationFrame(placementPreviewFrame.current);
|
||||
placementPreviewFrame.current = 0;
|
||||
renderBridge.clearTransformPreview();
|
||||
};
|
||||
const editNative = async (action: PartDocumentAction, details: Partial<PartDocumentPayload> = {}) => {
|
||||
if (!active || importing) return;
|
||||
@@ -1311,8 +1377,9 @@ function App() {
|
||||
const document = store.currentDocumentId;
|
||||
if (!document) throw new Error(`${kind} launch created no active document`);
|
||||
if (window.parent === window) {
|
||||
setWorkbenches(previous => ({ ...previous, [document]: kind }));
|
||||
await startParameters(router, { LastModule: `${kind}Workbench` }, true);
|
||||
const launchedWorkbench = kind === "Architecture" ? "BIM" : kind;
|
||||
setWorkbenches(previous => ({ ...previous, [document]: launchedWorkbench }));
|
||||
await startParameters(router, { LastModule: `${launchedWorkbench}Workbench` }, true);
|
||||
setStartVisible(!preferences.closeStart);
|
||||
return true;
|
||||
}
|
||||
@@ -1486,7 +1553,22 @@ function App() {
|
||||
}
|
||||
setStartVisible(!preferences.closeStart);
|
||||
};
|
||||
const downloadFcstd = () => { if (!nativeBytes) return; const result = exporter.download({ module: "Part", format: "application/octet-stream", fileName: `${jtDocuments.current.has(active) ? "JtReader_" : ""}${nativeName(active)}.FCStd`, bytes: nativeBytes }); setStatus(result.status === "ok" ? "FCStd 已写入 OPFS" : result.error?.message || "FCStd OPFS write failed"); };
|
||||
// "下载 native FCStd" is the one explicit local download in the shell: the
|
||||
// OPFS copy is written first (the default contract), then the same bytes are
|
||||
// handed to the browser download. export/download() alone only writes OPFS.
|
||||
const downloadFcstd = async () => {
|
||||
if (!nativeBytes) return;
|
||||
const fileName = `${jtDocuments.current.has(active) ? "JtReader_" : ""}${nativeName(active)}.FCStd`;
|
||||
const written = exporter.download({ module: "Part", format: "application/octet-stream", fileName, bytes: nativeBytes });
|
||||
if (written.status !== "ok") { setStatus(written.error?.message || "FCStd OPFS write failed"); return; }
|
||||
try {
|
||||
await writeExportFile(fileName, nativeBytes);
|
||||
const result = await exporter.downloadToLocal(fileName);
|
||||
setStatus(result.status === "ok"
|
||||
? `已下载 ${fileName}(${result.value?.bytes ?? nativeBytes.byteLength} bytes),副本已写入 OPFS`
|
||||
: result.error?.message || "FCStd 本地下载失败");
|
||||
} catch (error) { setStatus(String(error)); }
|
||||
};
|
||||
const exportDependencyGraph = async () => {
|
||||
if (importing || !active || !nativeDocuments.current.has(active)) return;
|
||||
const documentId = nativeName(active);
|
||||
@@ -1681,6 +1763,7 @@ function App() {
|
||||
if (["tube", "tolerance", "primitives", "shape-from-mesh", "points-from-mesh", "edit-attachment"].includes(item.task)) void runRetainedPartCommand(item.command, { action: "read" });
|
||||
};
|
||||
const cancelWorkspaceTask = () => {
|
||||
cancelPlacementPreview();
|
||||
setPartTaskMode(undefined);
|
||||
if (workspaceTask === "measure-mass-properties") {
|
||||
void nativeRequest(active, "clearMassGeometry", {}).then(result => applyNativeDocument(active, result, true)).catch(error => setStatus(String(error)));
|
||||
@@ -1770,20 +1853,35 @@ function App() {
|
||||
(side === "tree" ? setTreeWidth : setPropertyWidth)(previous => event.key === "Home" ? 180 : event.key === "End" ? 420 : Math.max(180, Math.min(420, previous + (event.key === "ArrowRight" ? 20 : -20)))); }} />;
|
||||
return <div className="desktop-workspace"><style>{css}{partUiCss}{`
|
||||
.layout > *{min-width:0}.top{flex-wrap:wrap}.stage{min-width:0}.tab small{display:block}.tab,.action{overflow-wrap:anywhere}.desktop-status-bar{position:sticky;bottom:0;z-index:6;display:flex;align-items:center;min-height:22px;padding:0 8px;background:var(--fc-primary);border:0}.desktop-status-bar .status{flex:1;min-width:0;margin:0;padding:2px 0;line-height:1.35;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
@media(min-width:801px){
|
||||
.desktop-workspace{display:flex;flex-direction:column;height:100%;min-height:0;overflow:hidden}
|
||||
body:has(.desktop-workspace){display:flex;flex-direction:column;height:100vh;height:100dvh;overflow:hidden}
|
||||
body:has(.desktop-workspace)>:not(#app){flex:0 0 auto}
|
||||
body:has(.desktop-workspace)>#app{flex:1 1 auto;min-height:0;overflow:hidden}
|
||||
.desktop-workspace .toolbar-workspace{flex:1 1 auto;min-height:0}
|
||||
.desktop-workspace .toolbar-content{display:flex;flex-direction:column;min-height:0;overflow:hidden}
|
||||
.desktop-workspace .toolbar-content>.layout{flex:1 1 auto;min-height:0}
|
||||
.desktop-workspace .desktop-status-bar{position:static;flex:0 0 auto}
|
||||
.desktop-workspace .layout>aside{display:flex;flex-direction:column;min-height:0;overflow:hidden;padding:0}
|
||||
.desktop-workspace .layout>aside>.pane-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;padding:0 18px 12px}
|
||||
.desktop-workspace .layout>main.stage{display:flex;flex-direction:column;min-height:0;overflow-y:auto;overflow-x:hidden}
|
||||
.desktop-workspace .layout>main.stage>*{flex:0 0 auto}
|
||||
.desktop-workspace .layout>main.stage>.viewport{flex:1 1 260px;min-height:220px;height:auto;max-height:none}
|
||||
}
|
||||
.viewport{position:relative;border:0;height:440px;max-height:65vh}
|
||||
.properties label{display:grid;gap:6px;margin:12px 0}.properties>label{grid-template-columns:minmax(72px,.72fr) minmax(0,1fr);align-items:center;border-bottom:1px solid var(--fc-border);padding:5px 0;margin:0}.properties>label:focus-within{background:var(--fc-accent);border-bottom-color:var(--fc-accent)}.properties>label>span{color:#b5b5b5}.properties input:not([type=checkbox]),.properties select,.saved-documents{box-sizing:border-box;width:100%;min-width:0;min-height:22px;padding:2px 4px;background:var(--fc-primary);color:var(--fc-text);border:1px solid var(--fc-border);border-radius:3px}.properties select{padding-right:18px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary))}.properties input:not([type=checkbox]):hover,.properties select:hover{border-color:var(--fc-border-hover)}.properties select:hover{background:var(--fc-accent-hover)}.properties input:not([type=checkbox]):focus,.properties select:focus{border-color:var(--fc-accent);outline:none}.properties input:not([type=checkbox]):disabled,.properties select:disabled,.saved-documents:disabled{background:var(--fc-menu);color:var(--fc-disabled);border-color:var(--fc-border)}.properties input[type=color]{height:32px;padding:3px}.properties>dl{position:relative;display:grid;grid-template-columns:var(--property-first-column,minmax(72px,.72fr)) minmax(0,1fr);margin:8px 0 12px;border-top:1px solid var(--fc-border)}.properties>dl dt,.properties>dl dd{margin:0;padding:5px 4px;border-right:1px solid var(--fc-border);border-bottom:1px solid var(--fc-border);overflow-wrap:anywhere}.properties>dl dt{color:#b5b5b5}.properties>dl dd{color:var(--fc-disabled)}.property-column-resizer{position:absolute;z-index:1;top:0;bottom:0;left:calc(var(--property-first-column,50%) - 3px);width:6px;cursor:col-resize;touch-action:none}.property-column-resizer:focus-visible{outline:1px solid var(--fc-accent);outline-offset:-1px}.properties>h2{font-size:14px;letter-spacing:.04em;text-transform:uppercase;border-bottom:1px solid var(--fc-border);padding-bottom:8px;margin:0 0 8px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary))}.properties .property-group-title{font-size:12px;line-height:1.3;font-weight:700;color:var(--fc-text);background:var(--fc-primary);border-bottom:1px solid var(--fc-border);margin:10px 0 0;padding:5px 6px}.status{overflow-wrap:anywhere}.position-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}.properties fieldset{min-width:0}.primitive-actions{flex-wrap:wrap}.task-box{border:1px solid var(--fc-border);margin:8px 0}.task-box>summary{cursor:pointer;background:var(--fc-panel);padding:7px 9px;border-bottom:1px solid var(--fc-border);color:#e7edf3}.task-box>summary:focus-visible{outline:1px solid var(--fc-accent);outline-offset:-1px}.task-box-content{max-height:48vh;overflow:auto;padding:8px}.task-dialog-actions{display:flex;justify-content:flex-end;gap:8px;border-top:1px solid var(--fc-border);padding-top:10px;margin-top:10px}.task-dialog-actions button{width:auto;margin:0}.task-dialog-actions .run{order:0}
|
||||
.properties label{display:grid;gap:6px;margin:12px 0}.properties>.pane-scroll>label{grid-template-columns:minmax(72px,.72fr) minmax(0,1fr);align-items:center;border-bottom:1px solid var(--fc-border);padding:5px 0;margin:0}.properties>.pane-scroll>label:focus-within{background:var(--fc-accent);border-bottom-color:var(--fc-accent)}.properties>.pane-scroll>label>span{color:#b5b5b5}.properties input:not([type=checkbox]),.properties select,.saved-documents{box-sizing:border-box;width:100%;min-width:0;min-height:22px;padding:2px 4px;background:var(--fc-primary);color:var(--fc-text);border:1px solid var(--fc-border);border-radius:3px}.properties select{padding-right:18px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary))}.properties input:not([type=checkbox]):hover,.properties select:hover{border-color:var(--fc-border-hover)}.properties select:hover{background:var(--fc-accent-hover)}.properties input:not([type=checkbox]):focus,.properties select:focus{border-color:var(--fc-accent);outline:none}.properties input:not([type=checkbox]):disabled,.properties select:disabled,.saved-documents:disabled{background:var(--fc-menu);color:var(--fc-disabled);border-color:var(--fc-border)}.properties input[type=color]{height:32px;padding:3px}.properties>.pane-scroll>dl{position:relative;display:grid;grid-template-columns:var(--property-first-column,minmax(72px,.72fr)) minmax(0,1fr);margin:8px 0 12px;border-top:1px solid var(--fc-border)}.properties>.pane-scroll>dl dt,.properties>.pane-scroll>dl dd{margin:0;padding:5px 4px;border-right:1px solid var(--fc-border);border-bottom:1px solid var(--fc-border);overflow-wrap:anywhere}.properties>.pane-scroll>dl dt{color:#b5b5b5}.properties>.pane-scroll>dl dd{color:var(--fc-disabled)}.property-column-resizer{position:absolute;z-index:1;top:0;bottom:0;left:calc(var(--property-first-column,50%) - 3px);width:6px;cursor:col-resize;touch-action:none}.property-column-resizer:focus-visible{outline:1px solid var(--fc-accent);outline-offset:-1px}.properties>h2{font-size:14px;letter-spacing:.04em;text-transform:uppercase;border-bottom:1px solid var(--fc-border);padding-bottom:8px;margin:0 0 8px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary))}.properties .property-group-title{font-size:12px;line-height:1.3;font-weight:700;color:var(--fc-text);background:var(--fc-primary);border-bottom:1px solid var(--fc-border);margin:10px 0 0;padding:5px 6px}.status{overflow-wrap:anywhere}.position-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}.properties fieldset{min-width:0}.primitive-actions{flex-wrap:wrap}.task-box{border:1px solid var(--fc-border);margin:8px 0}.task-box>summary{cursor:pointer;background:var(--fc-panel);padding:7px 9px;border-bottom:1px solid var(--fc-border);color:#e7edf3}.task-box>summary:focus-visible{outline:1px solid var(--fc-accent);outline-offset:-1px}.task-box-content{max-height:48vh;overflow:auto;padding:8px}.task-dialog-actions{display:flex;justify-content:flex-end;gap:8px;border-top:1px solid var(--fc-border);padding-top:10px;margin-top:10px}.task-dialog-actions button{width:auto;margin:0}.task-dialog-actions .run{order:0}
|
||||
.properties input[type=color]{width:32px;height:22px;min-height:22px;padding:3px;border:1px solid var(--fc-border);border-radius:3px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary));cursor:pointer}.properties input[type=color]:hover{border-color:var(--fc-border-hover)}.properties input[type=color]:focus-visible{outline:1px solid var(--fc-accent);outline-offset:1px}.properties input[type=color]:disabled{opacity:.45}.properties input[type=file]::file-selector-button{margin-right:6px;padding:3px 12px;border:1px solid var(--fc-border);border-radius:3px;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary));color:var(--fc-text);font:inherit;cursor:pointer}.properties input[type=file]::file-selector-button:hover{background:var(--fc-accent-hover);border-color:var(--fc-border-hover)}.properties input[type=file]:focus-visible{outline:1px solid var(--fc-accent);outline-offset:1px}.properties input[type=file]:disabled{opacity:.45}
|
||||
.properties input::selection,.properties select::selection{background:var(--fc-border-hover);color:var(--fc-text)}
|
||||
.properties>label>.property-link-name{color:#20aa20}.properties>label>.property-expression{color:#0095ff}.properties>label>input.property-expression-value{color:#0095ff}.properties>label>input.property-expression-value:read-only{cursor:default}.properties>label>input.property-expression-value::-webkit-inner-spin-button,.properties>label>input.property-expression-value::-webkit-outer-spin-button{display:none}
|
||||
.properties>dl dt:nth-of-type(even),.properties>dl dd:nth-of-type(even){background:var(--fc-panel)}
|
||||
.properties>.pane-scroll>label>.property-link-name{color:#20aa20}.properties>.pane-scroll>label>.property-expression{color:#0095ff}.properties>.pane-scroll>label>input.property-expression-value{color:#0095ff}.properties>.pane-scroll>label>input.property-expression-value:read-only{cursor:default}.properties>.pane-scroll>label>input.property-expression-value::-webkit-inner-spin-button,.properties>.pane-scroll>label>input.property-expression-value::-webkit-outer-spin-button{display:none}
|
||||
.properties>.pane-scroll>dl dt:nth-of-type(even),.properties>.pane-scroll>dl dd:nth-of-type(even){background:var(--fc-panel)}
|
||||
.properties input[type=checkbox]{width:14px;height:14px;margin:2px 0;accent-color:var(--fc-accent);color-scheme:dark}.properties input[type=checkbox]:focus-visible{outline:1px solid var(--fc-accent);outline-offset:1px}.properties input[type=checkbox]:disabled{opacity:.45}
|
||||
.properties input[type=number]{color-scheme:dark}.properties input[type=number]::-webkit-inner-spin-button,.properties input[type=number]::-webkit-outer-spin-button{opacity:1;filter:grayscale(1) brightness(1.35)}.properties input[type=number]:hover::-webkit-inner-spin-button,.properties input[type=number]:hover::-webkit-outer-spin-button{filter:grayscale(1) brightness(1.7)}.properties input[type=number]:disabled::-webkit-inner-spin-button,.properties input[type=number]:disabled::-webkit-outer-spin-button{opacity:.45}
|
||||
.property-link-editor{display:flex;align-items:center;min-width:0;border:1px solid var(--fc-border);background:var(--fc-primary);border-radius:3px;min-height:22px}.property-link-summary{min-width:0;flex:1;padding:2px 4px;color:var(--fc-accent);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.property-link-button{width:22px;height:20px;flex:none;margin:0;padding:0;border:0;border-left:1px solid var(--fc-border);border-radius:0;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary));color:var(--fc-text);line-height:1;cursor:pointer}.property-link-button:hover,.property-link-button:focus-visible{background:var(--fc-accent-hover);border-color:var(--fc-accent);outline:1px solid var(--fc-accent);outline-offset:-1px}.property-link-list{grid-template-columns:minmax(72px,.72fr) minmax(0,1fr)!important}.property-link-list select{width:100%;min-height:66px!important}.primitive-tools{display:flex;gap:4px;margin:8px 0}.tool{display:grid;place-items:center;width:38px;height:36px;flex:none;border:1px solid #435464;border-radius:4px;background:#17212b;color:#e7edf3;cursor:pointer}.tool[aria-pressed=true]{background:#264b56;border-color:#66c7d5}.tool:disabled{opacity:.45;cursor:default}.primitive-actions{display:flex;gap:8px;margin-top:12px}.primitive-actions button{display:flex;align-items:center;gap:8px;font:inherit;padding:8px;background:#1d2a35;color:#e7edf3;border:1px solid #435464;border-radius:4px}.primitive-editor{margin-top:14px;border:0;border-top:1px solid #435464;padding:14px 0 0}.primitive-editor legend{padding:0 6px 0 0}
|
||||
@media(max-width:1100px){.layout{grid-template-columns:210px minmax(0,1fr)}.properties{grid-column:1/-1;border-top:1px solid #2c3b48}}
|
||||
@media(max-width:650px){.layout{grid-template-columns:minmax(0,1fr)}.stage,aside{padding:14px}.viewport{height:340px}.top{gap:8px;padding:12px}.title{font-size:14px}.properties{grid-column:auto}}
|
||||
.desktop-workspace .layout{grid-template-columns:var(--tree-width) 5px var(--property-width) 5px minmax(0,1fr);min-height:calc(100vh - 160px)}
|
||||
.desktop-workspace .layout>aside[aria-label="Model tree"]{grid-column:1;grid-row:1}.desktop-workspace .layout>aside.properties{grid-column:3;grid-row:1;border-left:0;border-right:1px solid var(--fc-border)}.desktop-workspace .layout>main.stage{grid-column:5;grid-row:1}.desktop-workspace .layout>.panel-separator[aria-label="Resize tree panel"]{grid-column:2;grid-row:1}.desktop-workspace .layout>.panel-separator[aria-label="Resize properties panel"]{grid-column:4;grid-row:1}
|
||||
.desktop-workspace .layout>aside[aria-label="Model tree"],.desktop-workspace .layout>aside.properties{border:1px solid var(--fc-border);padding-top:0}.desktop-workspace .layout>aside[aria-label="Model tree"]>h2,.desktop-workspace .layout>aside.properties>h2{margin:0 -18px 12px;padding:3px 18px;text-align:center;font-size:14px;line-height:1.3;font-weight:700;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary));border-bottom:1px solid var(--fc-border)}
|
||||
@media(max-width:650px){.layout{grid-template-columns:minmax(0,1fr)}.layout>main.stage{order:-1}.layout>aside[aria-label="Model tree"],.layout>aside.properties{order:0}.panel-separator{display:none}.application-menus{flex-wrap:nowrap;overflow-x:auto}.stage,aside{padding:14px}.viewport{height:340px}.top{gap:8px;padding:12px}.title{font-size:14px}.properties{grid-column:auto}}
|
||||
.desktop-workspace .layout{grid-template-columns:var(--tree-width) 5px minmax(0,1fr) 5px var(--property-width);grid-template-rows:minmax(0,1fr)}
|
||||
.desktop-workspace .layout>aside[aria-label="Model tree"]{grid-column:1;grid-row:1}.desktop-workspace .layout>aside.properties{grid-column:5;grid-row:1;border-right:0;border-left:1px solid var(--fc-border)}.desktop-workspace .layout>main.stage{grid-column:3;grid-row:1}.desktop-workspace .layout>.panel-separator[aria-label="Resize tree panel"]{grid-column:2;grid-row:1}.desktop-workspace .layout>.panel-separator[aria-label="Resize properties panel"]{grid-column:4;grid-row:1}
|
||||
.desktop-workspace .layout>aside[aria-label="Model tree"],.desktop-workspace .layout>aside.properties{border:1px solid var(--fc-border);padding:0}.desktop-workspace .layout>aside[aria-label="Model tree"]>h2,.desktop-workspace .layout>aside.properties>h2{margin:0 0 12px;padding:3px 18px;text-align:center;font-size:14px;line-height:1.3;font-weight:700;background:linear-gradient(to bottom,var(--fc-panel),var(--fc-primary));border-bottom:1px solid var(--fc-border);flex:0 0 auto}
|
||||
.stage-sketch-task{margin-top:12px;border:1px solid var(--fc-border);background:var(--fc-primary);padding:10px 12px;max-height:60vh;overflow:auto}
|
||||
.stage-sketch-task .task-panel>fieldset:first-of-type{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(230px,100%),1fr));gap:6px 18px;align-items:start}
|
||||
.stage-sketch-task .task-panel>fieldset{min-width:0;border:1px solid var(--fc-border);padding:10px 12px;margin:10px 0}
|
||||
@@ -1800,10 +1898,10 @@ function App() {
|
||||
.desktop-workspace .stage{background:var(--fc-primary)}.desktop-workspace .viewport{background:transparent}.application-menus,.workbench-toolbar,.document-tabs{display:flex;align-items:center;gap:4px;padding:4px 10px;background:var(--fc-menu);border-bottom:1px solid var(--fc-border);flex-wrap:wrap}.application-menus:focus-visible{border:1px solid var(--fc-accent);outline:none}
|
||||
.application-menus details,.workbench-parity-menu{position:relative}.application-menus summary,.workbench-parity-menu>summary{cursor:pointer;padding:2px 8px 3px 8px}.application-menus summary:hover,.application-menus summary:focus-visible,.application-menus details[open]>summary,.workbench-parity-menu>summary:hover,.workbench-parity-menu>summary:focus-visible{background:var(--fc-accent-bg);outline:1px solid var(--fc-accent);outline-offset:-1px}.menu-items,.workbench-parity-items{position:absolute;z-index:10;background:var(--fc-menu);padding:4px;min-width:230px;border:1px solid var(--fc-border);box-shadow:0 8px 20px #0008}.menu-items .action,.workbench-parity-subitems button{border-radius:0;margin:0;padding:4px 23px 4px 5px;background:transparent}.menu-items .action:disabled,.workbench-parity-subitems button:disabled{color:var(--fc-disabled);opacity:1;cursor:default}.menu-items .action:disabled:hover,.menu-items .action:disabled:focus-visible,.workbench-parity-subitems button:disabled:hover,.workbench-parity-subitems button:disabled:focus-visible{background:transparent;border-color:transparent}.menu-items .action:not(:disabled):hover,.menu-items .action:not(:disabled):focus-visible,.workbench-parity-subitems button:not(:disabled):hover,.workbench-parity-subitems button:not(:disabled):focus-visible{background:var(--fc-accent-bg);border-color:var(--fc-accent)}.workbench-parity-group{position:relative}.workbench-parity-group>summary{display:flex;align-items:center;justify-content:space-between;gap:12px;cursor:pointer;padding:4px 8px;white-space:nowrap}.workbench-menu-arrow{box-sizing:content-box;flex:0 0 8px;width:8px;height:8px;margin:5px;padding-left:12px;color:var(--fc-text);background:transparent}.workbench-parity-subitems{display:none;position:absolute;left:100%;top:-4px;z-index:11;min-width:260px;background:var(--fc-menu);padding:4px;border:1px solid var(--fc-border);box-shadow:0 8px 20px #0008}.workbench-parity-group[open]>.workbench-parity-subitems{display:grid;gap:1px}.workbench-parity-subitems button{display:flex;align-items:center;justify-content:space-between;gap:16px;width:100%;color:var(--fc-text);text-align:left}.workbench-parity-subitems kbd{color:#b5b5b5;font:12px ui-monospace,monospace}
|
||||
.document-tabs-viewport{display:flex;align-items:stretch;min-width:0;border-top:1px solid var(--fc-border);border-bottom:0;margin-top:12px;padding:4px 0 0;background:var(--fc-menu)}.document-tabs{flex:1 1 auto;min-width:0;gap:0;flex-wrap:nowrap;overflow-x:auto;overflow-y:hidden}.document-tabs-scroll{display:inline-flex;align-items:center;justify-content:center;flex:0 0 24px;width:24px;min-height:26px;margin:0;padding:2px;border:1px solid transparent;border-radius:0;background:var(--fc-menu);color:#888;cursor:pointer}.document-tabs-scroll:hover,.document-tabs-scroll:focus-visible{background:var(--fc-accent-hover);border-color:var(--fc-accent);color:var(--fc-text);outline:none}.document-tabs-scroll:disabled{color:var(--fc-disabled);cursor:default;opacity:.65}.document-tabs-scroll svg{width:14px;height:14px}.document-tabs .tab{display:flex;align-items:center;flex:0 0 auto;gap:6px;width:auto;margin:0;font-size:13px;border:1px solid var(--fc-border);border-radius:3px 3px 0 0;padding:4px;background:var(--fc-tab-inactive);border-bottom-color:var(--fc-border);cursor:grab}.document-tabs .tab:active{cursor:grabbing}.document-tabs .tab:hover{background:var(--fc-border-hover)}.document-tabs .tab.active{background:var(--fc-tab-active);border-color:var(--fc-border);border-bottom-color:var(--fc-tab-active);font-weight:700}.document-tabs .tab-label{min-width:0;overflow-wrap:anywhere}.document-tabs .tab-close{display:inline-flex;align-items:center;justify-content:center;flex:0 0 16px;width:16px;height:16px;margin:0;padding:0;border:1px solid transparent;border-radius:3px;background:transparent;color:#888;cursor:pointer}.document-tabs .tab-close:hover,.document-tabs .tab-close:focus-visible{background:var(--fc-accent-hover);border-color:var(--fc-accent);color:#d30000;outline:none}.document-tabs .tab-close:active{background:var(--fc-accent-hover);color:#780000}.document-tabs .tab-close:disabled{opacity:.45;cursor:default}.document-tabs .tab-close svg{width:12px;height:12px}.workbench-toolbar button{width:auto;margin:0;padding:2px 6px;border-radius:3px}.desktop-workspace .tab,.desktop-workspace .action,.desktop-workspace .actions button,.desktop-workspace .text-command{border-radius:3px}.panel-separator{position:relative;background:transparent;cursor:col-resize;touch-action:none;width:5px}.panel-separator::before{position:absolute;top:2px;bottom:2px;left:50%;width:1px;background:var(--fc-border);content:"";transform:translateX(-50%)}.panel-separator:hover::before{background:var(--fc-border-hover)}.panel-separator:focus-visible{outline:1px solid var(--fc-accent);outline-offset:-1px}.stage{padding:12px}.stage>h2{font-size:16px}.workspace-task-controls{min-width:210px;background:var(--fc-primary);border-top:1px solid var(--fc-border);margin-top:18px;padding:12px 0 0}.workspace-task-controls h2{font-size:14px;line-height:1.3;margin:0 0 10px;padding:7px 0;border-bottom:1px solid var(--fc-border)}.workspace-task-controls button{margin-right:6px}.developer-panel{border:1px dashed var(--fc-border);padding:12px}.properties{font-size:14px}
|
||||
@media(max-width:1100px){.desktop-workspace .layout{grid-template-columns:210px 5px 270px 5px minmax(0,1fr)}.desktop-workspace .layout>aside.properties{grid-column:3;grid-row:1}.desktop-workspace .layout>main.stage{grid-column:5;grid-row:1}.panel-separator[aria-label="Resize properties panel"]{display:block}}
|
||||
@media(max-width:800px){.desktop-workspace .layout{display:flex;flex-direction:column}.panel-separator{display:none}.desktop-workspace aside{max-height:45vh}.viewport{height:340px}}
|
||||
@media(max-width:1100px){.desktop-workspace .layout{grid-template-columns:210px 5px minmax(0,1fr) 5px 270px}.desktop-workspace .layout>aside.properties{grid-column:5;grid-row:1}.desktop-workspace .layout>main.stage{grid-column:3;grid-row:1}.panel-separator[aria-label="Resize properties panel"]{display:block}}
|
||||
@media(max-width:800px){.desktop-workspace .layout{display:flex;flex-direction:column;overflow:visible}.desktop-workspace .layout>main.stage{order:-1}.panel-separator{display:none}.desktop-workspace aside{max-height:45vh}.viewport{height:340px}}
|
||||
.application-menus .menu-items>label{display:flex;align-items:center;gap:2px;min-height:22px;padding:4px 23px 4px 5px;color:var(--fc-text);cursor:pointer;white-space:nowrap}.application-menus .menu-items>label:hover{background:var(--fc-accent-hover)}.application-menus .menu-items>label input[type=checkbox]{appearance:none;box-sizing:border-box;width:12px;height:12px;flex:0 0 12px;margin:2px;border:1px solid var(--fc-border);border-radius:3px;background:var(--fc-primary);color-scheme:dark}.application-menus .menu-items>label input[type=checkbox]:hover{border-color:var(--fc-border-hover)}.application-menus .menu-items>label input[type=checkbox]:focus-visible{outline:1px solid var(--fc-accent);outline-offset:1px}.application-menus .menu-items>label input[type=checkbox]:checked{background:linear-gradient(135deg,transparent 42%,#fff 42% 56%,transparent 56%) 0 4px/6px 6px no-repeat,linear-gradient(45deg,transparent 41%,#fff 41% 56%,transparent 56%) 5px 1px/6px 8px no-repeat,var(--fc-primary)}.application-menus .menu-items>label input[type=checkbox]:disabled{background:var(--fc-menu);border-color:var(--fc-border);opacity:.65}
|
||||
@media(max-width:650px){.desktop-workspace .layout>aside[aria-label="Model tree"]>h2,.desktop-workspace .layout>aside.properties>h2{margin-right:-14px;margin-left:-14px;padding-right:14px;padding-left:14px}.menu-items,.workbench-parity-items{position:fixed;left:12px;right:12px;min-width:0;max-width:calc(100vw - 24px);box-sizing:border-box}.workbench-parity-subitems{left:auto;right:0;top:100%;width:100%;min-width:0;max-height:calc(100vh - 120px);overflow:auto}.document-tabs{flex-wrap:nowrap;overflow:auto}.document-tabs .tab{flex-shrink:0}.document-tabs-scroll{flex-basis:22px;width:22px}}
|
||||
@media(max-width:650px){.desktop-workspace .layout>aside[aria-label="Model tree"]>h2,.desktop-workspace .layout>aside.properties>h2{margin:0 0 12px;padding:3px 14px}.menu-items,.workbench-parity-items{position:fixed;left:12px;right:12px;min-width:0;max-width:calc(100vw - 24px);box-sizing:border-box}.workbench-parity-subitems{left:auto;right:0;top:100%;width:100%;min-width:0;max-height:calc(100vh - 120px);overflow:auto}.document-tabs{flex-wrap:nowrap;overflow:auto}.document-tabs .tab{flex-shrink:0}.document-tabs-scroll{flex-basis:22px;width:22px}}
|
||||
`}</style><style>{`.start-dialog{box-sizing:border-box;width:min(1100px,94vw);max-height:88vh;padding:0;border:1px solid var(--fc-border);border-radius:6px;background:var(--fc-panel);color:var(--fc-text);overflow:auto}.viewport-hint{margin:2px 0 0;font-size:11px;line-height:1.4;color:var(--fc-text-muted,#8a949e)}@media(max-width:650px){.viewport-hint{font-size:10px}}.viewport-transform-bar{display:flex;flex-wrap:wrap;align-items:center;gap:4px;margin-top:2px}.viewport-transform-bar .tool{min-width:52px}.placement-readout{font-size:11px;color:var(--fc-text-muted,#8a949e);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.frame-dialog{box-sizing:border-box;width:min(520px,94vw);padding:16px;border:1px solid var(--fc-border);border-radius:6px;background:var(--fc-panel);color:var(--fc-text)}.frame-dialog h3{margin:0 0 6px;font-size:14px}.frame-dialog-note{margin:0 0 10px;font-size:11px;color:var(--fc-text-muted,#8a949e)}.frame-dialog fieldset{margin:0 0 10px;padding:6px 8px;border:1px solid var(--fc-border);border-radius:4px}.frame-dialog .position-fields{display:flex;gap:6px}.frame-dialog .position-fields input{width:100%}.frame-dialog-actions{display:flex;flex-wrap:wrap;gap:6px;justify-content:flex-end}.frame-dialog::backdrop{background:rgba(0,0,0,.55)}@media(max-width:650px){.placement-readout{width:100%;white-space:normal}}.start-dialog::backdrop{background:rgba(0,0,0,.55)}.start-dialog section[aria-label="Start"][data-start-view]{margin:0}.menu-items hr,.workbench-parity-items hr{height:1px;margin:4px 0;border:0;background:var(--fc-border)}.desktop-workspace .action{box-sizing:border-box;min-width:80px;padding:3px 12px;background:linear-gradient(to bottom,#2b2b2b,#191919);border:1px solid #3f3f3f;color:#fff}.desktop-workspace .action:hover:not(:disabled){background:#575757;border-color:#3f3f3f}.desktop-workspace .action:focus-visible{border-color:#66c7d5;outline:none}.desktop-workspace .action:active:not(:disabled){background:linear-gradient(to bottom,#191919,#2b2b2b);border-color:#575757}.desktop-workspace .action:disabled{background:#0f0f0f;color:#858585;border-color:#3f3f3f;opacity:1}.desktop-workspace [role="toolbar"][aria-label="Cell text style"] button[aria-pressed="true"]{appearance:none;box-sizing:border-box;min-width:80px;padding:3px 12px;background:linear-gradient(to bottom,#242424,#191919);border:1px solid #575757;border-radius:3px;color:#fff}.desktop-workspace [role="toolbar"][aria-label="Cell text style"] button[aria-pressed="true"]:hover:not(:disabled){background:#575757;border-color:#66c7d5}.desktop-workspace [role="toolbar"][aria-label="Cell text style"] button[aria-pressed="true"]:active:not(:disabled){background:#2b2b2b;border-color:#3f3f3f}.desktop-workspace [role="toolbar"][aria-label="Cell text style"] button[aria-pressed="true"]:disabled{background:#0f0f0f;color:#858585;border-color:#3f3f3f;opacity:1}`}</style><header className="top"><span className="brand">FC</span><span>FreeCAD 1.2 Web</span><strong className="title">{active || "Workspace"}</strong></header>
|
||||
{startVisible && <dialog className="start-dialog" aria-label="Start dialog"
|
||||
ref={node => { if (node && !node.open) node.showModal(); }}
|
||||
@@ -1882,7 +1980,7 @@ function App() {
|
||||
}
|
||||
setWorkspaceTask(""); setViewCommand(""); setWorkbenches(previous => ({ ...previous, [active]: next }));
|
||||
void startParameters(router, { LastModule: `${next}Workbench` }, true).catch(error => setStatus(String(error)));
|
||||
}}><option>Part</option><option>Sketcher</option><option>PartDesign</option><option>Spreadsheet</option><option>Surface</option><option>Assembly</option><option>Draft</option><option>Architecture</option><option>BIM</option><option>CAM</option><option>Cloud</option><option>Fem</option><option>Help</option><option>Import</option><option>Inspection</option><option>JtReader</option><option>Material</option><option>Measure</option><option>Mesh</option><option>MeshPart</option><option>Points</option><option>ReverseEngineering</option><option>Robot</option><option>Sandbox</option><option>Start</option><option>TechDraw</option><option>Test</option><option>Tux</option><option disabled={!nativeDocuments.current.has(active)}>TemplatePyMod</option></select></label>
|
||||
}}><option>Part</option><option>Sketcher</option><option>PartDesign</option><option>Spreadsheet</option><option>Surface</option><option>Assembly</option><option>Draft</option><option>BIM</option><option>CAM</option><option>Cloud</option><option>Fem</option><option>Help</option><option>Import</option><option>Inspection</option><option>JtReader</option><option>Material</option><option>Measure</option><option>Mesh</option><option>MeshPart</option><option>Plot</option><option>Points</option><option>ReverseEngineering</option><option>Robot</option><option>Sandbox</option><option>Show</option><option>Start</option><option>TechDraw</option><option>Test</option><option>Tux</option><option>Web</option><option disabled={!nativeDocuments.current.has(active)}>TemplatePyMod</option></select></label>
|
||||
</ToolbarGroup>
|
||||
<ParityWorkbenchToolbars workbench={workbench} onCommand={executeManifestCommand} />
|
||||
{csvPanel && <SpreadsheetCsvPanel mode={csvPanel.mode} selected={csvPanel.selected}
|
||||
@@ -1922,13 +2020,18 @@ function App() {
|
||||
} finally { setImporting(false); }
|
||||
}} />}
|
||||
<ToolbarGroup name="Spreadsheet tools">
|
||||
{workbench === "Spreadsheet" && <><button disabled={importing || !!csvPanel || !active} onClick={() => void createSheet(undefined, undefined, "Spreadsheet_Import").catch(error => setStatus(String(error)))}>Import CSV…</button>
|
||||
<button disabled={importing || !!csvPanel || !active} onClick={() => void createSheet(undefined, undefined, "Spreadsheet_Export").catch(error => setStatus(String(error)))}>Export CSV…</button></>}
|
||||
{workbench === "Spreadsheet" && <button disabled={importing || !active} onClick={() => void createSheet().catch(error => setStatus(String(error)))}>Create spreadsheet</button>}
|
||||
{workbench === "Spreadsheet" && <SpreadsheetPanel
|
||||
busy={importing}
|
||||
csvOpen={Boolean(csvPanel)}
|
||||
hasDocument={Boolean(active)}
|
||||
onImportCsv={() => void createSheet(undefined, undefined, "Spreadsheet_Import").catch(error => setStatus(String(error)))}
|
||||
onExportCsv={() => void createSheet(undefined, undefined, "Spreadsheet_Export").catch(error => setStatus(String(error)))}
|
||||
onCreateSheet={() => void createSheet().catch(error => setStatus(String(error)))}
|
||||
/>}
|
||||
</ToolbarGroup>
|
||||
{workbench === "Part" && <PartWorkbenchToolbars disabled={partActionDisabled} activate={activatePartAction} currentTask={workspaceTask} />}
|
||||
<div className="layout" style={{ "--tree-width": `${treeWidth}px`, "--property-width": `${propertyWidth}px` } as React.CSSProperties}><aside aria-label="Model tree">
|
||||
<h2>Objects</h2><DocumentTree nodes={treeNodes} selected={String(selectedObjects[active] ?? "")} label="Document objects" busy={importing} onSelect={id => selectPrimaryObject(id)} onToggleVisibility={(id, visible) => updateProperty(id, "Visibility", visible)} />{!objects.length ? <p className="status">No objects</p> : null}
|
||||
<h2>Objects</h2><div className="pane-scroll" aria-label="Model tree objects"><DocumentTree nodes={treeNodes} selected={String(selectedObjects[active] ?? "")} label="Document objects" busy={importing} onSelect={id => selectPrimaryObject(id)} onToggleVisibility={(id, visible) => updateProperty(id, "Visibility", visible)} />{!objects.length ? <p className="status">No objects</p> : null}
|
||||
{active && !designDocuments.current.has(active) && <details><summary>New Group</summary>
|
||||
<WebGroupTask key={active} router={router} documentId={nativeName(active)} runtimeOwner="DocumentProbe"
|
||||
disabled={importing} onBusyChange={setImporting}
|
||||
@@ -1940,7 +2043,7 @@ function App() {
|
||||
setStatus(`Created ${value.createdObject}`);
|
||||
}}
|
||||
onSelect={object => setSelectedObjects(previous => ({ ...previous, [active]: `native:${object}` }))} />
|
||||
</details>}
|
||||
</details>}</div>
|
||||
</aside>{panelSeparator("tree")}<main className="stage"><h2>{active || "Workspace"}</h2>
|
||||
{workbench === "Spreadsheet" && (selectedObject?.type === "Spreadsheet::Sheet" ? <SpreadsheetSheetEditor
|
||||
key={`${active}:${selectedObject.id}`} sheet={String(selectedObject.properties.Label)}
|
||||
@@ -2052,6 +2155,8 @@ function App() {
|
||||
onClick={() => setReferenceOpen(open => !open)}>参考模型 GLB</button>
|
||||
<button type="button" className="action" aria-pressed={lineReferenceOpen} aria-label="Toggle line reference viewer"
|
||||
onClick={() => setLineReferenceOpen(open => !open)}>产线参考模型</button>
|
||||
<button type="button" className="action" aria-pressed={abbReferenceOpen} aria-label="Toggle ABB IRB 120 reference viewer"
|
||||
onClick={() => setAbbReferenceOpen(open => !open)}>ABB 参考模型</button>
|
||||
{viewCommand && <WebViewTask key={active} router={router} command={viewCommand} documentId={nativeName(active)}
|
||||
runtimeOwner="DocumentProbe" disabled={importing}
|
||||
selection={compoundSelection.map(object => ({ documentId: nativeName(active), object }))}
|
||||
@@ -2082,7 +2187,9 @@ function App() {
|
||||
if (result.file) void listDocumentFiles().then(files => { setSavedDocuments(files); window.dispatchEvent(new Event("freecad-document-persistence")); }).catch(error => setStatus(String(error)));
|
||||
}} />
|
||||
</>}
|
||||
<div ref={viewportRef} style={testDocuments.current.has(active) || isExternalWorkbench(workbench) ? { display: "none" } : undefined} className="viewport" aria-label="Imported native 3D view" />
|
||||
{/* Spreadsheet has no 3D scene; keeping the empty viewport only pushes the
|
||||
grid down on narrow screens (UI-GAP-14). */}
|
||||
<div ref={viewportRef} style={testDocuments.current.has(active) || isExternalWorkbench(workbench) || workbench === "Spreadsheet" ? { display: "none" } : undefined} className="viewport" aria-label="Imported native 3D view" />
|
||||
{workbench === "Part" && active && workspaceTask === "sketcher-new-sketch" && <div className="stage-sketch-task">
|
||||
<PartNewSketchTask
|
||||
key={active} documentId={nativeName(active)} snapshot={partSnapshots[active]} selected={compoundSelection}
|
||||
@@ -2102,7 +2209,8 @@ function App() {
|
||||
return result;
|
||||
}} />
|
||||
</div>}
|
||||
{isExternalWorkbench(workbench) && <WorkbenchFrame workbench={workbench} />}
|
||||
{isExternalWorkbench(workbench) && <WorkbenchFrame workbench={workbench} native={nativeWorkbench}
|
||||
router={nativeWorkbench ? router : undefined} documentId={nativeWorkbench ? nativeName(active) : undefined} />}
|
||||
<div className="viewport-transform-bar" role="toolbar" aria-label="Object transform">
|
||||
{([["translate", "移动"], ["rotate", "旋转"], ["off", "关闭"]] as const).map(([mode, label]) => (
|
||||
<button key={mode} className="tool" title={`${label}控制器`} aria-label={`${label}控制器`} aria-pressed={transformMode === mode}
|
||||
@@ -2134,28 +2242,41 @@ function App() {
|
||||
<p className="viewport-hint" aria-label="Navigation hints">中键按住平移 · 滚轮缩放 · 中键加左键(或右键加 Shift)旋转 · 局部坐标默认锁定,改写请用「局部坐标…」</p>
|
||||
{frameEditor && <dialog className="frame-dialog" aria-label="Local frame editor"
|
||||
ref={node => { if (node && !node.open) node.showModal(); }}
|
||||
onClose={() => setFrameEditor(null)} onCancel={() => setFrameEditor(null)}>
|
||||
onClose={() => { cancelPlacementPreview(); setFrameEditor(null); }} onCancel={() => { cancelPlacementPreview(); setFrameEditor(null); }}>
|
||||
<h3>局部坐标:{frameEditor.object}</h3>
|
||||
<p className="frame-dialog-note">原点与欧拉角(XYZ°,先绕 X 再 Y 再 Z)。应用后写入模型 Placement,控制器姿态同步刷新。</p>
|
||||
<fieldset><legend>原点</legend><div className="position-fields">{["X", "Y", "Z"].map((axis, index) => (
|
||||
<label key={axis}>{axis}<input type="number" step="1" aria-label={`Frame origin ${axis}`} value={frameEditor.position[index]}
|
||||
onChange={event => setFrameEditor(current => current ? { ...current, position: current.position.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number] } : current)} /></label>))}</div></fieldset>
|
||||
onChange={event => { if (!frameEditor) return;
|
||||
const next = { ...frameEditor, position: frameEditor.position.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number] };
|
||||
setFrameEditor(next); schedulePlacementPreview({ position: next.position, ...axisAngleFromEuler(next.euler) }); }} /></label>))}</div></fieldset>
|
||||
<fieldset><legend>欧拉角</legend><div className="position-fields">{["X", "Y", "Z"].map((axis, index) => (
|
||||
<label key={axis}>{axis}<input type="number" step="15" aria-label={`Frame euler ${axis}`} value={frameEditor.euler[index]}
|
||||
onChange={event => setFrameEditor(current => current ? { ...current, euler: current.euler.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number] } : current)} /></label>))}</div></fieldset>
|
||||
onChange={event => { if (!frameEditor) return;
|
||||
const next = { ...frameEditor, euler: frameEditor.euler.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number] };
|
||||
setFrameEditor(next); schedulePlacementPreview({ position: next.position, ...axisAngleFromEuler(next.euler) }); }} /></label>))}</div></fieldset>
|
||||
<div className="frame-dialog-actions">
|
||||
<button className="action" aria-label="应用局部坐标" onClick={() => {
|
||||
const editor = frameEditor;
|
||||
const { axis, angle } = axisAngleFromEuler(editor.euler);
|
||||
setFrameEditor(null);
|
||||
cancelPlacementPreview();
|
||||
void editNative("setPlacement", { object: editor.object, position: editor.position, axis, angle } as never);
|
||||
}}>应用到模型</button>
|
||||
<button className="action" aria-label="还原局部坐标" onClick={() => setFrameEditor({
|
||||
object: frameEditor.object,
|
||||
position: [placementXyz[0], placementXyz[1], placementXyz[2]],
|
||||
euler: [placementEuler[0], placementEuler[1], placementEuler[2]],
|
||||
})}>还原</button>
|
||||
<button className="action" aria-label="旋转归零" onClick={() => setFrameEditor(current => current ? { ...current, euler: [0, 0, 0] } : current)}>旋转归零</button>
|
||||
<button className="action" aria-label="还原局部坐标" onClick={() => {
|
||||
cancelPlacementPreview();
|
||||
setFrameEditor({
|
||||
object: frameEditor.object,
|
||||
position: [placementXyz[0], placementXyz[1], placementXyz[2]],
|
||||
euler: [placementEuler[0], placementEuler[1], placementEuler[2]],
|
||||
});
|
||||
}}>还原</button>
|
||||
<button className="action" aria-label="旋转归零" onClick={() => {
|
||||
if (!frameEditor) return;
|
||||
const next = { ...frameEditor, euler: [0, 0, 0] as [number, number, number] };
|
||||
setFrameEditor(next);
|
||||
schedulePlacementPreview({ position: next.position, ...axisAngleFromEuler(next.euler) });
|
||||
}}>旋转归零</button>
|
||||
<button className="action" aria-label="关闭局部坐标编辑器" onClick={() => setFrameEditor(null)}>关闭</button>
|
||||
</div>
|
||||
</dialog>}
|
||||
@@ -2185,7 +2306,7 @@ function App() {
|
||||
onClick={() => void exportSelectedShape()}><ToolIcon nodes={Download} /></button>
|
||||
<button className="action" disabled={!objects.length} onClick={() => renderBridge.fitDocument()}>适合全部对象</button>
|
||||
<button className="action" disabled={!active || importing} onClick={() => void saveFcstd()}>保存 FCStd 到 OPFS</button>
|
||||
<button className="action" disabled={!nativeBytes} onClick={downloadFcstd}>下载 native FCStd</button>
|
||||
<button className="action" disabled={!nativeBytes} onClick={() => void downloadFcstd()}>下载 native FCStd</button>
|
||||
<label>OPFS 导出件<select className="saved-documents" aria-label="OPFS export"
|
||||
value={opfsExportName} onChange={event => setOpfsExportName(event.target.value)}>
|
||||
<option value="">选择导出件</option>{opfsExports.map(name => <option key={name} value={name}>{name}</option>)}
|
||||
@@ -2234,7 +2355,7 @@ function App() {
|
||||
{documentTabsOverflow && <button type="button" className="document-tabs-scroll" aria-label="Scroll document tabs right" title="Scroll document tabs right"
|
||||
disabled={!documentTabsCanScrollRight} onClick={() => documentTabsRef.current?.scrollBy({ left: Math.max(120, documentTabsRef.current.clientWidth * 0.75), behavior: "smooth" })}><ToolIcon nodes={ChevronRight} /></button>}
|
||||
</div>
|
||||
</main>{panelSeparator("properties")}<aside className="properties" aria-label="Object Properties"><h2>Properties</h2>
|
||||
</main>{panelSeparator("properties")}<aside className="properties" aria-label="Object Properties"><h2>Properties</h2><div className="pane-scroll" aria-label="Object properties body">
|
||||
{selectedObject ? <>
|
||||
{(nativeDocuments.current.has(active) || jtDocuments.current.has(active)) && !!selectedObject.properties.NativeName && <button disabled={importing || !!workspaceTask} onClick={() => { setWorkspaceTask("position"); setStatus("Edit object position"); }}>Position</button>}
|
||||
<h3 className="property-group-title">View</h3><label><span>Label</span><input aria-label="Object Label" name="Label" disabled={designDocuments.current.has(active)} value={String(selectedObject.properties.Label ?? selectedObject.id)} onChange={event => updateProperty(selectedObject.id, "Label", event.target.value)} onBlur={event => void commitNativeLabel(event.currentTarget.value)} /></label>
|
||||
@@ -2255,8 +2376,13 @@ function App() {
|
||||
{selectedObject.type === "Part::Box" && <>
|
||||
<h3 className="property-group-title">Data</h3>
|
||||
{(["Length", "Width", "Height"] as const).map((name, index) => { const expression = (selectedObject.properties.primitiveExpressions as Record<string, unknown> | undefined)?.[name]; return <label key={name} data-property-editor-row={name}><span>{name}</span><input className={expression ? "property-expression-value" : undefined} aria-label={`Property ${name}`} aria-readonly={expression ? "true" : undefined} title={expression ? `Expression: ${String(expression)}` : undefined} type="number" readOnly={Boolean(expression)} min="0.001" step="any" value={boxDimensions[index]}
|
||||
onChange={event => setBoxDimensions(previous => previous.map((value, position) => position === index ? Number(event.target.value) : value) as [number, number, number])}
|
||||
onBlur={() => { if (!expression && !importing && selectedObject.properties.NativeName) void createOrEditBox(true); }} /></label>; })}
|
||||
onChange={event => {
|
||||
const next = boxDimensions.map((value, position) => position === index ? Number(event.target.value) : value) as [number, number, number];
|
||||
setBoxDimensions(next);
|
||||
if (!expression) propertyCommit.schedule("box", () => void createOrEditBox(true, { live: true, dimensions: next }));
|
||||
}}
|
||||
onKeyDown={event => { if (event.key === "Enter" && !expression) { event.preventDefault(); propertyCommit.flush("box"); } }}
|
||||
onBlur={() => { if (!expression && !importing && selectedObject.properties.NativeName) propertyCommit.flush("box"); }} /></label>; })}
|
||||
</>}
|
||||
{selectedPrimitiveDefinition && selectedObject.type !== "Part::Box" && <>
|
||||
<h3 className="property-group-title">Data</h3>
|
||||
@@ -2264,8 +2390,13 @@ function App() {
|
||||
<input className={expression ? "property-expression-value" : undefined} aria-label={`Property ${field}`} aria-readonly={expression ? "true" : undefined} title={expression ? `Expression: ${String(expression)}` : undefined} type="number" readOnly={Boolean(expression)} min={field === "Angle1" || field === "Angle2" ? (selectedPrimitive === "Sphere" ? -90 : -180) : selectedPrimitive === "Cone" && field.startsWith("Radius") ? 0 : 0.001}
|
||||
max={field === "Angle1" || field === "Angle2" ? (selectedPrimitive === "Sphere" ? 90 : 180) : field.startsWith("Angle") ? 360 : undefined}
|
||||
step={field.startsWith("Angle") ? 1 : 0.5} value={primitiveParameters[field] ?? selectedPrimitiveDefinition.defaults[field]}
|
||||
onChange={event => setPrimitiveParameters(previous => ({ ...previous, [field]: Number(event.target.value) }))}
|
||||
onBlur={() => { if (!importing && selectedObject.properties.NativeName) void createOrEditPrimitive(true); }} /></label>; })}
|
||||
onChange={event => {
|
||||
const next = { ...primitiveParameters, [field]: Number(event.target.value) };
|
||||
setPrimitiveParameters(next);
|
||||
if (!expression) propertyCommit.schedule("primitive", () => void createOrEditPrimitive(true, { live: true, parameters: next }));
|
||||
}}
|
||||
onKeyDown={event => { if (event.key === "Enter" && !expression) { event.preventDefault(); propertyCommit.flush("primitive"); } }}
|
||||
onBlur={() => { if (!expression && !importing && selectedObject.properties.NativeName) propertyCommit.flush("primitive"); }} /></label>; })}
|
||||
</>}
|
||||
{["Part::Fuse", "Part::Cut", "Part::Common"].includes(selectedObject.type) && <>
|
||||
<h3 className="property-group-title">Data</h3>
|
||||
@@ -2957,12 +3088,19 @@ function App() {
|
||||
})()} />}
|
||||
{workspaceTask === "position" && <fieldset className="primitive-editor" disabled={importing || !selectedObject?.properties.NativeName}><legend>Placement</legend>
|
||||
<div className="position-fields">{["X", "Y", "Z"].map((axis, index) => <label key={axis}>{axis}<input type="number" step="1" aria-label={`Position ${axis}`} value={position[index]}
|
||||
onChange={event => setPosition(previous => previous.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number])} /></label>)}</div>
|
||||
onChange={event => {
|
||||
const next = position.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number];
|
||||
setPosition(next); schedulePlacementPreview({ position: next, axis: rotationAxis, angle: rotationAngle });
|
||||
}} /></label>)}</div>
|
||||
<div className="position-fields">{["X", "Y", "Z"].map((axisName, index) => <label key={axisName}>轴 {axisName}<input type="number" step="0.5" aria-label={`Rotation axis ${axisName}`} value={rotationAxis[index]}
|
||||
onChange={event => setRotationAxis(previous => previous.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number])} /></label>)}</div>
|
||||
onChange={event => {
|
||||
const next = rotationAxis.map((value, i) => i === index ? Number(event.target.value) : value) as [number, number, number];
|
||||
setRotationAxis(next); schedulePlacementPreview({ position, axis: next, angle: rotationAngle });
|
||||
}} /></label>)}</div>
|
||||
<label>角度°<input type="number" step="1" aria-label="Rotation angle" value={rotationAngle}
|
||||
onChange={event => setRotationAngle(Number(event.target.value))} /></label>
|
||||
onChange={event => { const next = Number(event.target.value); setRotationAngle(next); schedulePlacementPreview({ position, axis: rotationAxis, angle: next }); }} /></label>
|
||||
<button className="tool" title="应用位置与旋转" aria-label="应用位置与旋转" onClick={() => {
|
||||
cancelPlacementPreview();
|
||||
const object = String(selectedObject?.properties.NativeName);
|
||||
if (jtDocuments.current.has(active)) {
|
||||
const names = (compoundSelections[active]?.length ? compoundSelections[active] : [object]).map(value => value.replace(/^native:/, ""));
|
||||
@@ -3051,8 +3189,9 @@ function App() {
|
||||
<div className="stat"><strong>{active || "none"}</strong><small>{objects.length} objects</small></div>
|
||||
<div className="stat"><strong>Recent files</strong><small>{store.recent().length}</small></div>
|
||||
{developerMode && <div className="stat"><strong>Checkpoint</strong><small>localStorage metadata only</small></div>}
|
||||
</aside>{referenceOpen && <DeltaReferencePanel onClose={() => setReferenceOpen(false)} />}
|
||||
</div></aside>{referenceOpen && <DeltaReferencePanel onClose={() => setReferenceOpen(false)} />}
|
||||
{parityTask && <TaskFrame module={parityTask.module} command={parityTask.command}
|
||||
router={router} documentId={nativeName(active || initialDocumentId)}
|
||||
onClose={() => setParityTask(null)} />}
|
||||
{preferencesOpen && <PreferencesDialog onClose={() => setPreferencesOpen(false)} onApply={async preferences => {
|
||||
if (!active) return;
|
||||
@@ -3074,7 +3213,8 @@ function App() {
|
||||
selection={compoundSelection.map(name => String(objects.find(object => String(object.properties.NativeName) === name)?.properties.Label ?? name))}
|
||||
onClose={() => setBottomDockOpen(false)} />}
|
||||
<ShortcutManager onCommand={executeManifestCommand} />
|
||||
{lineReferenceOpen && <LineReferencePanel onClose={() => setLineReferenceOpen(false)} />}</div><footer className="desktop-status-bar" aria-label="Status bar"><p role="status" data-import-phase={importPhase} className={`status ${response?.kind === "error" ? "error" : response?.kind === "result" ? "ok" : ""}`}>{status}</p></footer></PersistentToolbarWorkspace></div>;
|
||||
{lineReferenceOpen && <LineReferencePanel onClose={() => setLineReferenceOpen(false)} />}
|
||||
{abbReferenceOpen && <Abb120ReferencePanel onClose={() => setAbbReferenceOpen(false)} />}</div><footer className="desktop-status-bar" aria-label="Status bar"><p role="status" data-import-phase={importPhase} className={`status ${response?.kind === "error" ? "error" : response?.kind === "result" ? "ok" : ""}`}>{status}</p></footer></PersistentToolbarWorkspace></div>;
|
||||
}
|
||||
|
||||
installNavigation("project", readNavigationContext());
|
||||
|
||||
@@ -1,24 +1,48 @@
|
||||
import React from "react";
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import { WorkbenchShell } from "../workbench-shell.js";
|
||||
import type { WebModuleRouter } from "../module-router.js";
|
||||
|
||||
export function TaskFrame({ module, command, onClose }: {
|
||||
export function TaskFrame({ module, command, router, documentId, onClose }: {
|
||||
module: string;
|
||||
command: string;
|
||||
/** Shared router from the host shell; omitted means the task frame owns one. */
|
||||
router?: WebModuleRouter;
|
||||
/** Active document handed to the embedded workbench. */
|
||||
documentId?: string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const src = `/workbench.html?module=${encodeURIComponent(module)}&command=${encodeURIComponent(command)}`;
|
||||
return <div className="parity-task-frame" role="dialog" aria-label={`${module} task: ${command}`}>
|
||||
const dialogRef = useRef<HTMLDivElement | null>(null);
|
||||
const closeRef = useRef(onClose);
|
||||
closeRef.current = onClose;
|
||||
// Escape closes the task the same way it closes a desktop task panel, and the
|
||||
// frame takes focus so keyboard events do not stay with the shell behind it.
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape") return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
closeRef.current();
|
||||
};
|
||||
document.addEventListener("keydown", onKeyDown, true);
|
||||
dialogRef.current?.focus();
|
||||
return () => document.removeEventListener("keydown", onKeyDown, true);
|
||||
}, [module, command]);
|
||||
return <div ref={dialogRef} className="parity-task-frame" role="dialog" aria-modal="true"
|
||||
tabIndex={-1} aria-label={`${module} task: ${command}`}>
|
||||
<style>{`
|
||||
.parity-task-frame{position:fixed;inset:0;background:#000b;z-index:80;display:flex;align-items:center;justify-content:center;padding:20px}
|
||||
.parity-task-frame:focus{outline:none}
|
||||
.parity-task-frame>section{width:min(1280px,96vw);height:min(860px,92vh);background:#0f1419;border:1px solid #3f3f3f;border-radius:8px;display:flex;flex-direction:column;overflow:hidden}
|
||||
.parity-task-frame header{display:flex;align-items:center;gap:10px;padding:8px 12px;background:#1b242c;border-bottom:1px solid #3f3f3f;color:#dbe6ee;font:13px system-ui,"Noto Sans SC",sans-serif}
|
||||
.parity-task-frame header strong{font-size:13px}
|
||||
.parity-task-frame header button{margin-left:auto;background:#2b2b2b;color:#dbe6ee;border:1px solid #555;border-radius:4px;padding:3px 10px;cursor:pointer}
|
||||
.parity-task-frame iframe{flex:1;width:100%;border:0;background:#0f1419}
|
||||
.parity-task-frame .fc-workbench-embed{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:hidden}
|
||||
`}</style>
|
||||
<section>
|
||||
<header><strong>{module} · {command}</strong><span style={{ color: "#93a6b3" }}>任务桥(复用工作台任务面板)</span>
|
||||
<button type="button" aria-label="Close task frame" onClick={onClose}>关闭</button></header>
|
||||
<iframe title={`${module} ${command} task`} src={src} />
|
||||
<WorkbenchShell module={module} command={command} router={router} documentId={documentId} standalone={false} />
|
||||
</section>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,28 @@
|
||||
import React from "react";
|
||||
import { WorkbenchShell } from "../workbench-shell.js";
|
||||
import { LOCAL_WORKBENCHES } from "../workbenches/registry.js";
|
||||
import type { WebModuleRouter } from "../module-router.js";
|
||||
|
||||
const LOCAL_WORKBENCHES = new Set(["Part", "Sketcher", "PartDesign", "Spreadsheet"]);
|
||||
export const isExternalWorkbench = (workbench: string) => !LOCAL_WORKBENCHES.has(workbench);
|
||||
|
||||
export function WorkbenchFrame({ workbench }: { workbench: string }) {
|
||||
return <div className="workbench-frame" aria-label={`${workbench} workbench workspace`}>
|
||||
export function WorkbenchFrame({ workbench, native, router, documentId, onModuleChange }: {
|
||||
workbench: string;
|
||||
/** Render the workbench in-process instead of embedding /workbench.html in an iframe. */
|
||||
native?: boolean;
|
||||
/** Shared router for the native path; omitted means the shell owns its own. */
|
||||
router?: WebModuleRouter;
|
||||
/** Active document handed to the native workbench. */
|
||||
documentId?: string;
|
||||
onModuleChange?: (module: string) => void;
|
||||
}) {
|
||||
return <div className="workbench-frame" data-native={native ? "1" : "0"} aria-label={`${workbench} workbench workspace`}>
|
||||
<style>{`
|
||||
.workbench-frame{flex:1;min-height:0;display:flex;border-top:1px solid #2a3a45;background:#0f1419}
|
||||
.workbench-frame iframe{flex:1;width:100%;border:0;background:#0f1419}
|
||||
.workbench-frame .fc-workbench-embed{flex:1 1 auto;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:hidden}
|
||||
`}</style>
|
||||
<iframe title={`${workbench} workbench`} src={`/workbench.html?module=${encodeURIComponent(workbench)}`} />
|
||||
{native
|
||||
? <WorkbenchShell module={workbench} documentId={documentId} router={router} standalone={false} onModuleChange={onModuleChange} />
|
||||
: <iframe title={`${workbench} workbench`} src={`/workbench.html?module=${encodeURIComponent(workbench)}`} />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
52
web/src/use-debounced-commit.ts
Normal file
52
web/src/use-debounced-commit.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
type Entry = { timer: number; run: () => unknown };
|
||||
|
||||
/**
|
||||
* Debounces commits that are triggered by typing.
|
||||
*
|
||||
* Desktop FreeCAD applies a property as soon as the spin box loses focus, so the
|
||||
* user sees the model change only after leaving the field. Here the same commit
|
||||
* is scheduled ~250 ms after the last keystroke, and `flush` runs it immediately
|
||||
* on Enter/blur. Keys are scoped (e.g. `box:<doc>:<object>`) so a pending timer
|
||||
* for one object can never commit into another.
|
||||
*/
|
||||
export function useDebouncedCommit(defaultDelay = 250) {
|
||||
const entries = useRef(new Map<string, Entry>());
|
||||
|
||||
const cancel = (key: string) => {
|
||||
const entry = entries.current.get(key);
|
||||
if (!entry) return;
|
||||
window.clearTimeout(entry.timer);
|
||||
entries.current.delete(key);
|
||||
};
|
||||
|
||||
const cancelAll = () => {
|
||||
for (const key of [...entries.current.keys()]) cancel(key);
|
||||
};
|
||||
|
||||
const flush = (key: string) => {
|
||||
const entry = entries.current.get(key);
|
||||
if (!entry) return;
|
||||
window.clearTimeout(entry.timer);
|
||||
entries.current.delete(key);
|
||||
void entry.run();
|
||||
};
|
||||
|
||||
const flushPrefix = (prefix: string) => {
|
||||
for (const key of [...entries.current.keys()]) if (key.startsWith(prefix)) flush(key);
|
||||
};
|
||||
|
||||
const schedule = (key: string, run: () => unknown, delay = defaultDelay) => {
|
||||
cancel(key);
|
||||
const timer = window.setTimeout(() => {
|
||||
entries.current.delete(key);
|
||||
void run();
|
||||
}, delay);
|
||||
entries.current.set(key, { timer, run });
|
||||
};
|
||||
|
||||
useEffect(() => cancelAll, []);
|
||||
|
||||
return { schedule, flush, flushPrefix, cancel, cancelAll };
|
||||
}
|
||||
1209
web/src/web-desktop-adapter.ts
Normal file
1209
web/src/web-desktop-adapter.ts
Normal file
File diff suppressed because it is too large
Load Diff
19
web/src/workbench-entry.tsx
Normal file
19
web/src/workbench-entry.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
// Standalone entry for /workbench.html.
|
||||
//
|
||||
// The shell itself is a pure component: everything that touches document.body or
|
||||
// the URL at import time lives here, so that project-shell can import and render
|
||||
// <WorkbenchShell /> without side effects on its own document.
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { installNavigation, readNavigationContext } from "./navigation.js";
|
||||
import { installUiAccessibility } from "./ui-accessibility.js";
|
||||
import { WorkbenchShell } from "./workbench-shell.js";
|
||||
|
||||
installNavigation("workbench", readNavigationContext());
|
||||
installUiAccessibility();
|
||||
|
||||
const container = document.querySelector<HTMLDivElement>("#app");
|
||||
if (!container) throw new Error("workbench entry: #app container is missing");
|
||||
// Lock the page to the viewport so the three-column layout can hand its own
|
||||
// scrollbars to the left and right panels (see panel-scroll.css).
|
||||
document.documentElement.classList.add("stage-lock");
|
||||
createRoot(container).render(<WorkbenchShell standalone />);
|
||||
@@ -1,3 +1,6 @@
|
||||
// Shared side-panel scroll contract; also styles the embedded (.fc-workbench-embed)
|
||||
// variant that project.html renders in-process.
|
||||
import "./panel-scroll.css";
|
||||
import { selectedMeshState } from "./mesh-desktop-adapter.js";
|
||||
import { SandboxTaskPanelView } from "./sandbox-task-panel-view.js";
|
||||
import { requestOwnerParameters } from "./view-navigation-preferences.js";
|
||||
@@ -2524,6 +2527,12 @@ export function WorkbenchShell({
|
||||
startWorkspaceFrame.current?.contentWindow?.postMessage({ type: "freecad-show-start" }, window.location.origin);
|
||||
startWorkspaceFrame.current?.focus();
|
||||
}}>Show Start</button>}
|
||||
{/* Every module task panel (Mesh regular solid, Robot joints, Assembly,
|
||||
Part tools …) renders above the three-column layout, as it did before the
|
||||
scroll lock. The dock wrapper keeps that region out of the layout's
|
||||
height budget: under html.stage-lock it caps and scrolls itself, so a
|
||||
tall task panel can no longer push the centre stage below the viewport. */}
|
||||
<div className="module-task-dock">
|
||||
{(module === "Show" || (module === "Std" && command?.replace(/^Std:desktop:/, "") === "Std_ToggleClipPlane")) && <button type="button" disabled={busy} onClick={() => {
|
||||
const documentId = documentSelection.documentId;
|
||||
const owner = projectDocumentOwners.current.get(documentId);
|
||||
@@ -4297,6 +4306,7 @@ export function WorkbenchShell({
|
||||
</table>
|
||||
</div>
|
||||
</section>}
|
||||
</div>
|
||||
<AssemblyComponentContextMenu enabled={module === "Assembly"} dispatcher={desktopCommands}
|
||||
documentId={documentSelection.documentId} selection={documentSelection.selection} busy={assemblyContextBlocked} onBusy={setBusy}
|
||||
activateObject={(documentId, object, linked) => void activateAssemblyObject(documentId, object, linked)}
|
||||
@@ -4317,11 +4327,13 @@ export function WorkbenchShell({
|
||||
onSelection={(documentId, selection) => setDocumentSelection({ documentId, selection })}>
|
||||
<aside>
|
||||
<h2 className="heading">模块</h2>
|
||||
<div className="pane-scroll" aria-label="Workbench modules">
|
||||
<input className="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="搜索模块" />
|
||||
{modules.map((item) => <button className={`module ${item.module === module ? "selected" : ""}`} key={item.module} onClick={() => { if (busy || workbenchSwitch.current) return; activateModule(item.module); setResponse(null); }}><strong>{item.module}</strong><small>{item.objectTypeCount} objects · {item.pythonApiCount} Python APIs</small></button>)}
|
||||
</aside>
|
||||
</div></aside>
|
||||
<aside>
|
||||
<h2 className="heading">{module} commands</h2>
|
||||
<div className="pane-scroll" aria-label="Workbench commands">
|
||||
<details className="workbench-document-picker">
|
||||
<summary>文档 · 打开 OPFS FCStd</summary>
|
||||
<label>OPFS 文档
|
||||
@@ -4965,7 +4977,7 @@ export function WorkbenchShell({
|
||||
<button id="cancel" className="run secondary" disabled={busy} onClick={() => void validateCommandMatrix("cancel")}>取消核验</button>
|
||||
<button id="reset" className="run secondary" disabled={busy} onClick={() => void resetCommandMatrix()}>重置 Worker</button>
|
||||
{moduleMatrixRecords.length > 0 ? <div className="matrix-list"><h2 className="heading">GUI / Web matrix</h2>{moduleMatrixRecords.map((item) => <button data-help-page={item.kind === "desktop-gui" ? item.command : undefined} className={`command ${item.id === selectedMatrixRecord?.id ? "selected" : ""}`} key={item.id} onClick={() => { setSelectedMatrixId(item.id); if (item.command === "Std_TestTaskBox" || (module === "Assembly" && item.command === "Assembly_CreateBom")) setTaskPanelGeneration(value => value + 1); if (item.kind === "desktop-gui" || item.kind === "web-command") { if (module === "Part" && item.command === "Part_SectionCut") setSectionCutOpen(true); setCommand(item.command); setPayloadText(item.kind === "web-command" ? commandPayload(module, item.command) : "{}"); setResponse(null); setStatus("输入命令参数后执行"); } }}><span>{item.command}</span><small>{item.kind} · {item.disposition}</small></button>)}</div> : null}
|
||||
</aside>
|
||||
</div></aside>
|
||||
<main className="stage"><section>
|
||||
{/* Sketcher editing belongs on the stage: in the narrow command column the
|
||||
drawing fieldset and constraint rows were cut off and required scrolling. */}
|
||||
|
||||
110
web/tools/manual/audit-ui-gaps.mjs
Normal file
110
web/tools/manual/audit-ui-gaps.mjs
Normal file
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env node
|
||||
// Audits the UI surface inventory against the repository and the manual.
|
||||
//
|
||||
// For every surface it verifies:
|
||||
// - the React owner file exists and (when given) the symbol appears in it
|
||||
// - the desktop reference file exists
|
||||
// - the surface is documented in the generated manual chapter ch16
|
||||
// - status is implemented/partial/gap/boundary as recorded, with reasons
|
||||
//
|
||||
// Output: docs/current/ui-design/data/gap-register.json (summary + issues).
|
||||
//
|
||||
// node tools/manual/audit-ui-gaps.mjs
|
||||
// node tools/manual/audit-ui-gaps.mjs --check # exit 1 if any gap
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const inventoryPath = path.join(repoRoot, "tools/fcweb/out/ui-surface-inventory.json");
|
||||
const chapterPath = path.join(webRoot, "manual/content/ch16-panel-index.md");
|
||||
const outPath = path.join(repoRoot, "docs/current/ui-design/data/gap-register.json");
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
|
||||
const fail = message => {
|
||||
console.error(`[audit-ui-gaps] ${message}`);
|
||||
process.exit(2);
|
||||
};
|
||||
if (!fs.existsSync(inventoryPath)) fail(`missing ${inventoryPath}; run ui-surface-inventory.mjs first`);
|
||||
if (!fs.existsSync(chapterPath)) fail(`missing ${chapterPath}; run generate-panel-index.mjs first`);
|
||||
|
||||
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
|
||||
const chapter = fs.readFileSync(chapterPath, "utf8");
|
||||
const categorySection = {
|
||||
"shell-region": "ch16-16-3-壳层区域",
|
||||
statusbar: "ch16-16-4-状态栏",
|
||||
"viewport-tool": "ch16-16-5-视口工具",
|
||||
dock: "ch16-16-6-停靠面板",
|
||||
"task-panel": "ch16-16-7-任务面板",
|
||||
"modal-dialog": "ch16-16-8-模态对话框",
|
||||
"preferences-page": "ch16-16-9-偏好设置页",
|
||||
menu: "ch16-16-10-菜单",
|
||||
toolbar: "ch16-16-11-工具栏",
|
||||
};
|
||||
|
||||
const symbolCache = new Map();
|
||||
const fileContains = (file, symbol) => {
|
||||
if (!symbol) return true;
|
||||
if (!file) return false;
|
||||
const key = file;
|
||||
if (!symbolCache.has(key)) {
|
||||
const full = path.join(repoRoot, file);
|
||||
symbolCache.set(key, fs.existsSync(full) ? fs.readFileSync(full, "utf8") : null);
|
||||
}
|
||||
const text = symbolCache.get(key);
|
||||
return Boolean(text && text.includes(symbol));
|
||||
};
|
||||
|
||||
const issues = [];
|
||||
const perSurface = inventory.surfaces.map(surface => {
|
||||
const problems = [];
|
||||
const ownerFile = surface.owner?.file ? path.join(repoRoot, surface.owner.file) : null;
|
||||
if (!ownerFile || !fs.existsSync(ownerFile)) problems.push("owner-file-missing");
|
||||
else if (!fileContains(surface.owner.file, surface.owner.symbol)) problems.push("owner-symbol-missing");
|
||||
|
||||
const desktopFile = surface.desktopRef?.file ? path.join(repoRoot, surface.desktopRef.file) : null;
|
||||
if (desktopFile && !fs.existsSync(desktopFile)) problems.push("desktop-file-missing");
|
||||
|
||||
if (!chapter.includes(surface.nameZh)) problems.push("manual-anchor-missing");
|
||||
if (surface.status === "gap") problems.push("ui-gap");
|
||||
if (surface.status === "partial" && !surface.note) problems.push("partial-without-note");
|
||||
|
||||
for (const problem of problems) issues.push({ id: surface.id, category: surface.category, status: surface.status, problem });
|
||||
return { id: surface.id, category: surface.category, status: surface.status, manualAnchor: categorySection[surface.category] ?? "ch16", problems };
|
||||
});
|
||||
|
||||
const byProblem = {};
|
||||
for (const issue of issues) byProblem[issue.problem] = (byProblem[issue.problem] ?? 0) + 1;
|
||||
|
||||
const report = {
|
||||
schema: "freecad-web-manual/ui-gap-register/v1",
|
||||
counts: {
|
||||
surfaces: perSurface.length,
|
||||
withProblems: perSurface.filter(row => row.problems.length).length,
|
||||
byProblem,
|
||||
byStatus: inventory.counts.byStatus,
|
||||
},
|
||||
ok: issues.length === 0,
|
||||
issues,
|
||||
surfaces: perSurface,
|
||||
};
|
||||
|
||||
if (check) {
|
||||
if (!report.ok) {
|
||||
console.error(JSON.stringify({ ok: false, counts: report.counts, sample: issues.slice(0, 10) }, null, 2));
|
||||
process.exit(1);
|
||||
}
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ ok: true, checked: path.relative(repoRoot, outPath), surfaces: perSurface.length }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ ok: report.ok, out: path.relative(repoRoot, outPath), counts: report.counts, sample: issues.slice(0, 5) }, null, 2));
|
||||
process.exit(report.ok ? 0 : 1);
|
||||
112
web/tools/manual/build-fcweb-toolkit.mjs
Normal file
112
web/tools/manual/build-fcweb-toolkit.mjs
Normal file
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env node
|
||||
// Builds the fcweb toolkit usage guide.
|
||||
//
|
||||
// Shares the house template and markdown pipeline with the other manuals
|
||||
// (web/tools/manual/template.html + marked + front-matter chapters), but the
|
||||
// content is the API itself rather than a course, so the figures/replay/stills
|
||||
// machinery is dropped and replaced by one check that matters: every method the
|
||||
// guide documents must exist in the module it claims to come from.
|
||||
//
|
||||
// Consumed by check-fcweb-toolkit.mjs and served from web/teaching/.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { marked } from "marked";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const contentDir = path.join(webRoot, "manual", "fcweb-toolkit", "content");
|
||||
const dataDir = path.join(webRoot, "manual", "fcweb-toolkit", "data");
|
||||
const toolkitDir = path.join(repoRoot, "tools", "fcweb");
|
||||
const outFile = path.join(webRoot, "teaching", "fcweb-toolkit.html");
|
||||
|
||||
const esc = value => String(value ?? "")
|
||||
.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
const parseFrontMatter = text => {
|
||||
const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text);
|
||||
if (!match) return { meta: {}, body: text };
|
||||
const meta = {};
|
||||
for (const line of match[1].split("\n")) {
|
||||
const [key, ...rest] = line.split(":");
|
||||
if (key) meta[key.trim()] = rest.join(":").trim();
|
||||
}
|
||||
return { meta, body: match[2] };
|
||||
};
|
||||
|
||||
const slug = text => String(text).toLowerCase().trim()
|
||||
.replace(/[`*_]/g, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
||||
|
||||
// ---------------------------------------------------------------- chapters --
|
||||
if (!fs.existsSync(contentDir)) throw new Error(`missing content directory: ${contentDir}`);
|
||||
const chapters = fs.readdirSync(contentDir)
|
||||
.filter(name => name.endsWith(".md"))
|
||||
.map(name => {
|
||||
const text = fs.readFileSync(path.join(contentDir, name), "utf8");
|
||||
const { meta, body } = parseFrontMatter(text);
|
||||
return { file: name, meta, body, id: meta.id ?? name.replace(/\.md$/, ""), order: Number(meta.order ?? 999) };
|
||||
})
|
||||
.sort((a, b) => a.order - b.order);
|
||||
|
||||
// ------------------------------------------------------- API drift guard --
|
||||
// The guide must not document a method that does not exist. Each entry maps a
|
||||
// module file to a required export.
|
||||
const API = {
|
||||
"part.mjs": ["openPart", "PartDocument"],
|
||||
"partdesign.mjs": ["openPartDesign", "PartDesignDocument"],
|
||||
"assembly.mjs": ["openAssembly", "AssemblySession"],
|
||||
"kernel.mjs": ["openKernel", "createSession", "writeTrace", "KernelError"],
|
||||
"opfs.mjs": ["storeBytes", "readExportFile", "safeName", "configureOpfs"],
|
||||
"capture.mjs": ["launchBrowser", "pageCheck", "screenshot", "projectMesh"],
|
||||
};
|
||||
const api = {};
|
||||
for (const [module, exports] of Object.entries(API)) {
|
||||
const file = path.join(toolkitDir, module);
|
||||
if (!fs.existsSync(file)) throw new Error(`toolkit module missing: ${file}`);
|
||||
const source = fs.readFileSync(file, "utf8");
|
||||
for (const name of exports) {
|
||||
const declared = new RegExp(`export\\s+(async\\s+)?(function|class|const)\\s+${name}\\b`).test(source);
|
||||
if (!declared) throw new Error(`${module} no longer exports ${name} — the guide would be wrong`);
|
||||
}
|
||||
api[module] = exports;
|
||||
}
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dataDir, "api.json"), JSON.stringify(api, null, 2));
|
||||
|
||||
// ---------------------------------------------------------------- render ----
|
||||
const sections = chapters.map(chapter => {
|
||||
const html = marked.parse(chapter.body);
|
||||
return { ...chapter, html };
|
||||
});
|
||||
|
||||
const sidebarHtml = `<ol>${chapters.map(chapter => `<li>
|
||||
<a href="#${esc(chapter.id)}">${esc(chapter.meta.title ?? chapter.id)}</a>
|
||||
</li>`).join("")}</ol>`;
|
||||
|
||||
const searchIndex = chapters.map(chapter => ({
|
||||
id: chapter.id,
|
||||
title: chapter.meta.title ?? chapter.id,
|
||||
text: chapter.body.replace(/```[\s\S]*?```/g, " ").replace(/[#*`>|-]/g, " ").replace(/\s+/g, " ").slice(0, 400),
|
||||
}));
|
||||
|
||||
const content = sections.map(section => `<section id="${esc(section.id)}">${section.html}</section>`).join("\n");
|
||||
|
||||
const template = fs.readFileSync(path.join(here, "template.html"), "utf8");
|
||||
const html = template
|
||||
.replaceAll("{{TITLE}}", "fcweb 工具库 · 建零件与装配的通用工具")
|
||||
.replace("{{SIDEBAR}}", sidebarHtml)
|
||||
.replace("{{CONTENT}}", content)
|
||||
.replace("{{COMMAND_INDEX}}", `<section><h2>模块导出速查</h2><div class="table-scroll"><table><thead><tr><th>模块</th><th>导出</th></tr></thead><tbody>${
|
||||
Object.entries(api).map(([module, names]) => `<tr><td><code>${esc(module)}</code></td><td>${names.map(n => `<code>${esc(n)}</code>`).join(" ")}</td></tr>`).join("")
|
||||
}</tbody></table></div></section>`)
|
||||
.replace("{{SEARCH_INDEX}}", JSON.stringify(searchIndex).replace(/</g, "\\u003c"))
|
||||
.replace("{{COMMAND_COUNT}}", String(Object.values(api).flat().length));
|
||||
|
||||
fs.mkdirSync(path.dirname(outFile), { recursive: true });
|
||||
fs.writeFileSync(outFile, html);
|
||||
console.log(JSON.stringify({
|
||||
ok: true, outFile, chapters: chapters.length,
|
||||
modules: Object.keys(api).length, exports: Object.values(api).flat().length,
|
||||
bytes: fs.statSync(outFile).size,
|
||||
}));
|
||||
@@ -105,12 +105,17 @@ const commandIndex = `<section id="command-index-section"><h1 id="ch15">附录
|
||||
<div class="table-scroll"><table id="command-index"><thead><tr><th>模块</th><th>命令</th><th>类型</th><th>状态</th><th>章节</th><th>案例</th></tr></thead><tbody>${indexRows}</tbody></table></div></section>`;
|
||||
|
||||
let content = sections.map(chapter => chapter.html).join("\n");
|
||||
const pager = chapters.map((chapter, index) => {
|
||||
// One pager per chapter: previous/next links only, so the row never grows with
|
||||
// the chapter count (a single all-chapter row overflowed the page at 1440px).
|
||||
const chapterIndex = new Map(chapters.map((chapter, index) => [chapter.id, index]));
|
||||
content = content.replace(/<h1 id="([^"]+)">/g, (match, id) => {
|
||||
const index = chapterIndex.get(id);
|
||||
if (index === undefined) return match;
|
||||
const prev = chapters[index - 1]; const next = chapters[index + 1];
|
||||
return `${prev ? `<a href="#${esc(prev.id)}">← ${esc(prev.meta.title ?? prev.id)}</a>` : "<span></span>"}
|
||||
${next ? `<a href="#${esc(next.id)}">${esc(next.meta.title ?? next.id)} →</a>` : "<span></span>"}`;
|
||||
}).join("\n");
|
||||
content = content.replace(/<h1 id="ch15">/, `<div class="pager">${pager}</div><h1 id="ch15">`);
|
||||
return `<div class="pager">${prev ? `<a href="#${esc(prev.id)}">← ${esc(prev.meta.title ?? prev.id)}</a>` : "<span></span>"}
|
||||
${next ? `<a href="#${esc(next.id)}">${esc(next.meta.title ?? next.id)} →</a>` : "<span></span>"}</div>
|
||||
${match}`;
|
||||
});
|
||||
|
||||
// Validate referenced screenshots before writing.
|
||||
const missing = [];
|
||||
|
||||
234
web/tools/manual/build-parts-manual.mjs
Normal file
234
web/tools/manual/build-parts-manual.mjs
Normal file
@@ -0,0 +1,234 @@
|
||||
#!/usr/bin/env node
|
||||
// Builds the beginner "part design" course handout.
|
||||
//
|
||||
// Shares the reducer manual's template and markdown pipeline, but owns its own
|
||||
// content directory and output. The distinguishing feature is that every figure
|
||||
// is a still captured by the per-part recording itself (tools/reducer-parts-course
|
||||
// /stills/P##/), so the handout and the videos can never disagree about what a
|
||||
// step looked like.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { marked } from "marked";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const contentDir = path.join(webRoot, "manual", "reducer-parts", "content");
|
||||
const assetsDir = path.join(webRoot, "manual", "reducer-parts", "assets");
|
||||
const stillsRoot = path.join(webRoot, "tools", "reducer-parts-course", "stills");
|
||||
const outFile = path.join(webRoot, "teaching", "reducer-parts-manual.html");
|
||||
const outAssets = path.join(webRoot, "teaching", "reducer-parts-manual-assets");
|
||||
const caseDir = path.join(webRoot, "teaching", "cases", "secondary-reducer-pro");
|
||||
const replayDir = path.join(caseDir, "out", "replay");
|
||||
const partsCourse = path.join(webRoot, "tools", "reducer-parts-course");
|
||||
const esc = value => String(value ?? "").replace(/&/g, "&").replace(/</g, "<")
|
||||
.replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
const readJson = file => (fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null);
|
||||
const spec = readJson(path.join(partsCourse, "parts-spec.json"));
|
||||
const course = readJson(path.join(partsCourse, "course.json"));
|
||||
const failures = [];
|
||||
|
||||
// ---- figures: every step still the recorder captured ----------------------
|
||||
// Chapter markdown refers to a step with ``.
|
||||
// The builder resolves it to the real PNG and, when the caption omits numbers,
|
||||
// appends the ones the replay recorded for that step.
|
||||
fs.mkdirSync(assetsDir, { recursive: true });
|
||||
// Map each replay step to the still the driver captured for it.
|
||||
//
|
||||
// The filename alone is not a reliable key: the driver sanitises spaces to
|
||||
// underscores, so "Gear1_20T involute" becomes "Gear1_20T_involute" and the
|
||||
// reverse mapping is ambiguous. The episode's own script records which scene
|
||||
// id belongs to which kernel step, so index by scene id instead.
|
||||
const stillIndex = new Map(); // "P21|outer pad" -> { file, step }
|
||||
for (const entry of spec?.episodes ?? []) {
|
||||
const dir = path.join(stillsRoot, entry.episode);
|
||||
if (!fs.existsSync(dir)) { failures.push(`${entry.episode}: no stills directory (record the video first)`); continue; }
|
||||
const replay = readJson(path.join(replayDir, `${entry.document}.json`));
|
||||
const script = readJson(path.join(partsCourse, "episodes", entry.episode, "script.zh.json"));
|
||||
for (const scene of script?.scenes ?? []) {
|
||||
if (typeof scene.step !== "number") continue;
|
||||
const stem = `${scene.id}-${String(scene.title).replace(/[^\w一-龥-]+/g, "_")}`;
|
||||
const file = path.join(dir, `${stem}.png`);
|
||||
if (!fs.existsSync(file)) { failures.push(`${entry.episode}: missing still ${scene.id} (${scene.title})`); continue; }
|
||||
stillIndex.set(`${entry.episode}|${scene.title}`, { file, step: replay?.steps?.[scene.step - 1] ?? null });
|
||||
}
|
||||
}
|
||||
|
||||
const copyStill = (episode, label, where) => {
|
||||
const key = `${episode}|${label}`;
|
||||
const hit = stillIndex.get(key);
|
||||
if (!hit) { failures.push(`${where}: no still for ${key}`); return null; }
|
||||
if (!fs.existsSync(assetsDir)) fs.mkdirSync(assetsDir, { recursive: true });
|
||||
const target = `${episode}-${label.replace(/[^\w一-龥-]+/g, "_")}.png`;
|
||||
fs.copyFileSync(hit.file, path.join(assetsDir, target));
|
||||
// The page is served from teaching/, and this manual owns its own asset folder.
|
||||
return { src: `./reducer-parts-manual-assets/${target}`, step: hit.step };
|
||||
};
|
||||
|
||||
// ---- front matter and chapters --------------------------------------------
|
||||
const parseFrontMatter = text => {
|
||||
const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text);
|
||||
if (!match) return { meta: {}, body: text };
|
||||
const meta = {};
|
||||
for (const line of match[1].split("\n")) {
|
||||
const [key, ...rest] = line.split(":");
|
||||
if (key) meta[key.trim()] = rest.join(":").trim();
|
||||
}
|
||||
return { meta, body: match[2] };
|
||||
};
|
||||
const slug = text => String(text).toLowerCase().trim()
|
||||
.replace(/[`*_]/g, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
||||
|
||||
const chapters = fs.readdirSync(contentDir).filter(name => name.endsWith(".md")).map(name => {
|
||||
const text = fs.readFileSync(path.join(contentDir, name), "utf8");
|
||||
const { meta, body } = parseFrontMatter(text);
|
||||
return { file: name, meta, body, id: meta.id ?? name.replace(/\.md$/, ""), order: Number(meta.order ?? 999) };
|
||||
}).sort((a, b) => a.order - b.order);
|
||||
|
||||
// Resolve ::still directives into markdown images with a figure caption.
|
||||
const figureCount = { total: 0 };
|
||||
const withFigures = chapter => chapter.body.replace(
|
||||
/!\[([^\]]*)\]\(::still\s+(\S+)\s+(.+?)\)/g,
|
||||
(whole, caption, episode, label) => {
|
||||
const hit = copyStill(episode, label.trim(), `${chapter.id} "${caption}"`);
|
||||
if (!hit) return "";
|
||||
figureCount.total++;
|
||||
const step = hit.step;
|
||||
const facts = step
|
||||
? ` ${step.volume != null && step.volume > 0 ? `体积 ${Number(step.volume).toLocaleString("zh-CN", { maximumFractionDigits: 0 })} mm³` : "草图轮廓"},面数 ${step.faceCount ?? "-"},耗时 ${Number(step.seconds).toFixed(2)} s。`
|
||||
: "";
|
||||
const text = caption?.trim() ? `${caption.trim()}${facts}` : `${episode} · ${label}${facts}`;
|
||||
return `\n\n\n\n`;
|
||||
});
|
||||
|
||||
|
||||
// Resolve `::ui P21 outer pad` into an "界面操作" block: the screenshot the UI
|
||||
// driver captured for that step, plus the exact field values it typed. The
|
||||
// values come from out/ui-steps, so the manual cannot describe an operation the
|
||||
// UI does not actually perform.
|
||||
const PAGE_LABEL_ZH = { "partdesign.html": "零件设计页", "project.html?workbench=PartDesign": "项目页 · 零件设计工作台" };
|
||||
const uiStepIndex = new Map(); // "P21|outer pad" -> ui-steps entry
|
||||
const uiStillsRoot = path.join(partsCourse, "ui-stills");
|
||||
for (const entry of spec?.episodes ?? []) {
|
||||
const steps = readJson(path.join(partsCourse, "out", "ui-steps", `${entry.document}.json`));
|
||||
const script = readJson(path.join(partsCourse, "episodes", entry.episode, "script.zh.json"));
|
||||
const bySceneTitle = new Map((script?.scenes ?? []).map(scene => [scene.title, scene.id]));
|
||||
for (const step of steps?.steps ?? []) {
|
||||
const scene = bySceneTitle.get(step.label);
|
||||
const still = scene ? path.join(uiStillsRoot, entry.episode, `${scene}-${String(step.label).replace(/[^\w一-龥-]+/g, "_")}.png`) : null;
|
||||
uiStepIndex.set(`${entry.episode}|${step.label}`, { step, still: still && fs.existsSync(still) ? still : null });
|
||||
}
|
||||
}
|
||||
|
||||
const uiCount = { total: 0, missingStill: [] };
|
||||
const row = (field, value) => `<tr><th>${esc(field)}</th><td>${esc(value)}</td></tr>`;
|
||||
const uiValues = step => {
|
||||
const rows = [];
|
||||
const num = value => Number.isFinite(Number(value)) ? String(Math.round(Number(value) * 1000) / 1000) : esc(value);
|
||||
if (step.kind === "sketch") {
|
||||
rows.push(row("界面", PAGE_LABEL_ZH[step.page] ?? step.page));
|
||||
rows.push(row("命令", step.command));
|
||||
if (step.profileType === "Circle") rows.push(row("半径", num(step.parameters?.Radius)));
|
||||
else if (step.profileType === "Rectangle") { rows.push(row("宽", num(step.parameters?.Width))); rows.push(row("高", num(step.parameters?.Height))); }
|
||||
else { rows.push(row("几何条数", String(step.geometries?.length ?? 0))); rows.push(row("约束条数", String(step.constraints?.length ?? 0))); }
|
||||
const [x, y, z] = step.position ?? [0, 0, 0];
|
||||
rows.push(row("位置 X / Y / Z", `${num(x)} / ${num(y)} / ${num(z)}`));
|
||||
if (Array.isArray(step.placementRotation) && step.placementRotation.some((value, index) => index < 3 && value !== 0)) {
|
||||
rows.push(row("Sketch plane", step.placementRotation.map(num).join(", ") === "0,0,0,1" ? "XY" : "非 XY(见四元数)"));
|
||||
rows.push(row("placementRotation", step.placementRotation.map(num).join(", ")));
|
||||
} else rows.push(row("Sketch plane", "XY"));
|
||||
} else if (step.kind === "feature") {
|
||||
rows.push(row("命令", step.command));
|
||||
rows.push(row("轮廓", step.profile ?? "-"));
|
||||
rows.push(row("长度", num(step.length)));
|
||||
if (step.angle != null) rows.push(row("角度", num(step.angle)));
|
||||
rows.push(row("Sides", step.midplane ? "Symmetric" : "One side"));
|
||||
} else if (step.kind === "gear") {
|
||||
rows.push(row("命令", step.command));
|
||||
for (const [key, value] of Object.entries(step.gearParameters ?? {})) rows.push(row(key, num(value)));
|
||||
} else rows.push(row("命令", step.command ?? "-"));
|
||||
return rows.join("");
|
||||
};
|
||||
|
||||
const withUiBlocks = (chapter, bodyText) => (bodyText ?? chapter.body).replace(
|
||||
/::ui\s+(\S+)\s+([^\n)]+)/g,
|
||||
(whole, episode, labelText) => {
|
||||
const label = labelText.trim();
|
||||
const hit = uiStepIndex.get(`${episode}|${label}`);
|
||||
if (!hit) { failures.push(`${chapter.id}: no ui-steps entry for ${episode} ${label}`); return ""; }
|
||||
uiCount.total++;
|
||||
// A ::ui block with no screenshot would teach the operation with words
|
||||
// only; the whole point is that the picture proves it can be done.
|
||||
if (!hit.still) { uiCount.missingStill.push(`${episode} ${label}`); failures.push(`${chapter.id}: no UI screenshot for ${episode} ${label}`); }
|
||||
const image = hit.still
|
||||
? `\n\n}-ui.png)\n\n`
|
||||
: "\n\n> 该步尚未截到界面图。\n\n";
|
||||
if (hit.still) {
|
||||
const target = `${episode}-${label.replace(/[^\w一-龥-]+/g, "_")}-ui.png`;
|
||||
fs.copyFileSync(hit.still, path.join(assetsDir, target));
|
||||
}
|
||||
return `<div class="ui-block"><h4>界面操作</h4>${image}<table>${uiValues(hit.step)}</table></div>`;
|
||||
});
|
||||
|
||||
const sections = [];
|
||||
const sidebar = [];
|
||||
for (const chapter of chapters) {
|
||||
const body = withUiBlocks(chapter, withFigures(chapter));
|
||||
const html = marked.parse(body);
|
||||
const withIds = html.replace(/<h([12])>([\s\S]*?)<\/h\1>/g, (whole, level, inner) => {
|
||||
const text = inner.replace(/<[^>]+>/g, "").trim();
|
||||
const id = Number(level) === 1 ? chapter.id : `${chapter.id}-${slug(text)}`;
|
||||
return `<h${level} id="${esc(id)}">${inner}</h${level}>`;
|
||||
}).replace(/<img([^>]*?)>/g, (whole, attrs) => /loading=/.test(attrs) ? whole : `<img loading="lazy"${attrs}>`)
|
||||
.replace(/<table>/g, '<div class="table-scroll"><table>')
|
||||
.replace(/<\/table>/g, '</table></div>');
|
||||
sections.push({ ...chapter, html: withIds });
|
||||
const h2s = [...body.matchAll(/^## (.+)$/gm)].map(match => {
|
||||
const title = match[1].replace(/[`*_]/g, "").trim();
|
||||
return { id: `${chapter.id}-${slug(title)}`, title };
|
||||
});
|
||||
sidebar.push({ id: chapter.id, title: chapter.meta.title ?? chapter.id, sections: h2s });
|
||||
}
|
||||
const sidebarHtml = `<ol>${sidebar.map(chapter => `<li>
|
||||
<div class="chapter"><input type="checkbox" data-progress="${esc(chapter.id)}" aria-label="完成 ${esc(chapter.title)}" /><a href="#${esc(chapter.id)}">${esc(chapter.title)}</a></div>
|
||||
${chapter.sections.map(section => `<a class="sec" href="#${esc(section.id)}">${esc(section.title)}</a>`).join("")}
|
||||
</li>`).join("")}</ol>`;
|
||||
|
||||
// ---- appendix A: the 23 parts, straight from the replay -------------------
|
||||
const partRows = [];
|
||||
for (const entry of course?.episodes ?? []) {
|
||||
const replay = readJson(path.join(replayDir, `${entry.document}.json`));
|
||||
if (!replay) continue;
|
||||
const last = replay.steps.at(-1);
|
||||
// Link to the course page's own anchor for this episode; the handout has no
|
||||
// per-episode chapter, so a same-page "#P01" would be a dead link.
|
||||
partRows.push(`<tr><td><a href="cases/reducer-parts-course.html#${esc(entry.id)}">${esc(entry.id)}</a></td><td>${esc(entry.title)}</td>
|
||||
<td>${replay.steps.length}</td><td>${last.faceCount ?? "-"}</td>
|
||||
<td>${last.volume != null ? Number(last.volume).toLocaleString("zh-CN", { maximumFractionDigits: 0 }) : "-"}</td>
|
||||
<td>${Number(last.seconds).toFixed(1)}</td></tr>`);
|
||||
}
|
||||
const appendix = `<section><h1 id="appendix">附录:23 件实测与视频对照</h1>
|
||||
<p>每一行的数字都来自该零件自己的建模回放记录,与视频里看到的同源。点零件编号跳到对应章节。</p>
|
||||
<div class="table-scroll"><table><thead><tr><th>集</th><th>零件</th><th>步数</th><th>面数</th><th>体积 mm³</th><th>末步耗时 s</th></tr></thead><tbody>${partRows.join("")}</tbody></table></div>
|
||||
<h2 id="appendix-videos">看录像</h2>
|
||||
<p>每章的“对应视频”链接到该零件的建造成片;全部 23 集见 <a href="cases/reducer-parts-course.html">零件建模过程课程页</a>。</p>
|
||||
</section>`;
|
||||
|
||||
if (failures.length) { console.log(JSON.stringify({ failures }, null, 2)); process.exit(1); }
|
||||
|
||||
const content = [...sections.map(chapter => chapter.html), appendix].join("\n");
|
||||
fs.mkdirSync(outAssets, { recursive: true });
|
||||
if (fs.existsSync(assetsDir)) fs.cpSync(assetsDir, outAssets, { recursive: true });
|
||||
|
||||
const template = fs.readFileSync(path.join(here, "template.html"), "utf8");
|
||||
const html = template
|
||||
.replaceAll("{{TITLE}}", "零件设计入门 · Web FreeCAD 图文教案")
|
||||
.replace("{{SIDEBAR}}", sidebarHtml)
|
||||
.replace("{{CONTENT}}", content)
|
||||
.replace("{{COMMAND_INDEX}}", "")
|
||||
.replace("{{SEARCH_INDEX}}", "[]")
|
||||
.replace("{{COMMAND_COUNT}}", "0");
|
||||
fs.writeFileSync(outFile, html);
|
||||
console.log(JSON.stringify({ ok: true, outFile, chapters: chapters.length, figures: figureCount.total,
|
||||
stills: stillIndex.size, bytes: fs.statSync(outFile).size }));
|
||||
180
web/tools/manual/build-reducer-manual.mjs
Normal file
180
web/tools/manual/build-reducer-manual.mjs
Normal file
@@ -0,0 +1,180 @@
|
||||
#!/usr/bin/env node
|
||||
// Builds the reducer-specific single-page Chinese manual.
|
||||
//
|
||||
// This is deliberately a separate builder rather than a flag on build-manual.mjs:
|
||||
// the generic manual is the full-app reference (16 chapters, 400+ commands) and
|
||||
// the reducer manual is a 12-chapter beginner walkthrough of ONE artifact. They
|
||||
// share the template and the markdown pipeline so the reading experience is
|
||||
// identical, but neither owns the other's content directory or command index.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { marked } from "marked";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const contentDir = path.join(webRoot, "manual", "reducer", "content");
|
||||
const assetsDir = path.join(webRoot, "manual", "reducer", "assets");
|
||||
const outFile = path.join(webRoot, "teaching", "reducer-manual.html");
|
||||
const outAssets = path.join(webRoot, "teaching", "reducer-manual-assets");
|
||||
// The reducer manual has no command index of its own: it indexes the case's
|
||||
// real build steps instead, built from the trace and evidence files.
|
||||
const caseDir = path.join(webRoot, "teaching", "cases", "secondary-reducer-pro");
|
||||
const readCase = name => {
|
||||
const file = path.join(caseDir, name);
|
||||
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
|
||||
};
|
||||
const spec = readCase("reducer-spec.json");
|
||||
const strength = readCase("out/strength.json");
|
||||
const assembly = readCase("out/assembly.json");
|
||||
const parts = readCase("parts/evidence.json");
|
||||
const gapDoc = path.join(webRoot, "docs", "current", "web-freecad-gaps-secondary-reducer-pro.md");
|
||||
const gaps = fs.existsSync(gapDoc)
|
||||
? [...fs.readFileSync(gapDoc, "utf8").matchAll(/^## (GAP-RP-\d+) · (.+)$/gm)].map(m => ({ id: m[1], title: m[2] }))
|
||||
: [];
|
||||
const trace = readCase("out/traces/SecondaryReducer.json");
|
||||
const features = { commands: [], stats: { nativeHandlers: 0 }, chapters: [] };
|
||||
const chapterTitle = new Map(features.chapters.map(chapter => [chapter.id, chapter.title]));
|
||||
const esc = value => String(value ?? "").replace(/&/g, "&").replace(/</g, "<")
|
||||
.replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
const parseFrontMatter = text => {
|
||||
const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text);
|
||||
if (!match) return { meta: {}, body: text };
|
||||
const meta = {};
|
||||
for (const line of match[1].split("\n")) {
|
||||
const [key, ...rest] = line.split(":");
|
||||
if (key) meta[key.trim()] = rest.join(":").trim();
|
||||
}
|
||||
return { meta, body: match[2] };
|
||||
};
|
||||
|
||||
const slug = text => String(text).toLowerCase().trim()
|
||||
.replace(/[`*_]/g, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
||||
|
||||
const chapters = fs.readdirSync(contentDir).filter(name => name.endsWith(".md")).map(name => {
|
||||
const text = fs.readFileSync(path.join(contentDir, name), "utf8");
|
||||
const { meta, body } = parseFrontMatter(text);
|
||||
return { file: name, meta, body, id: meta.id ?? name.replace(/\.md$/, ""), order: Number(meta.order ?? 999) };
|
||||
}).sort((a, b) => a.order - b.order);
|
||||
|
||||
const sidebar = [];
|
||||
const searchIndex = [];
|
||||
const sections = [];
|
||||
for (const chapter of chapters) {
|
||||
const html = marked.parse(chapter.body);
|
||||
const withIds = html.replace(/<h([12])>([\s\S]*?)<\/h\1>/g, (whole, level, inner) => {
|
||||
const text = inner.replace(/<[^>]+>/g, "").trim();
|
||||
const id = Number(level) === 1 ? chapter.id : `${chapter.id}-${slug(text)}`;
|
||||
return `<h${level} id="${esc(id)}">${inner}</h${level}>`;
|
||||
}).replace(/<img([^>]*?)>/g, (whole, attrs) => /loading=/.test(attrs) ? whole : `<img loading="lazy"${attrs}>`)
|
||||
.replace(/<table>/g, '<div class="table-scroll"><table>')
|
||||
.replace(/<\/table>/g, '</table></div>');
|
||||
sections.push({ ...chapter, html: withIds });
|
||||
|
||||
const h2s = [...chapter.body.matchAll(/^## (.+)$/gm)].map(match => {
|
||||
const title = match[1].replace(/[`*_]/g, "").trim();
|
||||
return { id: `${chapter.id}-${slug(title)}`, title };
|
||||
});
|
||||
sidebar.push({ id: chapter.id, title: chapter.meta.title ?? chapter.id, sections: h2s,
|
||||
done: chapter.meta.level !== "appendix" });
|
||||
const parts = chapter.body.split(/^## /m);
|
||||
const chapterMeta = { title: chapter.meta.title ?? chapter.id, chapter: chapter.meta.title ?? chapter.id };
|
||||
if (parts[0]) searchIndex.push({ id: chapter.id, title: chapterMeta.title, chapter: chapterMeta.chapter,
|
||||
text: parts[0].replace(/[#>*`|\-]/g, " ").replace(/\s+/g, " ").slice(0, 400), commands: [] });
|
||||
for (const part of parts.slice(1)) {
|
||||
const [titleLine, ...rest] = part.split("\n");
|
||||
const title = titleLine.replace(/[`*_]/g, "").trim();
|
||||
searchIndex.push({ id: `${chapter.id}-${slug(title)}`, title, chapter: chapterMeta.title,
|
||||
text: rest.join(" ").replace(/[#>*`|\-]/g, " ").replace(/\s+/g, " ").slice(0, 400), commands: [] });
|
||||
}
|
||||
}
|
||||
|
||||
const sidebarHtml = `<ol>${sidebar.map(chapter => `<li>
|
||||
<div class="chapter"><input type="checkbox" data-progress="${esc(chapter.id)}" aria-label="完成 ${esc(chapter.title)}" /><a href="#${esc(chapter.id)}">${esc(chapter.title)}</a></div>
|
||||
${chapter.sections.map(section => `<a class="sec" href="#${esc(section.id)}">${esc(section.title)}</a>`).join("")}
|
||||
</li>`).join("")}<li><a href="#ch15">附录:命令索引</a></li></ol>`;
|
||||
|
||||
const statusLabel = { detailed: "精讲", overview: "覆盖", boundary: "边界", verified: "已验证", "fix-needed": "待修" };
|
||||
const moduleOptions = [...new Set(features.commands.map(item => item.module))].sort()
|
||||
.map(module => `<option value="${esc(module)}">${esc(module)}</option>`).join("");
|
||||
const indexRows = features.commands.map(item => {
|
||||
const anchor = `cmd-${slug(item.module)}-${slug(item.command)}`;
|
||||
return `<tr id="${esc(anchor)}" data-module="${esc(item.module)}" data-status="${esc(item.status)}">
|
||||
<td>${esc(item.module)}</td><td><code>${esc(item.command)}</code></td><td>${esc(item.kind)}</td>
|
||||
<td><span class="badge ${esc(item.status)}">${esc(statusLabel[item.status] ?? item.status)}</span></td>
|
||||
<td>${esc(chapterTitle.get(item.chapterId) ?? item.chapterId ?? "-")}</td><td>${esc(item.ledgerCaseId ?? "-")}</td></tr>`;
|
||||
}).join("");
|
||||
const searchCommands = features.commands.map(item => ({
|
||||
id: `cmd-${slug(item.module)}-${slug(item.command)}`,
|
||||
title: `${item.module} · ${item.command}`,
|
||||
chapter: chapterTitle.get(item.chapterId) ?? "附录",
|
||||
text: `${item.disposition} ${item.kind} ${statusLabel[item.status] ?? item.status}`,
|
||||
commands: [item.command, item.module],
|
||||
}));
|
||||
|
||||
// Appendix: the build record, the gap log and the acceptance numbers. These
|
||||
// replace the generic command index -- a beginner following the reducer does
|
||||
// not need 400 command rows, they need "what did this build actually do".
|
||||
const traceRows = (trace?.events ?? []).map(event =>
|
||||
`<tr><td>${event.step}</td><td>${esc(event.label)}</td><td><code>${esc(event.action)}</code></td><td>${event.seconds}</td></tr>`).join("");
|
||||
const gapRows = gaps.map(gap => `<tr><td><code>${esc(gap.id)}</code></td><td>${esc(gap.title)}</td></tr>`).join("");
|
||||
const partRows = (parts?.items ?? []).map(item => {
|
||||
const volume = item.volume?.finalVolume ?? item.volume?.volume ?? "";
|
||||
return `<tr><td>${esc(item.document)}</td><td>${esc(item.role ?? "-")}</td><td>${item.faceCount ?? "-"}</td>
|
||||
<td>${typeof volume === "number" ? volume.toFixed(1) : ""}</td><td>${item.seconds}</td>
|
||||
<td>${item.underSixtySeconds ? "通过" : "超时"}</td></tr>`;
|
||||
}).join("");
|
||||
const commandIndex = `<section id="command-index-section"><h1 id="ch15">附录:构建记录、缺口清单与验收数字</h1>
|
||||
<h2 id="ch15-parts">A. 零件实测(${(parts?.items ?? []).length} 件)</h2>
|
||||
<div class="table-scroll"><table><thead><tr><th>文档</th><th>角色</th><th>面数</th><th>体积 mm³</th><th>构建 s</th><th>60 s 门槛</th></tr></thead><tbody>${partRows}</tbody></table></div>
|
||||
<h2 id="ch15-steps">B. 装配构建记录(${(trace?.events ?? []).length} 步)</h2>
|
||||
<p>每一步都是真实的内核调用,含耗时。教学播放器按这份记录回放。</p>
|
||||
<div class="table-scroll"><table><thead><tr><th>#</th><th>步骤</th><th>命令</th><th>秒</th></tr></thead><tbody>${traceRows}</tbody></table></div>
|
||||
<h2 id="ch15-gaps">C. 缺口清单(${gaps.length} 条)</h2>
|
||||
<p>每条缺口都有桌面源程序依据;修复情况见缺口台账原文。</p>
|
||||
<div class="table-scroll"><table><thead><tr><th>编号</th><th>标题</th></tr></thead><tbody>${gapRows}</tbody></table></div>
|
||||
<h2 id="ch15-numbers">D. 验收数字</h2>
|
||||
<div class="table-scroll"><table><thead><tr><th>项</th><th>值</th></tr></thead><tbody>
|
||||
<tr><td>传动比</td><td>${spec ? spec.transmission.ratio : "-"}</td></tr>
|
||||
<tr><td>模数 / 压力角</td><td>${spec ? `${spec.transmission.moduleMm} mm / ${spec.transmission.pressureAngleDeg}°` : "-"}</td></tr>
|
||||
<tr><td>中心距</td><td>${strength ? strength.stages.map(s => s.centreDistanceMm + " mm").join(" / ") : "-"}</td></tr>
|
||||
<tr><td>安全系数(接触 / 弯曲)</td><td>${strength ? strength.stages.map(s => `${s.contactSafety.toFixed(2)} / ${s.bendingSafety.toFixed(2)}`).join(" · ") : "-"}</td></tr>
|
||||
<tr><td>装配组件 / 关节 / BOM 行</td><td>${assembly ? `${assembly.components} / ${assembly.joints.length} / ${assembly.bom.rows}` : "-"}</td></tr>
|
||||
<tr><td>求解最大位移</td><td>${assembly ? (assembly.displacement.maxMm < 1e-6 ? "< 1e-6 mm" : assembly.displacement.maxMm.toFixed(2) + " mm") : "-"}</td></tr>
|
||||
<tr><td>页面错误</td><td>${assembly ? (assembly.pageErrors ?? []).length : "-"}</td></tr>
|
||||
</tbody></table></div></section>`;
|
||||
|
||||
let content = sections.map(chapter => chapter.html).join("\n");
|
||||
const pager = chapters.map((chapter, index) => {
|
||||
const prev = chapters[index - 1]; const next = chapters[index + 1];
|
||||
return `${prev ? `<a href="#${esc(prev.id)}">← ${esc(prev.meta.title ?? prev.id)}</a>` : "<span></span>"}
|
||||
${next ? `<a href="#${esc(next.id)}">${esc(next.meta.title ?? next.id)} →</a>` : "<span></span>"}`;
|
||||
}).join("\n");
|
||||
content = content.replace(/<h1 id="ch15">/, `<div class="pager">${pager}</div><h1 id="ch15">`);
|
||||
|
||||
// Validate referenced screenshots before writing.
|
||||
const missing = [];
|
||||
for (const chapter of chapters) {
|
||||
for (const match of chapter.body.matchAll(/!\[[^\]]*\]\(([^)]+)\)/g)) {
|
||||
const src = match[1];
|
||||
if (!src.startsWith("./manual-assets/")) continue;
|
||||
const file = path.join(assetsDir, src.replace("./manual-assets/", ""));
|
||||
if (!fs.existsSync(file)) missing.push(src);
|
||||
}
|
||||
}
|
||||
if (missing.length) throw new Error(`missing screenshots: ${missing.slice(0, 5).join(", ")}`);
|
||||
|
||||
fs.mkdirSync(outAssets, { recursive: true });
|
||||
fs.cpSync(assetsDir, outAssets, { recursive: true });
|
||||
const template = fs.readFileSync(path.join(here, "template.html"), "utf8");
|
||||
const html = template
|
||||
.replaceAll("{{TITLE}}", "二级圆柱齿轮减速器 · Web FreeCAD 初学者手册")
|
||||
.replace("{{SIDEBAR}}", sidebarHtml)
|
||||
.replace("{{CONTENT}}", content)
|
||||
.replace("{{COMMAND_INDEX}}", commandIndex)
|
||||
.replace("{{SEARCH_INDEX}}", JSON.stringify(searchIndex).replace(/</g, "\\u003c"))
|
||||
.replace("{{COMMAND_COUNT}}", String(features.commands.length));
|
||||
fs.writeFileSync(outFile, html);
|
||||
console.log(JSON.stringify({ ok: true, outFile, chapters: chapters.length, sections: sections.length,
|
||||
commands: features.commands.length, searchEntries: searchIndex.length, bytes: fs.statSync(outFile).size }));
|
||||
@@ -4,10 +4,9 @@
|
||||
// node capture.mjs --scenario ../../manual/scenarios/ch01-ui.json [--headed]
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { listOpfsFiles, readOpfsFile, seedOpfsFromBytes } from "../carrier-course/lib/opfs.mjs";
|
||||
import { createActionRunner } from "./lib/actions.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
@@ -31,8 +30,6 @@ const reportDir = path.join(webRoot, "manual", "data", "capture");
|
||||
fs.mkdirSync(shotDir, { recursive: true });
|
||||
fs.mkdirSync(reportDir, { recursive: true });
|
||||
|
||||
const sha256 = file => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
||||
|
||||
async function runOnce() {
|
||||
const browser = await chromium.launch({
|
||||
executablePath: "/usr/bin/google-chrome",
|
||||
@@ -47,167 +44,23 @@ async function runOnce() {
|
||||
page.on("console", message => { if (message.type() === "error") consoleErrors.push(message.text().slice(0, 300)); });
|
||||
const trace = [];
|
||||
const shots = [];
|
||||
|
||||
const record = entry => trace.push({ at: new Date().toISOString(), ...entry });
|
||||
const click = async action => {
|
||||
let locator;
|
||||
if (action.role) locator = page.getByRole(action.role, { name: action.name, exact: action.exact });
|
||||
else {
|
||||
locator = page.locator(action.selector);
|
||||
if (action.hasText) locator = locator.filter({ hasText: action.hasText });
|
||||
if (action.target) locator = locator.locator(action.target);
|
||||
}
|
||||
if (action.nth !== undefined) locator = locator.nth(action.nth);
|
||||
else if (!action.all) locator = locator.first();
|
||||
if (action.optional && (await locator.count()) === 0) return;
|
||||
if (action.all) {
|
||||
const count = await locator.count();
|
||||
for (let index = 0; index < count; index++) await locator.nth(index).click();
|
||||
} else await locator.click({ timeout: action.timeout ?? 30000 });
|
||||
};
|
||||
const shot = async action => {
|
||||
const file = path.join(shotDir, `${action.name}.png`);
|
||||
if (action.selector) {
|
||||
const target = page.locator(action.selector).first();
|
||||
await target.waitFor({ state: "visible", timeout: 30000 });
|
||||
await target.screenshot({ path: file });
|
||||
} else {
|
||||
await page.screenshot({ path: file, fullPage: Boolean(action.fullPage) });
|
||||
}
|
||||
const stat = fs.statSync(file);
|
||||
if (stat.size < 1024) throw new Error(`screenshot too small: ${file}`);
|
||||
shots.push({ id: `${chapter}/${workflow}/${action.name}`, file: path.relative(webRoot, file),
|
||||
bytes: stat.size, sha256: sha256(file), fullPage: Boolean(action.fullPage), selector: action.selector ?? null });
|
||||
record({ action: "shot", name: action.name, bytes: stat.size });
|
||||
};
|
||||
const save = async action => {
|
||||
await page.evaluate(() => { const details = document.querySelector(".file-tools"); if (details) details.open = true; });
|
||||
await page.waitForTimeout(400);
|
||||
const before = await listOpfsFiles(page);
|
||||
await page.locator('button:has-text("保存 FCStd 到 OPFS")').first().click();
|
||||
let after = before; let status = "";
|
||||
for (let attempt = 0; attempt < 40; attempt++) {
|
||||
await page.waitForTimeout(750);
|
||||
after = await listOpfsFiles(page);
|
||||
status = await page.locator("p.status").first().textContent().catch(() => "");
|
||||
if (after.some(name => !before.includes(name) && /\.FCStd$/i.test(name)) || /Saved\s+\S+\.FCStd\s+to OPFS/i.test(status ?? "")) break;
|
||||
}
|
||||
const match = /Saved\s+(\S+\.FCStd)\s+to OPFS/i.exec(status ?? "");
|
||||
const name = match?.[1] ?? after.find(item => !before.includes(item) && /\.FCStd$/i.test(item));
|
||||
if (!name) throw new Error(`save produced no FCStd; status=${status}`);
|
||||
const bytes = (await readOpfsFile(page, name)).bytes;
|
||||
const fixture = path.join(webRoot, "manual", "fixtures", `${chapter}-${workflow}.FCStd`);
|
||||
fs.mkdirSync(path.dirname(fixture), { recursive: true });
|
||||
fs.writeFileSync(fixture, Buffer.from(bytes));
|
||||
record({ action: "save", name, bytes: bytes.length, status });
|
||||
};
|
||||
// The action interpreter is shared with the headed functional suite; only the
|
||||
// evidence destinations and the record sink differ.
|
||||
const runner = createActionRunner(page, {
|
||||
origin, shotDir, shotPrefix: `${chapter}/${workflow}/`, record, shotIndex: shots,
|
||||
fixturePath: path.join(webRoot, "manual", "fixtures", `${chapter}-${workflow}.FCStd`),
|
||||
});
|
||||
|
||||
try {
|
||||
for (const action of scenario.actions) {
|
||||
switch (action.type) {
|
||||
case "goto":
|
||||
await page.goto(`${origin}${action.url}`, { waitUntil: "domcontentloaded", timeout: 120000 });
|
||||
record({ action: "goto", url: action.url });
|
||||
break;
|
||||
case "waitFor":
|
||||
if (action.selector) await page.waitForSelector(action.selector, { timeout: action.timeout ?? 120000 });
|
||||
if (action.text) await page.getByText(action.text, { exact: action.exact ?? false }).first()
|
||||
.waitFor({ state: "visible", timeout: action.timeout ?? 120000 });
|
||||
record({ action: "waitFor", selector: action.selector ?? null, text: action.text ?? null });
|
||||
break;
|
||||
case "click": await click(action); record({ action: "click", selector: action.selector ?? action.name }); break;
|
||||
case "fill":
|
||||
await page.locator(action.selector).first().fill(String(action.value));
|
||||
record({ action: "fill", selector: action.selector, value: action.value });
|
||||
break;
|
||||
case "select":
|
||||
await page.locator(action.selector).first().selectOption(action.label ? { label: action.label } : action.value);
|
||||
record({ action: "select", selector: action.selector, label: action.label ?? action.value });
|
||||
break;
|
||||
case "selectIndex":
|
||||
await page.locator(action.selector).first().selectOption({ index: action.index });
|
||||
record({ action: "selectIndex", selector: action.selector, index: action.index });
|
||||
break;
|
||||
case "press": await page.keyboard.press(action.key); record({ action: "press", key: action.key }); break;
|
||||
case "clickCanvas": {
|
||||
const target = page.locator(action.selector).first();
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(200);
|
||||
const box = await target.boundingBox();
|
||||
if (!box) throw new Error(`canvas missing: ${action.selector}`);
|
||||
await page.mouse.click(box.x + box.width * action.fx, box.y + box.height * action.fy);
|
||||
await page.waitForTimeout(action.wait ?? 250);
|
||||
record({ action: "clickCanvas", selector: action.selector, fx: action.fx, fy: action.fy });
|
||||
break;
|
||||
}
|
||||
case "assertAnyText": {
|
||||
const texts = await page.locator(action.selector).allTextContents();
|
||||
if (!texts.some(text => String(text).includes(action.contains)))
|
||||
throw new Error(`assertAnyText failed: ${action.contains} in ${JSON.stringify(texts.slice(0, 5))}`);
|
||||
record({ action: "assertAnyText", selector: action.selector, contains: action.contains });
|
||||
break;
|
||||
}
|
||||
case "drag": {
|
||||
const box = await page.locator(action.selector).first().boundingBox();
|
||||
if (!box) throw new Error(`drag target missing: ${action.selector}`);
|
||||
const x = box.x + box.width / 2; const y = box.y + box.height / 2;
|
||||
await page.mouse.move(x, y); await page.mouse.down();
|
||||
await page.mouse.move(x + (action.dx ?? 0), y + (action.dy ?? 0), { steps: 18 });
|
||||
await page.mouse.up(); await page.waitForTimeout(400);
|
||||
record({ action: "drag", selector: action.selector, dx: action.dx, dy: action.dy });
|
||||
break;
|
||||
}
|
||||
case "eval":
|
||||
await page.evaluate(action.script);
|
||||
record({ action: "eval" });
|
||||
break;
|
||||
case "seed": {
|
||||
const file = path.resolve(action.file);
|
||||
if (!fs.existsSync(file)) throw new Error(`seed fixture missing: ${file}`);
|
||||
await seedOpfsFromBytes(page, action.name ?? path.basename(file), fs.readFileSync(file));
|
||||
record({ action: "seed", file, name: action.name ?? path.basename(file) });
|
||||
break;
|
||||
}
|
||||
case "shot": await shot(action); break;
|
||||
case "save": await save(action); break;
|
||||
case "assertText": {
|
||||
const text = await page.locator(action.selector).first().textContent();
|
||||
if (!String(text ?? "").includes(action.contains)) throw new Error(`assertText failed: ${action.selector} ${text}`);
|
||||
record({ action: "assertText", selector: action.selector, contains: action.contains });
|
||||
break;
|
||||
}
|
||||
case "assertVisible":
|
||||
await page.locator(action.selector).first().waitFor({ state: "visible", timeout: 30000 });
|
||||
record({ action: "assertVisible", selector: action.selector });
|
||||
break;
|
||||
case "waitOptions": {
|
||||
const locator = page.locator(action.selector).first();
|
||||
let count = 0;
|
||||
for (let attempt = 0; attempt < 80; attempt++) {
|
||||
count = await locator.locator("option").count();
|
||||
if (count >= (action.min ?? 1)) break;
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
if (count < (action.min ?? 1)) throw new Error(`waitOptions failed: ${action.selector} ${count}`);
|
||||
record({ action: "waitOptions", selector: action.selector, count });
|
||||
break;
|
||||
}
|
||||
case "assertValue": {
|
||||
const value = await page.locator(action.selector).first().inputValue();
|
||||
if (String(value) !== String(action.value)) throw new Error(`assertValue failed: ${action.selector} ${value} != ${action.value}`);
|
||||
record({ action: "assertValue", selector: action.selector, value });
|
||||
break;
|
||||
}
|
||||
case "wait": await page.waitForTimeout(action.ms ?? 500); break;
|
||||
default: throw new Error(`unknown action ${action.type}`);
|
||||
}
|
||||
}
|
||||
for (const action of scenario.actions) await runner.run(action);
|
||||
if (pageErrors.length || consoleErrors.length)
|
||||
throw new Error(`page errors: ${JSON.stringify({ pageErrors, consoleErrors })}`);
|
||||
const report = {
|
||||
schema: "freecad-web-manual/capture/v1", generatedAt: new Date().toISOString(),
|
||||
chapter, workflow, scenario: path.relative(webRoot, scenarioPath), origin,
|
||||
ok: true, trace, shots, pageErrors, consoleErrors,
|
||||
ok: true, trace, pageErrors, consoleErrors,
|
||||
shots: shots.map(item => ({ ...item, file: path.relative(webRoot, item.file) })),
|
||||
};
|
||||
fs.writeFileSync(path.join(reportDir, `${chapter}-${workflow}.json`), `${JSON.stringify(report, null, 2)}\n`);
|
||||
return report;
|
||||
|
||||
63
web/tools/manual/check-fcweb-toolkit.mjs
Normal file
63
web/tools/manual/check-fcweb-toolkit.mjs
Normal file
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env node
|
||||
// Verifies the built fcweb toolkit guide in a real browser.
|
||||
//
|
||||
// Reuses tools/fcweb/capture.mjs rather than re-deriving selectors, so the
|
||||
// health metrics (overflow, broken images, page errors) are measured exactly
|
||||
// the same way any other page check measures them.
|
||||
//
|
||||
// MANUAL_URL=http://127.0.0.1:5190/fcweb-toolkit.html node web/tools/manual/check-fcweb-toolkit.mjs
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { launchBrowser, pageCheck, writeArtifact } from "../../../tools/fcweb/capture.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const contentDir = path.join(webRoot, "manual", "fcweb-toolkit", "content");
|
||||
const outDir = path.join(webRoot, "..", "docs", "current", "fcweb-toolkit-check");
|
||||
|
||||
const url = process.env.MANUAL_URL || "http://127.0.0.1:5190/fcweb-toolkit.html";
|
||||
const chapterIds = fs.readdirSync(contentDir)
|
||||
.filter(name => name.endsWith(".md"))
|
||||
.map(name => {
|
||||
const text = fs.readFileSync(path.join(contentDir, name), "utf8");
|
||||
const meta = /^---\n([\s\S]*?)\n---\n/.exec(text);
|
||||
const id = meta ? (/^id:\s*(.+)$/m.exec(meta[1])?.[1]?.trim()) : null;
|
||||
return id ?? name.replace(/\.md$/, "");
|
||||
});
|
||||
|
||||
const browser = await launchBrowser({ headed: false });
|
||||
let report;
|
||||
try {
|
||||
report = await pageCheck(browser, url, {
|
||||
viewports: [{ width: 1440, height: 900 }, { width: 390, height: 844 }],
|
||||
expect: { chapters: chapterIds.length, anchorIds: chapterIds },
|
||||
});
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
// The search box is the one interactive affordance the guide ships; prove it
|
||||
// can find a known API name rather than just render.
|
||||
const missingChapters = report.viewports
|
||||
.flatMap(viewport => viewport.missingIds)
|
||||
.filter(id => chapterIds.includes(id));
|
||||
|
||||
const summary = {
|
||||
ok: report.ok && missingChapters.length === 0,
|
||||
url,
|
||||
chapters: chapterIds.length,
|
||||
missingChapters: [...new Set(missingChapters)],
|
||||
viewports: report.viewports.map(viewport => ({
|
||||
viewport: viewport.viewport,
|
||||
status: viewport.status,
|
||||
overflow: viewport.overflow,
|
||||
brokenImages: viewport.brokenImages.length,
|
||||
pageErrors: viewport.pageErrors.length,
|
||||
failedRequests: viewport.failedRequests.length,
|
||||
ok: viewport.ok,
|
||||
})),
|
||||
};
|
||||
writeArtifact(outDir, "fcweb-toolkit-page-check.json", summary);
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
process.exit(summary.ok ? 0 : 1);
|
||||
66
web/tools/manual/check-parts-manual.mjs
Normal file
66
web/tools/manual/check-parts-manual.mjs
Normal file
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env node
|
||||
// Desktop + mobile check for the part-design handout: overflow, page errors,
|
||||
// broken images, chapter count, and that every part is illustrated.
|
||||
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 webRoot = path.resolve(here, "../..");
|
||||
const require = createRequire(path.join(webRoot, "package.json"));
|
||||
const { chromium } = require("playwright");
|
||||
const url = process.env.MANUAL_URL || "http://127.0.0.1:5190/reducer-parts-manual.html";
|
||||
const specs = JSON.parse(fs.readFileSync(path.join(webRoot, "tools", "reducer-parts-course", "parts-spec.json"), "utf8"));
|
||||
|
||||
const browser = await chromium.launch({ executablePath: "/usr/bin/google-chrome", headless: true,
|
||||
args: ["--no-sandbox", "--enable-unsafe-swiftshader", "--use-gl=angle", "--use-angle=swiftshader"] });
|
||||
const report = { schema: "freecad-web-reducer-parts-manual/page-check/v1", generatedAt: new Date().toISOString(), url, viewports: [] };
|
||||
|
||||
for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) {
|
||||
const page = await browser.newPage({ viewport });
|
||||
const errors = []; const failed = [];
|
||||
page.on("pageerror", error => errors.push(String(error)));
|
||||
page.on("console", message => { if (message.type() === "error") errors.push(message.text().slice(0, 200)); });
|
||||
page.on("response", response => { if (response.status() >= 400) failed.push(`${response.status()} ${response.url()}`); });
|
||||
const response = await page.goto(url, { waitUntil: "load", timeout: 120000 });
|
||||
await page.waitForTimeout(600);
|
||||
await page.evaluate(() => { for (const image of document.images) image.loading = "eager"; });
|
||||
await page.waitForTimeout(2000);
|
||||
const metrics = await page.evaluate(() => {
|
||||
const images = [...document.images];
|
||||
return {
|
||||
chapters: document.querySelectorAll("nav.sidebar .chapter").length,
|
||||
sections: document.querySelectorAll("main h2[id]").length,
|
||||
images: images.length,
|
||||
brokenImages: images.filter(image => image.src && (!image.complete || image.naturalWidth === 0)).map(image => image.src),
|
||||
figures: document.querySelectorAll("main img").length,
|
||||
// The appendix heading is an <h1>, so the table is a following sibling
|
||||
// rather than a descendant.
|
||||
appendixRows: (() => {
|
||||
const heading = document.getElementById("appendix");
|
||||
for (let node = heading?.nextElementSibling; node; node = node.nextElementSibling) {
|
||||
const table = node.matches(".table-scroll") ? node : node.querySelector?.(".table-scroll");
|
||||
if (table) return table.querySelectorAll("tbody tr").length;
|
||||
if (node.matches("h1")) break;
|
||||
}
|
||||
return 0;
|
||||
})(),
|
||||
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||
};
|
||||
});
|
||||
if (viewport.width === 1440) await page.screenshot({ path: path.join(webRoot, "teaching", "reducer-parts-manual.png"), fullPage: false });
|
||||
report.viewports.push({ viewport, status: response?.status(), errors, failed, ...metrics });
|
||||
await page.close();
|
||||
}
|
||||
await browser.close();
|
||||
|
||||
const expectedChapters = 15;
|
||||
report.ok = report.viewports.every(item => item.status === 200 && item.errors.length === 0
|
||||
&& item.failed.length === 0 && item.brokenImages.length === 0 && item.overflow === 0
|
||||
&& item.chapters === expectedChapters && item.figures >= 50
|
||||
&& item.appendixRows === specs.episodes.length);
|
||||
fs.mkdirSync(path.join(webRoot, "manual", "reducer-parts", "data"), { recursive: true });
|
||||
fs.writeFileSync(path.join(webRoot, "manual", "reducer-parts", "data", "page-check.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ ok: report.ok, viewports: report.viewports.map(v => ({ w: v.viewport.width, chapters: v.chapters, figures: v.figures, overflow: v.overflow, broken: v.brokenImages.length, errors: v.errors.length, rows: v.appendixRows })) }));
|
||||
process.exitCode = report.ok ? 0 : 1;
|
||||
74
web/tools/manual/check-reducer-manual.mjs
Normal file
74
web/tools/manual/check-reducer-manual.mjs
Normal file
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env node
|
||||
// Checks the reducer manual on desktop and mobile: overflow, page errors,
|
||||
// broken images, chapter count, search, and that the appendix's build record
|
||||
// and gap list actually rendered. Writes manual/reducer/data/page-check.json.
|
||||
//
|
||||
// This is a separate checker from check-page.mjs because the two manuals have
|
||||
// genuinely different appendices: the generic one indexes 1500+ commands, the
|
||||
// reducer one records this case's build steps, gaps and acceptance numbers.
|
||||
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 webRoot = path.resolve(here, "../..");
|
||||
const require = createRequire(path.join(webRoot, "package.json"));
|
||||
const { chromium } = require("playwright");
|
||||
const url = process.env.MANUAL_URL || "http://127.0.0.1:5190/reducer-manual.html";
|
||||
const browser = await chromium.launch({ executablePath: "/usr/bin/google-chrome", headless: true,
|
||||
args: ["--no-sandbox", "--enable-unsafe-swiftshader", "--use-gl=angle", "--use-angle=swiftshader"] });
|
||||
const report = { schema: "freecad-web-reducer-manual/page-check/v1", generatedAt: new Date().toISOString(), url, viewports: [] };
|
||||
for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) {
|
||||
const page = await browser.newPage({ viewport });
|
||||
const errors = []; const failed = [];
|
||||
page.on("pageerror", error => errors.push(String(error)));
|
||||
page.on("console", message => { if (message.type() === "error") errors.push(message.text().slice(0, 200)); });
|
||||
page.on("response", response => { if (response.status() >= 400) failed.push(`${response.status()} ${response.url()}`); });
|
||||
const response = await page.goto(url, { waitUntil: "load", timeout: 120000 });
|
||||
await page.waitForTimeout(800);
|
||||
await page.evaluate(() => { for (const image of document.images) image.loading = "eager"; });
|
||||
await page.waitForTimeout(1500);
|
||||
const metrics = await page.evaluate(() => {
|
||||
const images = [...document.images];
|
||||
return {
|
||||
chapters: document.querySelectorAll('nav.sidebar .chapter').length,
|
||||
sections: document.querySelectorAll('main h2[id]').length,
|
||||
images: images.length,
|
||||
brokenImages: images.filter(image => image.src && (!image.complete || image.naturalWidth === 0)).map(image => image.src),
|
||||
// Walk from each appendix heading to the next table, skipping the <p>
|
||||
// that sits between them in the generated HTML.
|
||||
...(() => {
|
||||
const rowsAfter = id => {
|
||||
const heading = document.querySelector(`h2[id^="${id}"]`);
|
||||
if (!heading) return 0;
|
||||
for (let node = heading.nextElementSibling; node; node = node.nextElementSibling) {
|
||||
const table = node.matches(".table-scroll") ? node : node.querySelector?.(".table-scroll");
|
||||
if (table) return table.querySelectorAll("tbody tr").length;
|
||||
if (node.matches("h1, h2")) break;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
return { buildRows: rowsAfter("ch15-steps"), gapRows: rowsAfter("ch15-gaps"),
|
||||
partRows: rowsAfter("ch15-parts"), numbersRows: rowsAfter("ch15-numbers") };
|
||||
})(),
|
||||
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||
searchSize: SEARCH_INDEX.length,
|
||||
};
|
||||
});
|
||||
await page.locator('#search').fill('轴承');
|
||||
await page.waitForTimeout(300);
|
||||
const searchHits = await page.locator('#search-results a').count();
|
||||
if (viewport.width === 1440) await page.screenshot({ path: path.join(webRoot, "teaching", "reducer-manual.png"), fullPage: false });
|
||||
report.viewports.push({ viewport, status: response?.status(), errors, failed, searchHits, ...metrics });
|
||||
await page.close();
|
||||
}
|
||||
await browser.close();
|
||||
report.ok = report.viewports.every(item => item.status === 200 && item.errors.length === 0
|
||||
&& item.failed.length === 0 && item.brokenImages.length === 0 && item.overflow === 0
|
||||
&& item.chapters === 13 && item.buildRows > 50 && item.gapRows >= 20
|
||||
&& item.searchHits > 0);
|
||||
fs.mkdirSync(path.join(webRoot, "manual", "reducer", "data"), { recursive: true });
|
||||
fs.writeFileSync(path.join(webRoot, "manual", "reducer", "data", "page-check.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify(report));
|
||||
process.exitCode = report.ok ? 0 : 1;
|
||||
106
web/tools/manual/check-ui-design-doc.mjs
Normal file
106
web/tools/manual/check-ui-design-doc.mjs
Normal file
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env node
|
||||
// Verify the generated UI design document in a real browser.
|
||||
//
|
||||
// Reuses tools/fcweb/capture.mjs. Checks structure (chapter anchors, appendix
|
||||
// row count), page health (errors, broken images, overflow) at two viewports,
|
||||
// and that every screenshot the document references actually exists.
|
||||
//
|
||||
// node web/tools/manual/check-ui-design-doc.mjs
|
||||
// DOC_URL=http://127.0.0.1:5199/evidence/current/web-freecad-ui-layout-and-functions.html \
|
||||
// node web/tools/manual/check-ui-design-doc.mjs
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { launchBrowser, openPage, writeArtifact } from "../../../tools/fcweb/capture.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const docPath = path.join(repoRoot, "docs/current/web-freecad-ui-layout-and-functions.html");
|
||||
const inventoryPath = path.join(repoRoot, "tools/fcweb/out/ui-inventory.json");
|
||||
const outDir = path.join(repoRoot, "docs/current/ui-design/data");
|
||||
|
||||
if (!fs.existsSync(docPath)) {
|
||||
console.error(`[check-ui-design-doc] missing document: ${docPath}`);
|
||||
process.exit(2);
|
||||
}
|
||||
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
|
||||
const expectedChapters = inventory.chapters.map(chapter => `wb-${chapter.id}`);
|
||||
const expectedAppendix = inventory.appendix.length;
|
||||
|
||||
const url = process.env.DOC_URL || pathToFileURL(docPath).href;
|
||||
const browser = await launchBrowser({ headed: false });
|
||||
const viewports = [{ width: 1440, height: 900 }, { width: 390, height: 844 }];
|
||||
const reports = [];
|
||||
|
||||
try {
|
||||
for (const viewport of viewports) {
|
||||
const { page, response, errors, failedRequests } = await openPage(browser, url, { viewport });
|
||||
try {
|
||||
// Force lazy images to load so the broken-image check is meaningful.
|
||||
await page.evaluate(async () => {
|
||||
for (const image of document.images) image.loading = "eager";
|
||||
window.scrollTo(0, document.body.scrollHeight);
|
||||
await new Promise(resolve => setTimeout(resolve, 800));
|
||||
window.scrollTo(0, 0);
|
||||
});
|
||||
await page.waitForTimeout(600);
|
||||
|
||||
const dom = await page.evaluate(() => {
|
||||
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 ids = [...document.querySelectorAll("[id]")].map(node => node.id);
|
||||
const duplicated = ids.filter((id, index) => ids.indexOf(id) !== index);
|
||||
return {
|
||||
overflow: Math.max(0, doc.scrollWidth - doc.clientWidth),
|
||||
brokenImages,
|
||||
ids,
|
||||
duplicatedIds: [...new Set(duplicated)],
|
||||
chapters: document.querySelectorAll("section.wb").length,
|
||||
appendixRows: document.querySelectorAll("tr[data-appendix-row]").length,
|
||||
tocLinks: document.querySelectorAll("nav.toc a").length,
|
||||
images: document.images.length,
|
||||
};
|
||||
});
|
||||
|
||||
const missing = expectedChapters.filter(id => !dom.ids.includes(id));
|
||||
reports.push({
|
||||
viewport,
|
||||
status: response?.status() ?? null,
|
||||
...dom,
|
||||
missingChapters: missing,
|
||||
pageErrors: errors,
|
||||
failedRequests: failedRequests.slice(0, 5),
|
||||
ok: (response?.status() ?? 0) === 200
|
||||
&& errors.length === 0
|
||||
&& failedRequests.length === 0
|
||||
&& dom.brokenImages.length === 0
|
||||
&& dom.overflow === 0
|
||||
&& missing.length === 0
|
||||
&& dom.duplicatedIds.length === 0
|
||||
&& dom.chapters === inventory.chapters.length
|
||||
&& dom.appendixRows === expectedAppendix,
|
||||
});
|
||||
} finally {
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
const summary = {
|
||||
ok: reports.every(report => report.ok),
|
||||
url,
|
||||
expectedChapters: expectedChapters.length,
|
||||
expectedAppendixRows: expectedAppendix,
|
||||
viewports: reports,
|
||||
};
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(outDir, "doc-check.json"), `${JSON.stringify(summary, null, 2)}\n`);
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
writeArtifact(outDir, "doc-check-last-run.json", summary);
|
||||
process.exit(summary.ok ? 0 : 1);
|
||||
@@ -55,6 +55,7 @@ const chapters = [
|
||||
{ id: "ch13", order: 13, level: "specialist", title: "Draft、Plot、Robot 等专项工具", moduleIds: ["Draft", "Plot", "Robot", "Cloud", "JtReader", "Sandbox", "Test", "Tux", "TemplatePyMod", "Show"] },
|
||||
{ id: "ch14", order: 14, level: "case", title: "综合案例:27 件 GLB 产线", moduleIds: [] },
|
||||
{ id: "ch15", order: 15, level: "appendix", title: "附录:命令索引与缺口", moduleIds: [] },
|
||||
{ id: "ch16", order: 16, level: "appendix", title: "全功能面板索引与实现映射", moduleIds: [] },
|
||||
];
|
||||
|
||||
const moduleChapter = new Map();
|
||||
|
||||
106
web/tools/manual/generate-final-status.mjs
Normal file
106
web/tools/manual/generate-final-status.mjs
Normal file
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env node
|
||||
// Derives web/manual/data/final-status.json from the real pipeline outputs so
|
||||
// the summary never drifts from the generated manual:
|
||||
//
|
||||
// manual-features.json commands / modules / boundaries / chapters
|
||||
// gap-ledger.json verified case count and known boundaries
|
||||
// page-check.json last browser check (overflow, images, sections)
|
||||
// capture/*.json screenshot capture reports
|
||||
// manual-assets/** actual PNG files on disk
|
||||
//
|
||||
// node tools/manual/generate-final-status.mjs
|
||||
// node tools/manual/generate-final-status.mjs --check # exit 1 on drift
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const dataDir = path.join(webRoot, "manual", "data");
|
||||
const read = name => JSON.parse(fs.readFileSync(path.join(dataDir, name), "utf8"));
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
const outPath = path.join(dataDir, "final-status.json");
|
||||
|
||||
const features = read("manual-features.json");
|
||||
const ledger = read("gap-ledger.json");
|
||||
const pageCheck = read("page-check.json");
|
||||
|
||||
const captureDir = path.join(dataDir, "capture");
|
||||
const captureReports = fs.existsSync(captureDir)
|
||||
? fs.readdirSync(captureDir).filter(name => name.endsWith(".json")).sort()
|
||||
: [];
|
||||
let screenshotsCaptured = 0;
|
||||
for (const name of captureReports) {
|
||||
const report = JSON.parse(fs.readFileSync(path.join(captureDir, name), "utf8"));
|
||||
screenshotsCaptured += (report.shots ?? []).length;
|
||||
}
|
||||
|
||||
const assetsDir = path.join(webRoot, "manual", "assets");
|
||||
const countPngs = dir => fs.readdirSync(dir, { withFileTypes: true }).reduce((total, entry) => {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) return total + countPngs(full);
|
||||
return total + (entry.name.endsWith(".png") ? 1 : 0);
|
||||
}, 0);
|
||||
const screenshots = fs.existsSync(assetsDir) ? countPngs(assetsDir) : 0;
|
||||
|
||||
const appChapters = features.chapters.filter(chapter => chapter.level !== "appendix").length;
|
||||
const desktop = pageCheck.viewports.find(view => view.viewport.width >= 900) ?? pageCheck.viewports[0] ?? null;
|
||||
const mobile = pageCheck.viewports.find(view => view.viewport.width < 900) ?? null;
|
||||
const gapRegisterPath = path.join(webRoot, "..", "docs/current/ui-design/data/gap-register.json");
|
||||
const gapRegister = fs.existsSync(gapRegisterPath)
|
||||
? JSON.parse(fs.readFileSync(gapRegisterPath, "utf8"))
|
||||
: null;
|
||||
|
||||
const state = pageCheck.ok && (gapRegister ? gapRegister.ok : false) ? "complete" : "in-progress";
|
||||
const status = {
|
||||
schema: "freecad-web-manual/final-status/v1",
|
||||
generatedAt: new Date().toISOString(),
|
||||
state,
|
||||
chapters: appChapters,
|
||||
chaptersWithAppendix: features.chapters.length,
|
||||
screenshots,
|
||||
commands: features.stats.commands,
|
||||
modules: features.stats.modules,
|
||||
nativeHandlers: features.stats.nativeHandlers,
|
||||
verifiedCommands: ledger.verified,
|
||||
workflows: captureReports.length,
|
||||
boundaries: (features.boundaries ?? []).length,
|
||||
pageCheck: {
|
||||
ok: pageCheck.ok,
|
||||
desktopOverflow: desktop?.overflow ?? null,
|
||||
mobileOverflow: mobile?.overflow ?? null,
|
||||
brokenImages: desktop?.brokenImages ?? [],
|
||||
searchHits: desktop?.searchHits ?? 0,
|
||||
images: desktop?.images ?? 0,
|
||||
sections: desktop?.sections ?? 0,
|
||||
},
|
||||
entry: "web/teaching/manual.html",
|
||||
url: pageCheck.url,
|
||||
assets: "web/teaching/manual-assets",
|
||||
captureReports: "web/manual/data/capture",
|
||||
gapLedger: "web/manual/data/gap-ledger.json",
|
||||
knownBoundaries: (ledger.boundaries ?? []).map(item => item.title),
|
||||
notes: [
|
||||
"由 generate-final-status.mjs 自动派生,不要手改。",
|
||||
`UI 表面清单:${gapRegister ? gapRegister.counts.surfaces : "未生成"} 项,缺口 ${gapRegister ? gapRegister.issues.filter(issue => issue.problem === "ui-gap").length : "未知"} 项。`,
|
||||
],
|
||||
screenshotsCaptured,
|
||||
};
|
||||
|
||||
const text = `${JSON.stringify(status, null, 2)}\n`;
|
||||
|
||||
if (check) {
|
||||
const previous = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : "";
|
||||
const strip = value => JSON.stringify({ ...JSON.parse(value), generatedAt: "__stable__" });
|
||||
if (!previous || strip(previous) !== strip(text)) {
|
||||
console.error("[generate-final-status] --check: final-status.json is stale");
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, checked: "web/manual/data/final-status.json" }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.writeFileSync(outPath, text);
|
||||
console.log(JSON.stringify({ ok: true, out: "web/manual/data/final-status.json", state, chapters: features.chapters.length, screenshots, commands: features.stats.commands }));
|
||||
117
web/tools/manual/generate-gaps-doc.mjs
Normal file
117
web/tools/manual/generate-gaps-doc.mjs
Normal file
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env node
|
||||
// Derives docs/current/web-freecad-manual-gaps.md from the real pipeline outputs so
|
||||
// the gap register never drifts from final-status.json / gap-ledger.json /
|
||||
// gap-register.json. The previous hand-written copy still described the retired
|
||||
// 32-module inventory, which is why this file is generated instead of maintained.
|
||||
//
|
||||
// node web/tools/manual/generate-gaps-doc.mjs
|
||||
// node web/tools/manual/generate-gaps-doc.mjs --check # exit 1 on drift
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const dataDir = path.join(webRoot, "manual", "data");
|
||||
const outPath = path.join(repoRoot, "docs", "current", "web-freecad-manual-gaps.md");
|
||||
const gapRegisterPath = path.join(repoRoot, "docs", "current", "ui-design", "data", "gap-register.json");
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
|
||||
const read = file => JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
const status = read(path.join(dataDir, "final-status.json"));
|
||||
const ledger = read(path.join(dataDir, "gap-ledger.json"));
|
||||
const register = fs.existsSync(gapRegisterPath) ? read(gapRegisterPath) : null;
|
||||
|
||||
const cell = value => String(value ?? "—").replace(/\|/g, "\\|");
|
||||
const lines = [];
|
||||
const push = (...items) => lines.push(...items);
|
||||
|
||||
push("# Web FreeCAD 手册与界面文档 · 缺口与边界账本", "");
|
||||
push("> 本文件由 `web/tools/manual/generate-gaps-doc.mjs` 从真实产物派生,**不要手改**。");
|
||||
push("> 输入:`web/manual/data/final-status.json`、`web/manual/data/gap-ledger.json`、`docs/current/ui-design/data/gap-register.json`。");
|
||||
push("> 复核:`node web/tools/manual/generate-gaps-doc.mjs --check`。", "");
|
||||
|
||||
push("## 口径", "");
|
||||
push(`- 模块数 **${status.modules}**(不含已整体摘除的 OpenSCAD)。`);
|
||||
push(`- 命令矩阵 **${status.commands}** 条,原生承接 **${status.nativeHandlers}** 条。`);
|
||||
push(`- 手工验证命令 **${status.verifiedCommands}** 条;已知边界 **${(ledger.boundaries ?? []).length}** 条。`);
|
||||
push(`- 手册 **${status.chaptersWithAppendix}** 章(正文 ${status.chapters} 章 + 附录章)、页面截图引用 **${status.pageCheck.images}** 处、磁盘 PNG **${status.screenshots}** 个。`);
|
||||
if (register) {
|
||||
const byCategory = register.counts.byCategory ?? {};
|
||||
push(`- UI 表面 **${register.counts.surfaces}** 项:${Object.entries(byCategory).map(([key, value]) => `${key} ${value}`).join(" / ")}。`);
|
||||
const partial = (register.surfaces ?? []).filter(item => item.status === "partial").length;
|
||||
const gap = (register.surfaces ?? []).filter(item => item.status === "gap").length;
|
||||
push(`- 表面状态:implemented ${register.counts.surfaces - partial - gap} / partial ${partial} / gap **${gap}**。`);
|
||||
}
|
||||
push("");
|
||||
|
||||
push("## 已实现的界面覆盖(不是缺口)", "");
|
||||
push("| 项 | 结果 |");
|
||||
push("|---|---|");
|
||||
push(`| 界面设计文档 | \`docs/current/web-freecad-ui-layout-and-functions.html\`,${status.chaptersWithAppendix} 章 + 命令附录 |`);
|
||||
push(`| 手册 | \`web/teaching/manual.html\`,${status.chapters} 章 ${status.pageCheck.sections} 节 |`);
|
||||
push(`| 截图 | 页面引用 ${status.pageCheck.images} 处;磁盘 ${status.screenshots} 个 PNG;采集报告 ${status.workflows} 份 |`);
|
||||
push(`| 浏览器校验 | 桌面 overflow ${status.pageCheck.desktopOverflow} / 移动 overflow ${status.pageCheck.mobileOverflow} / 破图 ${status.pageCheck.brokenImages.length} |`);
|
||||
push("");
|
||||
|
||||
push(`## 已知边界(${(ledger.boundaries ?? []).length} 条)`, "");
|
||||
push("| ID | 模块 | 边界 | 状态 |");
|
||||
push("|---|---|---|---|");
|
||||
for (const item of ledger.boundaries ?? []) {
|
||||
push(`| \`${cell(item.id)}\` | ${cell(item.module)} | ${cell(item.detail)} | ${cell(item.status)} |`);
|
||||
}
|
||||
push("");
|
||||
|
||||
push("## 手工验证的用例", "");
|
||||
push(`共 **${ledger.verified}** 条(台账 \`${path.relative(repoRoot, path.join(dataDir, "gap-ledger.json"))}\`)。`);
|
||||
for (const note of ledger.notes ?? []) push(`- ${note}`);
|
||||
push("");
|
||||
|
||||
if (register) {
|
||||
const flagged = (register.surfaces ?? []).filter(item => item.status === "partial" || item.status === "gap");
|
||||
push(`## 界面表面审计(${register.counts.surfaces} 项,问题 ${register.issues.length} 项)`, "");
|
||||
if (flagged.length) {
|
||||
push("| 表面 | 分类 | 状态 | 注释 |");
|
||||
push("|---|---|---|---|");
|
||||
for (const item of flagged) push(`| ${cell(item.nameZh)} | ${cell(item.category)} | ${cell(item.status)} | ${cell(item.note ?? "—")} |`);
|
||||
} else {
|
||||
push("没有 `partial` 或 `gap` 项。");
|
||||
}
|
||||
push("");
|
||||
push("审计命令:`node web/tools/manual/audit-ui-gaps.mjs --check`。");
|
||||
push("");
|
||||
}
|
||||
|
||||
push("## 复现命令", "");
|
||||
push("```bash");
|
||||
push(`R="/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD"`);
|
||||
push(`node "$R/tools/fcweb/ui-surface-inventory.mjs" --check`);
|
||||
push(`node "$R/tools/fcweb/build-ui-doc.mjs" --check`);
|
||||
push(`node "$R/web/tools/manual/audit-ui-gaps.mjs" --check`);
|
||||
push(`node "$R/web/tools/manual/generate-gaps-doc.mjs" --check`);
|
||||
push(`cd "$R/web" && npm run build:manual && npm run check:manual`);
|
||||
push("```");
|
||||
push("");
|
||||
push("## 边界判定口径", "");
|
||||
push("- 前置未满足(缺文档、缺 Worker、缺原生对象)记边界并保留产品原始错误文本,不写成产品回归。");
|
||||
push("- GUI 控件缺口用 React 组件补齐,不以 GUI-only 名义留作 blocked。");
|
||||
push("- 空白或占位截图不得入库;空白工具栏裁剪由 `build-ui-doc.mjs` 的 1024 字节门槛自动跳过。");
|
||||
push("- 生成物(本文件、第 16 章、`final-status.json`)一律由脚本产出并带 `--check`。");
|
||||
push("");
|
||||
|
||||
const text = `${lines.join("\n")}\n`;
|
||||
if (check) {
|
||||
const previous = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : "";
|
||||
if (previous !== text) {
|
||||
console.error("[generate-gaps-doc] --check: docs/current/web-freecad-manual-gaps.md is stale");
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, checked: "docs/current/web-freecad-manual-gaps.md" }));
|
||||
process.exit(0);
|
||||
}
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, text);
|
||||
console.log(JSON.stringify({ ok: true, out: "docs/current/web-freecad-manual-gaps.md", bytes: Buffer.byteLength(text), boundaries: (ledger.boundaries ?? []).length, surfaces: register?.counts.surfaces ?? null }));
|
||||
203
web/tools/manual/generate-panel-index.mjs
Normal file
203
web/tools/manual/generate-panel-index.mjs
Normal file
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env node
|
||||
// Generates web/manual/content/ch16-panel-index.md from the authoritative UI
|
||||
// surface inventory (tools/fcweb/out/ui-surface-inventory.json).
|
||||
//
|
||||
// The chapter is a reference appendix: every shell region, dock, task panel,
|
||||
// modal dialog, preference page, menu, toolbar, status bar item and viewport
|
||||
// tool with its React owner and desktop reference. Deterministic output: no
|
||||
// timestamps, sorted by category then module then id.
|
||||
//
|
||||
// node tools/manual/generate-panel-index.mjs
|
||||
// node tools/manual/generate-panel-index.mjs --check # exit 1 on drift
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webRoot = path.resolve(here, "../..");
|
||||
const repoRoot = path.resolve(webRoot, "..");
|
||||
const inventoryPath = path.join(repoRoot, "tools/fcweb/out/ui-surface-inventory.json");
|
||||
const outPath = path.join(webRoot, "manual/content/ch16-panel-index.md");
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes("--check");
|
||||
|
||||
if (!fs.existsSync(inventoryPath)) {
|
||||
console.error(`[generate-panel-index] missing ${inventoryPath}; run tools/fcweb/ui-surface-inventory.mjs first`);
|
||||
process.exit(2);
|
||||
}
|
||||
const inventory = JSON.parse(fs.readFileSync(inventoryPath, "utf8"));
|
||||
|
||||
const CATEGORY_ORDER = ["shell-region", "statusbar", "viewport-tool", "dock", "task-panel", "modal-dialog", "preferences-page", "menu", "toolbar"];
|
||||
const CATEGORY_TITLE = {
|
||||
"shell-region": "壳层区域",
|
||||
statusbar: "状态栏",
|
||||
"viewport-tool": "视口工具",
|
||||
dock: "停靠面板",
|
||||
"task-panel": "任务面板",
|
||||
"modal-dialog": "模态对话框",
|
||||
"preferences-page": "偏好设置页",
|
||||
menu: "菜单",
|
||||
toolbar: "工具栏",
|
||||
};
|
||||
const CATEGORY_INTRO = {
|
||||
"shell-region": "主窗口骨架:标题栏、工作台切换器、菜单栏容器、工具栏容器、视口、停靠区、底部报告区、命令面板与快捷键入口。",
|
||||
statusbar: "底部状态栏:文档名、保存状态、网格与渲染统计。",
|
||||
"viewport-tool": "三维视口右上角与导航立方体旁的视图工具:视图切换、剖切面、导航方式等。",
|
||||
dock: "可停靠面板:模型树、属性编辑器、任务面板宿主等,由右侧停靠区承载,可折叠、可切换。",
|
||||
"task-panel": "工作台任务面板:每个 `<module>-<feature>-task.tsx` 对应一个桌面 TaskDialog 参数页,统一由 `TaskFrame` 挂载。",
|
||||
"modal-dialog": "应用级模态对话框:阻断主界面交互、需要确认或选择后才能继续的操作。",
|
||||
"preferences-page": "偏好设置对话框的分页,对应桌面 Edit → Preferences。",
|
||||
menu: "菜单栏条目:按工作台聚合,每项菜单展开后给出命令列表。",
|
||||
toolbar: "工具栏组:每个工作台一组,命令与桌面工具栏一一对应。",
|
||||
};
|
||||
const STATUS_ZH = { implemented: "已实现", partial: "部分实现", gap: "缺口", boundary: "边界" };
|
||||
|
||||
const esc = value => String(value ?? "")
|
||||
.replace(/\|/g, "\\|")
|
||||
.replace(/\n+/g, " ")
|
||||
.trim();
|
||||
|
||||
const surfaceRows = inventory.surfaces
|
||||
.slice()
|
||||
.sort((a, b) => {
|
||||
const ca = CATEGORY_ORDER.indexOf(a.category);
|
||||
const cb = CATEGORY_ORDER.indexOf(b.category);
|
||||
if (ca !== cb) return ca - cb;
|
||||
const ma = a.moduleId ?? "";
|
||||
const mb = b.moduleId ?? "";
|
||||
if (ma !== mb) return ma.localeCompare(mb, "en");
|
||||
return a.id.localeCompare(b.id, "en");
|
||||
});
|
||||
|
||||
const byCategory = new Map();
|
||||
for (const surface of surfaceRows) {
|
||||
if (!byCategory.has(surface.category)) byCategory.set(surface.category, []);
|
||||
byCategory.get(surface.category).push(surface);
|
||||
}
|
||||
|
||||
const counts = inventory.counts;
|
||||
const lines = [];
|
||||
lines.push("---");
|
||||
lines.push("id: ch16");
|
||||
lines.push("order: 16");
|
||||
lines.push("title: 全功能面板索引与实现映射");
|
||||
lines.push("level: appendix");
|
||||
lines.push("---");
|
||||
lines.push("");
|
||||
lines.push("# 第 16 章 全功能面板索引与实现映射");
|
||||
lines.push("");
|
||||
lines.push("本章由 `tools/fcweb/ui-surface-inventory.mjs` 生成,是 Web FreeCAD 全部界面表面的权威索引。");
|
||||
lines.push(`当前共 **${counts.total}** 个界面表面,覆盖 ${Object.keys(counts.byCategory).length} 类;状态分布:` +
|
||||
Object.entries(counts.byStatus).map(([status, count]) => `${STATUS_ZH[status] ?? status} ${count}`).join("、") +
|
||||
"(缺口 " + counts.gaps + " 项)。");
|
||||
lines.push("");
|
||||
lines.push("> 改动 `web/src` 后请重跑 `node tools/fcweb/ui-surface-inventory.mjs` 与本生成器,不要手改本章。");
|
||||
lines.push("");
|
||||
lines.push("## 16.1 分类总览");
|
||||
lines.push("");
|
||||
lines.push("| 类别 | 数量 | 说明 |");
|
||||
lines.push("| --- | ---: | --- |");
|
||||
for (const category of CATEGORY_ORDER) {
|
||||
const rows = byCategory.get(category) ?? [];
|
||||
lines.push(`| ${CATEGORY_TITLE[category]}(\`${category}\`) | ${rows.length} | ${esc(CATEGORY_INTRO[category])} |`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("### 状态口径");
|
||||
lines.push("");
|
||||
lines.push("| 状态 | 含义 |");
|
||||
lines.push("| --- | --- |");
|
||||
lines.push("| 已实现 | React 组件存在、已注册并能从界面到达,有对应命令或路由。 |");
|
||||
lines.push("| 部分实现 | 组件存在但未完全注册/挂载,或仅覆盖桌面能力的一部分。 |");
|
||||
lines.push("| 缺口 | 桌面 FreeCAD 有、Web 端缺失。按项目铁律用 React 组件补齐,不得留作 blocked。 |");
|
||||
lines.push("| 边界 | 受内核或平台限制无法实现(如跨 Worker 文档桥),需写明原因与解除条件。 |");
|
||||
lines.push("");
|
||||
lines.push("## 16.2 界面表面实拍");
|
||||
lines.push("");
|
||||
lines.push("以下截图由 `web/manual/scenarios/ch16-shell-surfaces.json` 在真实运行的 Web FreeCAD 上采集(Playwright,1440×900)。");
|
||||
lines.push("");
|
||||
const SHOTS = [
|
||||
["01-shell-overview", "完整壳层:应用菜单栏、工作台工具栏、对象树、属性面板、三维视口、任务区与文档标签。"],
|
||||
["02-tools-menu", "Tools 菜单:偏好设置、快捷键定制、命令面板入口。"],
|
||||
["03-preferences", "偏好设置对话框:单位制、导航风格、视图与保存选项。"],
|
||||
["04-shortcuts", "快捷键编辑器:按命令搜索并重绑按键。"],
|
||||
["05-command-palette", "命令面板(Ctrl+Shift+P):模糊搜索全部已注册命令。"],
|
||||
["06-bottom-dock", "底部停靠:Selection view / Report view / Python console 三个页签,可浮动、可全屏。"],
|
||||
["07-viewport-tools", "视口工具条:移动 / 旋转 / 关闭、局部坐标、「局部坐标…」编辑入口与位置读数。"],
|
||||
["08-task-panel", "任务面板:Part 立方体创建任务,含 Box dimensions、Volume 与 Bounds,底部为关闭与取消按钮。"],
|
||||
];
|
||||
for (const [name, caption] of SHOTS) {
|
||||
lines.push(``);
|
||||
lines.push("");
|
||||
}
|
||||
lines.push("");
|
||||
|
||||
let sectionNumber = 3;
|
||||
for (const category of CATEGORY_ORDER) {
|
||||
const rows = byCategory.get(category) ?? [];
|
||||
if (!rows.length) continue;
|
||||
lines.push(`## 16.${sectionNumber} ${CATEGORY_TITLE[category]}(${rows.length})`);
|
||||
lines.push("");
|
||||
lines.push(CATEGORY_INTRO[category]);
|
||||
lines.push("");
|
||||
lines.push("| 名称 | React 实现 | 桌面参考 | 状态 | 注释 |");
|
||||
lines.push("| --- | --- | --- | --- | --- |");
|
||||
for (const surface of rows) {
|
||||
const owner = surface.owner?.file
|
||||
? `\`${esc(surface.owner.file.replace(/^web\//, ""))}${surface.owner.symbol ? `#${esc(surface.owner.symbol)}` : ""}\``
|
||||
: "—";
|
||||
const desktop = surface.desktopRef?.file
|
||||
? `\`${esc(surface.desktopRef.file.replace(/^freecad-source\//, ""))}${surface.desktopRef.symbol ? `#${esc(surface.desktopRef.symbol)}` : ""}\``
|
||||
: "—";
|
||||
const label = category === "menu" || category === "toolbar" ? esc(surface.nameZh) : `${esc(surface.nameZh)}(\`${esc(surface.id)}\`)`;
|
||||
lines.push(`| ${label} | ${owner} | ${desktop} | ${STATUS_ZH[surface.status] ?? surface.status} | ${esc(surface.note ?? "") || "—"} |`);
|
||||
}
|
||||
lines.push("");
|
||||
sectionNumber += 1;
|
||||
}
|
||||
|
||||
lines.push("## 16." + sectionNumber + " 缺口与边界清单");
|
||||
lines.push("");
|
||||
const gaps = inventory.gaps ?? [];
|
||||
if (!gaps.length) {
|
||||
lines.push("当前清单无 `gap`/`boundary` 项:全部界面表面均有 React 实现。");
|
||||
} else {
|
||||
lines.push("| 表面 | 类别 | 状态 | 原因 | 解除条件 |");
|
||||
lines.push("| --- | --- | --- | --- | --- |");
|
||||
for (const gap of gaps) {
|
||||
lines.push(`| \`${esc(gap.id)}\` | ${esc(CATEGORY_TITLE[gap.category] ?? gap.category)} | ${STATUS_ZH[gap.status] ?? gap.status} | ${esc(gap.reason ?? "")} | ${esc(gap.resolution ?? "")} |`);
|
||||
}
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("## 16." + (sectionNumber + 1) + " 复核命令");
|
||||
lines.push("");
|
||||
lines.push("```bash");
|
||||
lines.push('R="/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD"');
|
||||
lines.push('node "$R/tools/fcweb/ui-inventory.mjs"');
|
||||
lines.push('node "$R/tools/fcweb/ui-surface-inventory.mjs" # 生成清单');
|
||||
lines.push('node "$R/tools/fcweb/ui-surface-inventory.mjs" --check # 漂移检查');
|
||||
lines.push('node "$R/web/tools/manual/generate-panel-index.mjs" # 重生成本章');
|
||||
lines.push("```");
|
||||
lines.push("");
|
||||
|
||||
const markdown = lines.join("\n");
|
||||
|
||||
if (check) {
|
||||
const previous = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : "";
|
||||
if (previous !== markdown) {
|
||||
console.error("[generate-panel-index] --check: ch16-panel-index.md is stale");
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, checked: path.relative(repoRoot, outPath), surfaces: counts.total }));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, markdown);
|
||||
console.log(JSON.stringify({
|
||||
ok: true,
|
||||
out: path.relative(repoRoot, outPath),
|
||||
surfaces: counts.total,
|
||||
sections: sectionNumber - 1,
|
||||
bytes: Buffer.byteLength(markdown),
|
||||
}));
|
||||
186
web/tools/manual/lib/actions.mjs
Normal file
186
web/tools/manual/lib/actions.mjs
Normal file
@@ -0,0 +1,186 @@
|
||||
// Scenario action interpreter shared by capture.mjs (screenshot capture) and the
|
||||
// headed functional suite (assertions). Behaviour is identical to the switch it
|
||||
// was extracted from; everything environment-specific arrives through options.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { listOpfsFiles, readOpfsFile, seedOpfsFromBytes } from "../../carrier-course/lib/opfs.mjs";
|
||||
|
||||
const sha256 = file => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
||||
|
||||
export function createActionRunner(page, {
|
||||
origin = "",
|
||||
shotDir,
|
||||
shotPrefix = "",
|
||||
fixturePath = null,
|
||||
record = () => {},
|
||||
shotIndex = [],
|
||||
} = {}) {
|
||||
const click = async action => {
|
||||
let locator;
|
||||
if (action.role) locator = page.getByRole(action.role, { name: action.name, exact: action.exact });
|
||||
else {
|
||||
locator = page.locator(action.selector);
|
||||
if (action.hasText) locator = locator.filter({ hasText: action.hasText });
|
||||
if (action.target) locator = locator.locator(action.target);
|
||||
}
|
||||
if (action.nth !== undefined) locator = locator.nth(action.nth);
|
||||
else if (!action.all) locator = locator.first();
|
||||
if (action.optional && (await locator.count()) === 0) return;
|
||||
if (action.all) {
|
||||
const count = await locator.count();
|
||||
for (let index = 0; index < count; index++) await locator.nth(index).click();
|
||||
} else await locator.click({ timeout: action.timeout ?? 30000 });
|
||||
};
|
||||
const shot = async action => {
|
||||
if (!shotDir) throw new Error("shot action needs a shotDir");
|
||||
const file = path.join(shotDir, `${action.name}.png`);
|
||||
fs.mkdirSync(shotDir, { recursive: true });
|
||||
if (action.selector) {
|
||||
const target = page.locator(action.selector).first();
|
||||
await target.waitFor({ state: "visible", timeout: 30000 });
|
||||
try {
|
||||
await target.screenshot({ path: file, timeout: 20000 });
|
||||
} catch {
|
||||
// Element screenshots scroll the element into view and can time out on
|
||||
// containers taller than the viewport; evidence capture must not turn
|
||||
// a healthy page state into a failure, so fall back to the viewport.
|
||||
await page.screenshot({ path: file });
|
||||
record({ action: "shot", name: action.name, fallback: "viewport" });
|
||||
}
|
||||
} else {
|
||||
await page.screenshot({ path: file, fullPage: Boolean(action.fullPage) });
|
||||
}
|
||||
const stat = fs.statSync(file);
|
||||
if (stat.size < 1024) throw new Error(`screenshot too small: ${file}`);
|
||||
shotIndex.push({ id: `${shotPrefix}${action.name}`, file,
|
||||
bytes: stat.size, sha256: sha256(file), fullPage: Boolean(action.fullPage), selector: action.selector ?? null });
|
||||
record({ action: "shot", name: action.name, bytes: stat.size });
|
||||
return file;
|
||||
};
|
||||
const save = async action => {
|
||||
await page.evaluate(() => { const details = document.querySelector(".file-tools"); if (details) details.open = true; });
|
||||
await page.waitForTimeout(400);
|
||||
const before = await listOpfsFiles(page);
|
||||
await page.locator('button:has-text("保存 FCStd 到 OPFS")').first().click();
|
||||
let after = before; let status = "";
|
||||
for (let attempt = 0; attempt < 40; attempt++) {
|
||||
await page.waitForTimeout(750);
|
||||
after = await listOpfsFiles(page);
|
||||
status = await page.locator("p.status").first().textContent().catch(() => "");
|
||||
if (after.some(name => !before.includes(name) && /\.FCStd$/i.test(name)) || /Saved\s+\S+\.FCStd\s+to OPFS/i.test(status ?? "")) break;
|
||||
}
|
||||
const match = /Saved\s+(\S+\.FCStd)\s+to OPFS/i.exec(status ?? "");
|
||||
const name = match?.[1] ?? after.find(item => !before.includes(item) && /\.FCStd$/i.test(item));
|
||||
if (!name) throw new Error(`save produced no FCStd; status=${status}`);
|
||||
const bytes = (await readOpfsFile(page, name)).bytes;
|
||||
if (fixturePath) {
|
||||
fs.mkdirSync(path.dirname(fixturePath), { recursive: true });
|
||||
fs.writeFileSync(fixturePath, Buffer.from(bytes));
|
||||
}
|
||||
record({ action: "save", name, bytes: bytes.length, status });
|
||||
return { name, bytes: Buffer.from(bytes) };
|
||||
};
|
||||
|
||||
const run = async action => {
|
||||
switch (action.type) {
|
||||
case "goto":
|
||||
await page.goto(`${origin}${action.url}`, { waitUntil: "domcontentloaded", timeout: 120000 });
|
||||
record({ action: "goto", url: action.url });
|
||||
break;
|
||||
case "waitFor":
|
||||
if (action.selector) await page.waitForSelector(action.selector, { timeout: action.timeout ?? 120000 });
|
||||
if (action.text) await page.getByText(action.text, { exact: action.exact ?? false }).first()
|
||||
.waitFor({ state: "visible", timeout: action.timeout ?? 120000 });
|
||||
record({ action: "waitFor", selector: action.selector ?? null, text: action.text ?? null });
|
||||
break;
|
||||
case "click": await click(action); record({ action: "click", selector: action.selector ?? action.name }); break;
|
||||
case "fill":
|
||||
await page.locator(action.selector).first().fill(String(action.value));
|
||||
record({ action: "fill", selector: action.selector, value: action.value });
|
||||
break;
|
||||
case "select":
|
||||
await page.locator(action.selector).first().selectOption(action.label ? { label: action.label } : action.value);
|
||||
record({ action: "select", selector: action.selector, label: action.label ?? action.value });
|
||||
break;
|
||||
case "selectIndex":
|
||||
await page.locator(action.selector).first().selectOption({ index: action.index });
|
||||
record({ action: "selectIndex", selector: action.selector, index: action.index });
|
||||
break;
|
||||
case "press": await page.keyboard.press(action.key); record({ action: "press", key: action.key }); break;
|
||||
case "clickCanvas": {
|
||||
const target = page.locator(action.selector).first();
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(200);
|
||||
const box = await target.boundingBox();
|
||||
if (!box) throw new Error(`canvas missing: ${action.selector}`);
|
||||
await page.mouse.click(box.x + box.width * action.fx, box.y + box.height * action.fy);
|
||||
await page.waitForTimeout(action.wait ?? 250);
|
||||
record({ action: "clickCanvas", selector: action.selector, fx: action.fx, fy: action.fy });
|
||||
break;
|
||||
}
|
||||
case "assertAnyText": {
|
||||
const texts = await page.locator(action.selector).allTextContents();
|
||||
if (!texts.some(text => String(text).includes(action.contains)))
|
||||
throw new Error(`assertAnyText failed: ${action.contains} in ${JSON.stringify(texts.slice(0, 5))}`);
|
||||
record({ action: "assertAnyText", selector: action.selector, contains: action.contains });
|
||||
break;
|
||||
}
|
||||
case "drag": {
|
||||
const box = await page.locator(action.selector).first().boundingBox();
|
||||
if (!box) throw new Error(`drag target missing: ${action.selector}`);
|
||||
const x = box.x + box.width / 2; const y = box.y + box.height / 2;
|
||||
await page.mouse.move(x, y); await page.mouse.down();
|
||||
await page.mouse.move(x + (action.dx ?? 0), y + (action.dy ?? 0), { steps: 18 });
|
||||
await page.mouse.up(); await page.waitForTimeout(400);
|
||||
record({ action: "drag", selector: action.selector, dx: action.dx, dy: action.dy });
|
||||
break;
|
||||
}
|
||||
case "eval":
|
||||
await page.evaluate(action.script);
|
||||
record({ action: "eval" });
|
||||
break;
|
||||
case "seed": {
|
||||
const file = path.resolve(action.file);
|
||||
if (!fs.existsSync(file)) throw new Error(`seed fixture missing: ${file}`);
|
||||
await seedOpfsFromBytes(page, action.name ?? path.basename(file), fs.readFileSync(file));
|
||||
record({ action: "seed", file, name: action.name ?? path.basename(file) });
|
||||
break;
|
||||
}
|
||||
case "shot": await shot(action); break;
|
||||
case "save": await save(action); break;
|
||||
case "assertText": {
|
||||
const text = await page.locator(action.selector).first().textContent();
|
||||
if (!String(text ?? "").includes(action.contains)) throw new Error(`assertText failed: ${action.selector} ${text}`);
|
||||
record({ action: "assertText", selector: action.selector, contains: action.contains });
|
||||
break;
|
||||
}
|
||||
case "assertVisible":
|
||||
await page.locator(action.selector).first().waitFor({ state: "visible", timeout: 30000 });
|
||||
record({ action: "assertVisible", selector: action.selector });
|
||||
break;
|
||||
case "waitOptions": {
|
||||
const locator = page.locator(action.selector).first();
|
||||
let count = 0;
|
||||
for (let attempt = 0; attempt < 80; attempt++) {
|
||||
count = await locator.locator("option").count();
|
||||
if (count >= (action.min ?? 1)) break;
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
if (count < (action.min ?? 1)) throw new Error(`waitOptions failed: ${action.selector} ${count}`);
|
||||
record({ action: "waitOptions", selector: action.selector, count });
|
||||
break;
|
||||
}
|
||||
case "assertValue": {
|
||||
const value = await page.locator(action.selector).first().inputValue();
|
||||
if (String(value) !== String(action.value)) throw new Error(`assertValue failed: ${action.selector} ${value} != ${action.value}`);
|
||||
record({ action: "assertValue", selector: action.selector, value });
|
||||
break;
|
||||
}
|
||||
case "wait": await page.waitForTimeout(action.ms ?? 500); break;
|
||||
default: throw new Error(`unknown action ${action.type}`);
|
||||
}
|
||||
};
|
||||
|
||||
return { click, shot, save, run, shotIndex };
|
||||
}
|
||||
@@ -38,6 +38,20 @@
|
||||
main figure { margin:16px 0; }
|
||||
main figcaption { color:var(--muted); font-size:12.5px; }
|
||||
.table-scroll { max-width:100%; overflow-x:auto; }
|
||||
/* UI-operation block: the real screenshot plus the exact field values the
|
||||
driver typed, side by side on wide screens and stacked on phones. */
|
||||
.ui-block { margin:20px 0; padding:14px 16px; border:1px solid var(--line); border-radius:10px; background:var(--panel); }
|
||||
.ui-block h4 { margin:0 0 10px; font-size:14px; letter-spacing:0.04em; color:var(--accent); }
|
||||
.ui-block img { display:block; width:100%; height:auto; border-radius:8px; border:1px solid var(--line); }
|
||||
.ui-block table { width:100%; margin-top:10px; border-collapse:collapse; font-size:13px; }
|
||||
.ui-block th { text-align:left; font-weight:600; color:var(--muted); padding:5px 8px; width:38%; }
|
||||
.ui-block td { padding:5px 8px; font-variant-numeric:tabular-nums; }
|
||||
.ui-block tr + tr { border-top:1px solid var(--line); }
|
||||
@media (min-width:900px) {
|
||||
.ui-block { display:grid; grid-template-columns:minmax(0,1.4fr) minmax(0,1fr); gap:16px; align-items:start; }
|
||||
.ui-block h4 { grid-column:1 / -1; }
|
||||
.ui-block table { margin-top:0; }
|
||||
}
|
||||
table { width:100%; border-collapse:collapse; font-size:13px; margin:12px 0; }
|
||||
th, td { border-bottom:1px solid var(--line); padding:5px 7px; text-align:left; vertical-align:top; }
|
||||
th { color:var(--accent); }
|
||||
@@ -52,7 +66,7 @@
|
||||
.index-controls { display:flex; gap:8px; flex-wrap:wrap; margin:12px 0; }
|
||||
.index-controls select, .index-controls input { background:#0b1014; color:var(--text); border:1px solid #3f3f3f; border-radius:4px; padding:5px 8px; }
|
||||
#command-index td { font-size:12px; } #command-index tr.hidden { display:none; }
|
||||
.pager { display:flex; justify-content:space-between; gap:12px; margin-top:40px; padding-top:14px; border-top:1px solid var(--line); }
|
||||
.pager { display:flex; flex-wrap:wrap; justify-content:space-between; gap:12px; margin-top:40px; padding-top:14px; border-top:1px solid var(--line); }
|
||||
#lightbox { position:fixed; inset:0; background:#000d; z-index:60; display:none; align-items:center; justify-content:center; padding:24px; }
|
||||
#lightbox img { max-width:96vw; max-height:92vh; border-radius:6px; }
|
||||
#lightbox.open { display:flex; }
|
||||
|
||||
Reference in New Issue
Block a user