diff --git a/docs/current/web-functional-suite/README.md b/docs/current/web-functional-suite/README.md new file mode 100644 index 00000000..d1243f19 --- /dev/null +++ b/docs/current/web-functional-suite/README.md @@ -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 ` | 逗号分隔的用例 id | +| `--priority P0,P1,P2,P3` | 按层选择 | +| `--module ` | 只跑指定模块的 `MOD-*` | +| `--resume ` / `--force` | 断点续跑;`--force` 重跑已完成用例 | +| `--headless` / `--slow ` / `--highlight` | 无头、放慢、高亮(观察用) | +| `--screenshots fails\|all` | 失败截图(默认)或全量截图 | +| `--out ` | 证据根目录(默认 `docs/current/web-functional-suite`) | +| `--prune ` | 只保留最近 n 次运行目录 | +| `--legacy-ids ` | 以子进程运行 `tools/run_user_manual_tests.mjs` 并归一化为 `LEGACY-*` | +| `--timeout-scale ` | 统一放大/缩小用例超时 | + +退出码:0 = 全部 passed;1 = 存在 failed/running;2 = 没有选中任何用例。 + +## 用例分层 + +| 前缀 | 层 | 内容 | 来源 | +|---|---|---|---| +| `SHELL-0x` | P0 | 入口隔离(COOP/COEP)、Start 工作区、新建文档 + Cube、OPFS 可写、画布与图标渲染 | `cases/shell.mjs` | +| `CH--` | P1 | 手册 27 份场景 JSON 全动作执行 + 章末后置断言(pageerror、状态栏、画布) | `cases/chapters.mjs` → `web/manual/scenarios/*.json` | +| `CH-ch14-*`、`CH-ch15-*` | P1 | 无场景 JSON 的两章用手写用例(生产线资产契约、Help/命令面板/偏好/快捷键) | `cases/handwritten.mjs` | +| `MOD--01` | P2 | 31 个模块:壳层挂载、模块坞选中、命令面注册、规范命令返回 `kind=result` | `cases/modules.mjs` → `feature-capability-registry.json` | +| `X-*` | P3 | 五种导出格式落 OPFS、FCStd 存取哈希、保存后回开、坏文件错误恢复、viewport 无溢出、左右面板独立滚动(`X-panel-scroll`) | `cases/crosscut.mjs` | +| `LEGACY-` | 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-/`: + +- `manifest.json`:origin、Chrome 版本、用例清单、dist 相对路径 +- `results.json` / `checkpoint.json`:逐案结果与断点(`--resume` 依据) +- `report.md` / `junit.xml` / `index.html`:人读报告、CI 报告、浏览器索引 +- `gaps.ndjson`:缺口台账(caseId、classification、failureClass、evidence) +- `cases//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 ] [--port ] [--document ]`,打印 `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`。用例必须按目录分别轮询/回读,禁止跨目录假设;下载目录始终为空,导出不得自动下载。 diff --git a/tools/functional-suite/cases/chapters.mjs b/tools/functional-suite/cases/chapters.mjs new file mode 100644 index 00000000..150c4fa6 --- /dev/null +++ b/tools/functional-suite/cases/chapters.mjs @@ -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 }; + }); + }, +})); diff --git a/tools/functional-suite/cases/crosscut.mjs b/tools/functional-suite/cases/crosscut.mjs new file mode 100644 index 00000000..84ce5998 --- /dev/null +++ b/tools/functional-suite/cases/crosscut.mjs @@ -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
; 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 }; + }); + }, + }, +]; diff --git a/tools/functional-suite/cases/handwritten.mjs b/tools/functional-suite/cases/handwritten.mjs new file mode 100644 index 00000000..8d653f81 --- /dev/null +++ b/tools/functional-suite/cases/handwritten.mjs @@ -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 }; + }); + }, + }, +]; diff --git a/tools/functional-suite/cases/index.mjs b/tools/functional-suite/cases/index.mjs new file mode 100644 index 00000000..50e4d1ea --- /dev/null +++ b/tools/functional-suite/cases/index.mjs @@ -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]; +} diff --git a/tools/functional-suite/cases/modules.mjs b/tools/functional-suite/cases/modules.mjs new file mode 100644 index 00000000..a3609454 --- /dev/null +++ b/tools/functional-suite/cases/modules.mjs @@ -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) }; + }); + }, +})); diff --git a/tools/functional-suite/cases/shell.mjs b/tools/functional-suite/cases/shell.mjs new file mode 100644 index 00000000..40ca746d --- /dev/null +++ b/tools/functional-suite/cases/shell.mjs @@ -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
/ 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 }; diff --git a/tools/functional-suite/cli.mjs b/tools/functional-suite/cli.mjs new file mode 100644 index 00000000..e2a273c2 --- /dev/null +++ b/tools/functional-suite/cli.mjs @@ -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 comma separated case ids (e.g. SHELL-01,CH02-part) + --priority comma separated priorities: P0,P1,P2,P3 (default all) + --module comma separated module names for MOD-* cases + --resume 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 Playwright slowMo pacing for live observation + --highlight outline the acted element before each action + --screenshots "fails" (default) or "all" + --jobs browser workers (1 = single headed window, default 1) + --out evidence root (default docs/current/web-functional-suite) + --prune keep only the newest n run directories + --legacy-ids also run tools/run_user_manual_tests.mjs ids (all = 53 cases) + --timeout-scale 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; +} diff --git a/tools/functional-suite/executors/legacy.mjs b/tools/functional-suite/executors/legacy.mjs new file mode 100644 index 00000000..6d82ebb5 --- /dev/null +++ b/tools/functional-suite/executors/legacy.mjs @@ -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; +} diff --git a/tools/functional-suite/gap-ledger.mjs b/tools/functional-suite/gap-ledger.mjs new file mode 100644 index 00000000..bc7045cb --- /dev/null +++ b/tools/functional-suite/gap-ledger.mjs @@ -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 }, + }; +} diff --git a/tools/functional-suite/report.mjs b/tools/functional-suite/report.mjs new file mode 100644 index 00000000..6e786c2f --- /dev/null +++ b/tools/functional-suite/report.mjs @@ -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, """); + +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 ` + : `\n ${esc(item.error)}`; + return ` ${failure}\n `; + }); + return `\n\n${body.join("\n")}\n\n`; +} + +export function writeIndex(ctx) { + const rows = ctx.results.map(item => { + const color = item.status === "passed" ? "#137333" : item.status === "blocked" ? "#8a6d00" : "#a50e0e"; + return `${esc(item.id)}${esc(item.priority)}${esc(statusCell(item))}${Number(item.seconds ?? 0).toFixed(1)}s${esc(item.error ? item.error.slice(0, 160) : "")}`; + }); + return `Web FreeCAD functional suite + +

Web FreeCAD 功能测试(有头)

+

${esc(ctx.startedAt)} · origin ${esc(ctx.origin)} · passed ${ctx.counts.passed} / failed ${ctx.counts.failed} / blocked ${ctx.counts.blocked}

+${rows.join("")}
id优先级状态耗时错误
+

report.md · results.json · junit.xml

`; +} + +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; +} diff --git a/tools/functional-suite/runtime.mjs b/tools/functional-suite/runtime.mjs new file mode 100644 index 00000000..6f964ef4 --- /dev/null +++ b/tools/functional-suite/runtime.mjs @@ -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; +} diff --git a/tools/layout-probe.mjs b/tools/layout-probe.mjs new file mode 100644 index 00000000..1c881dec --- /dev/null +++ b/tools/layout-probe.mjs @@ -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 repeatable page path (default: /project.html, + * /partdesign.html, /workbench.html?module=Part|Robot|Mesh) + * --root dist root to serve (default /web/dist) + * --origin probe an already running host instead of starting one + * --wait-for ready selector (default: .layout, .design-layout or .pane-scroll) + * --wait-ms settle time after ready (default 1500) + * --viewport default 1440x1000 + * --headed show the browser (needs DISPLAY); --slow adds slowMo + * --pause keep each headed page open until Enter (implies --headed) + * --inject spacer height used to test pane scrolling (default 2000, 0 disables) + * --scroll-test how far each pane is scrolled (default 400) + * --screenshot per-page PNG; "{page}" is replaced by a url slug + * --json 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); diff --git a/tools/static-host.mjs b/tools/static-host.mjs index e3e75d1f..d2582fdb 100644 --- a/tools/static-host.mjs +++ b/tools/static-host.mjs @@ -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 ] [--port ] [--document ] + * Prints ORIGIN=http://127.0.0.1: 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 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); } diff --git a/tools/web-freecad-functional-suite.mjs b/tools/web-freecad-functional-suite.mjs new file mode 100644 index 00000000..72284c6a --- /dev/null +++ b/tools/web-freecad-functional-suite.mjs @@ -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; diff --git a/web/manual/scenarios/ch05-assembly.json b/web/manual/scenarios/ch05-assembly.json index 45225953..2069733a 100644 --- a/web/manual/scenarios/ch05-assembly.json +++ b/web/manual/scenarios/ch05-assembly.json @@ -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" }, { diff --git a/web/src/document-tree.tsx b/web/src/document-tree.tsx new file mode 100644 index 00000000..bd17b66c --- /dev/null +++ b/web/src/document-tree.tsx @@ -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; + data: DocumentTreeNode; + onSelectObject: (id: string) => void; + onToggleVisibility?: (id: string, visible: boolean) => void; + busy: boolean; + }, +) { + const arrow = node.isLeaf ? null : ( + + ); + return <> + {arrow} +
+ {data.toggleable !== false + ? event.stopPropagation()} + onChange={event => onToggleVisibility?.(data.id, event.target.checked)} /> + :
+
{data.description ?? ""}
+
{data.internalName}
+ ; +} + +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(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 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) => ( +
{ node.handleClick(event); }}> + {children} +
+ ), []); + const renderNode = useCallback(({ node }: NodeRendererProps) => ( + callbacks.current.onSelect(id)} + onToggleVisibility={(id, visible) => callbacks.current.onToggleVisibility?.(id, visible)} busy={callbacks.current.busy} /> + ), []); + + return
+ +
+
Labels & Attributes
Description
Internal name
+
+ + 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} + +
; +} diff --git a/web/src/export-service.ts b/web/src/export-service.ts new file mode 100644 index 00000000..99129568 --- /dev/null +++ b/web/src/export-service.ts @@ -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> { + const bytes = await readExportFile(fileName); + return downloadBytes(fileName, bytes, mime); + } + + download(native: Partial): 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 } }; + } +} diff --git a/web/src/import-render-bridge.ts b/web/src/import-render-bridge.ts index d81d9967..9e4f4c3c 100644 --- a/web/src/import-render-bridge.ts +++ b/web/src/import-render-bridge.ts @@ -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 { diff --git a/web/src/module-registry.generated.ts b/web/src/module-registry.generated.ts index fe447dcc..1e056007 100644 --- a/web/src/module-registry.generated.ts +++ b/web/src/module-registry.generated.ts @@ -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"; diff --git a/web/src/panel-scroll.css b/web/src/panel-scroll.css new file mode 100644 index 00000000..6d47738f --- /dev/null +++ b/web/src/panel-scroll.css @@ -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 + 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; +} diff --git a/web/src/partdesign-workspace-component.tsx b/web/src/partdesign-workspace-component.tsx new file mode 100644 index 00000000..d5720090 --- /dev/null +++ b/web/src/partdesign-workspace-component.tsx @@ -0,0 +1,1305 @@ +import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +// Shared side-panel scroll contract (standalone page and embedded stage). +import "./panel-scroll.css"; +import { ArrowLeft, Box, Circle, CircleDot, Copy, RectangleHorizontal, FilePlus2, FolderOpen, FileInput, FileOutput, Save, Download, Undo2, Redo2, Plus, RefreshCw, Trash2, ArrowUpFromLine, ArrowDownToLine, Rotate3d, RotateCcw, CornerDownRight, CornerRightDown, Maximize, Layers2, Route, Combine, Scissors, type IconNode } from "lucide"; +import { WebModuleRouter } from "./module-router.js"; +import { ImportRenderBridge } from "./import-render-bridge.js"; +import { documentObjectMesh, type NativeDocumentObject } from "./part-document-facade.js"; +import { PARTDESIGN_DOCUMENT_COMMAND, PARTDESIGN_DOCUMENT_SCHEMA, type DesignAction, type DesignPayload, type DesignObject, type DesignResult, type ProfileFeature, type ProfileType, type DressUpFeature, type DatumType } from "./partdesign-document-facade.js"; +import { listDocumentFiles, listExportFiles, readDocumentFile, readExportFile, writeDocumentFile, writeExportFile } from "./storage.js"; +import { executePartDesignDesktop } from "./partdesign-desktop-adapter.js"; +import { PartDatumTask } from "./part-datum-task.js"; +import { PART_DATUM_TYPES, type PartDatumCommand, type PartDocumentResult } from "./part-document-facade.js"; + +import { gearDefaults, GearParameterFields, invalidSprocketRoller, type GearType } from "./partdesign-gear-fields.js"; +import { defaultSketchGeometry, defaultSketchProfile, SketchGeometryFields } from "./partdesign-sketch-geometry-fields.js"; +import { DocumentTree, type DocumentTreeNode } from "./document-tree.js"; +import { PLANE_PRESETS } from "./placement-presets.js"; + +// Sketch support planes, as quaternions. Desktop Sketcher maps a sketch to any +// planar face; the web form exposes the three axis-aligned planes plus a raw +// quaternion escape hatch so an arbitrary face normal can still be expressed. +// The values live in placement-presets.ts so the assembly insert task cannot +// drift from the sketch and gear forms. +const SKETCH_PLANE_ROTATION: Record = { + ...PLANE_PRESETS, + Custom: [0, 0, 0, 1], +}; + +function Icon({ nodes }: { nodes: IconNode }) { return ; } +// Match the existing desktop FeaturePrimitive/PrismExtension property names. +const designPrimitiveDefaults: Record> = { + Box: { Length: 10, Width: 10, Height: 10 }, + Cylinder: { Radius: 10, Height: 10, Angle: 360 }, + Sphere: { Radius: 5, Angle1: -90, Angle2: 90, Angle3: 360 }, + Cone: { Radius1: 2, Radius2: 4, Height: 10, Angle: 360 }, + Ellipsoid: { Radius1: 2, Radius2: 4, Radius3: 0, Angle1: -90, Angle2: 90, Angle3: 360 }, + Torus: { Radius1: 10, Radius2: 2, Angle1: -180, Angle2: 180, Angle3: 360 }, + Prism: { Polygon: 6, Circumradius: 2, Height: 10 }, + Wedge: { Xmin: 0, Ymin: 0, Zmin: 0, Xmax: 10, Ymax: 10, Zmax: 10, X2min: 2, Z2min: 2, X2max: 8, Z2max: 8 }, +}; +const primitiveQuantityMinimum = 2e-7; +type PrimitiveFieldConstraint = { min?: number; max?: number; step?: number }; +const primitiveFieldConstraint = (kind: string, parameters: Record, field: string): PrimitiveFieldConstraint => { + const value = (name: string) => Number.isFinite(parameters[name]) ? parameters[name] : undefined; + const positive = { min: primitiveQuantityMinimum }; + const angleU = { min: 0, max: 360, step: 1 }; + const angleV = { min: -90, max: 90, step: 1 }; + if (["Box", "Cylinder"].includes(kind) && ["Length", "Width", "Height", "Radius"].includes(field)) return positive; + if (kind === "Cylinder" && field === "Angle") return angleU; + if (kind === "Sphere") { + if (field === "Radius") return positive; + if (field === "Angle1") return { ...angleV, max: value("Angle2") ?? angleV.max }; + if (field === "Angle2") return { ...angleV, min: value("Angle1") ?? angleV.min }; + if (field === "Angle3") return angleU; + } + if (kind === "Cone") { + if (["Radius1", "Radius2"].includes(field)) return { min: 0 }; + if (field === "Height") return positive; + if (field === "Angle") return angleU; + } + if (kind === "Ellipsoid") { + if (["Radius1", "Radius2"].includes(field)) return positive; + if (field === "Radius3") return { min: 0 }; + if (field === "Angle1") return { ...angleV, max: value("Angle2") ?? angleV.max }; + if (field === "Angle2") return { ...angleV, min: value("Angle1") ?? angleV.min }; + if (field === "Angle3") return angleU; + } + if (kind === "Torus") { + if (field === "Radius1") return { min: Math.max(primitiveQuantityMinimum, value("Radius2") ?? primitiveQuantityMinimum) }; + if (field === "Radius2") return { min: primitiveQuantityMinimum, max: value("Radius1") }; + if (field === "Angle1") return { min: -180, max: value("Angle2") ?? 180, step: 1 }; + if (field === "Angle2") return { min: value("Angle1") ?? -180, max: 180, step: 1 }; + if (field === "Angle3") return angleU; + } + if (kind === "Prism") { + if (field === "Polygon") return { min: 3, max: 1000, step: 1 }; + if (["Circumradius", "Height"].includes(field)) return positive; + } + if (kind === "Wedge") { + const maxima: Record = { Xmin: "Xmax", Ymin: "Ymax", Zmin: "Zmax", X2min: "X2max", Z2min: "Z2max" }; + const minima: Record = { Xmax: "Xmin", Ymax: "Ymin", Zmax: "Zmin", X2max: "X2min", Z2max: "Z2min" }; + if (maxima[field]) return { max: value(maxima[field]) }; + if (minima[field]) return { min: value(minima[field]) }; + } + return {}; +}; +const primitiveParametersValid = (kind: string, parameters: Record) => { + const finite = Object.values(parameters).every(value => Number.isFinite(value)); + if (!finite) return false; + const p = parameters; + const positive = (value: number | undefined) => Number.isFinite(value) && value! >= primitiveQuantityMinimum; + const angleU = (value: number | undefined) => Number.isFinite(value) && value! >= 0 && value! <= 360; + const angleV = (value: number | undefined) => Number.isFinite(value) && value! >= -90 && value! <= 90; + if (kind === "Box") return [p.Length, p.Width, p.Height].every(positive); + if (kind === "Cylinder") return positive(p.Radius) && positive(p.Height) && angleU(p.Angle) && p.Angle > 0; + // Sphere Angle3 follows the desktop property's inclusive 0..360 range. + if (kind === "Sphere") return positive(p.Radius) && angleV(p.Angle1) && angleV(p.Angle2) && p.Angle1 <= p.Angle2 && angleU(p.Angle3); + // FreeCAD's Cone property allows a zero closing angle; native recompute + // remains the authority for whether that degenerate shape can be committed. + if (kind === "Cone") return [p.Radius1, p.Radius2].every(value => Number.isFinite(value) && value >= 0) && positive(p.Height) && angleU(p.Angle); + if (kind === "Ellipsoid") return positive(p.Radius1) && positive(p.Radius2) && Number.isFinite(p.Radius3) && p.Radius3 >= 0 && angleV(p.Angle1) && angleV(p.Angle2) && p.Angle1 <= p.Angle2 && angleU(p.Angle3) && p.Angle3 > 0; + if (kind === "Torus") return positive(p.Radius1) && positive(p.Radius2) && p.Radius1 >= p.Radius2 && p.Angle1 >= -180 && p.Angle1 <= p.Angle2 && p.Angle2 <= 180 && angleU(p.Angle3) && p.Angle3 > 0; + if (kind === "Prism") return Number.isInteger(p.Polygon) && p.Polygon >= 3 && p.Polygon <= 1000 && positive(p.Circumradius) && positive(p.Height); + if (kind === "Wedge") return p.Xmax - p.Xmin >= primitiveQuantityMinimum && p.Ymax - p.Ymin >= primitiveQuantityMinimum && p.Zmax - p.Zmin >= primitiveQuantityMinimum && p.X2max - p.X2min >= 0 && p.Z2max - p.Z2min >= 0; + return false; +}; +export interface EmbeddedDesignWorkspace { + document: string; snapshot?: DesignResult; selected: string; workbench: "Sketcher" | "PartDesign"; + sceneDocument: string; + datumSelection?: Array<{ object: string; subelements: string[] }>; + renderer: ImportRenderBridge; + request: (action: DesignPayload["action"], details: Partial) => Promise; + onSnapshot: (result: DesignResult) => void; onSelection: (name: string) => void; + onBusy: (busy: boolean) => void; onStatus: (text: string) => void; +} +export function PartDesignWorkspace({ router: sharedRouter, embedded }: { router?: WebModuleRouter; embedded?: EmbeddedDesignWorkspace } = {}) { + // The primary workspace owns a shared router across workbench switches. + // Only the standalone workspace may dispose the router it creates itself. + const router = useMemo(() => sharedRouter ?? new WebModuleRouter(), [sharedRouter]); + const renderer = useMemo(() => { if (embedded?.renderer) return embedded.renderer; const bridge = new ImportRenderBridge(); bridge.camera.up.set(0, 0, 1); return bridge; }, [embedded?.renderer]); + const viewport = useRef(null); + const serial = useRef(1); + const [localActive, setActive] = useState("Design1"); + const active = embedded?.document ?? localActive; + const [partDatumCommand, setPartDatumCommand] = useState(); + useEffect(() => setPartDatumCommand(undefined), [active]); + const [documents, setDocuments] = useState>({}); + const [localSelected, setLocalSelected] = useState(""); + const selected = embedded?.selected ?? localSelected; + const setSelected = (name: string) => embedded ? embedded.onSelection(name) : setLocalSelected(name); + const [body, setBody] = useState(""); + const [reorderObjects, setReorderObjects] = useState([]); + const [reorderAfter, setReorderAfter] = useState(""); + const [moveObjects, setMoveObjects] = useState([]); + const [moveTargetBody, setMoveTargetBody] = useState(""); + const [duplicateObjects, setDuplicateObjects] = useState([]); + const [duplicateRecursive, setDuplicateRecursive] = useState(true); + const [duplicateBody, setDuplicateBody] = useState(""); + const [primitiveMode, setPrimitiveMode] = useState<"Additive" | "Subtractive">("Additive"); + const [primitiveKind, setPrimitiveKind] = useState("Box"); + const [primitiveParameters, setPrimitiveParameters] = useState>({ ...designPrimitiveDefaults.Box }); + const [primitivePosition, setPrimitivePosition] = useState<[number, number, number]>([0, 0, 0]); + const [gearKind, setGearKind] = useState("InvoluteGear"); + const [gearParameters, setGearParameters] = useState({ ...gearDefaults.InvoluteGear }); + const [gearPreset, setGearPreset] = useState(""); + const [profileType, setProfileType] = useState("Rectangle"); + const [parameters, setParameters] = useState>({ Width: 10, Height: 8 }); + // Geometry profiles are the desktop addGeometry/addConstraint surface; the + // payload is sent verbatim, so the editor only has to keep the arrays valid. + const [sketchGeometries, setSketchGeometries] = useState(defaultSketchProfile().geometries); + const [sketchConstraints, setSketchConstraints] = useState(defaultSketchProfile().constraints); + const [requireFullyConstrained, setRequireFullyConstrained] = useState(false); + const [position, setPosition] = useState<[number, number, number]>([0, 0, 0]); + // Sketch planes are not always parallel to XY: a Pocket on a Y-facing face + // must cut along Y. Desktop Sketcher stores a full Placement; without the + // rotation the profile silently lands on XY (GAP-RP-34). + const [sketchRotation, setSketchRotation] = useState<[number, number, number, number]>([0, 0, 0, 1]); + const [sketchRotationMode, setSketchRotationMode] = useState("XY"); + // A gear profile is placed by its own Placement, exactly like a sketch: the + // reducer's gear bodies sit at an axial offset and often face along Y. The + // form used to expose neither, so every gear landed at the origin on XY. + const [gearPosition, setGearPosition] = useState<[number, number, number]>([0, 0, 0]); + const [gearRotation, setGearRotation] = useState<[number, number, number, number]>([0, 0, 0, 1]); + const [gearPlane, setGearPlane] = useState("XY"); + const [profile, setProfile] = useState(""); + const [sketchMapMode, setSketchMapMode] = useState<"FlatFace" | "Deactivated">("Deactivated"); + const [sketchSupport, setSketchSupport] = useState(""); + const [sketchFace, setSketchFace] = useState(""); + const [featureType, setFeatureType] = useState("Pad"); + const [sections, setSections] = useState([]); + const [ruled, setRuled] = useState(false); + const [closed, setClosed] = useState(false); + const [spine, setSpine] = useState(""); + const [spineEdges, setSpineEdges] = useState([]); + const [pipeMode, setPipeMode] = useState>("Standard"); + const [transition, setTransition] = useState>("Transformed"); + const [auxiliarySpine, setAuxiliarySpine] = useState(""); + const [auxiliarySpineEdges, setAuxiliarySpineEdges] = useState([]); + const [auxiliaryCurvilinear, setAuxiliaryCurvilinear] = useState(true); + const [binormal, setBinormal] = useState<[number, number, number]>([0, 0, 1]); + const [length, setLength] = useState(6); + const [diameter, setDiameter] = useState(4); + const [depth, setDepth] = useState(5); + const [depthType, setDepthType] = useState<"Dimension" | "ThroughAll">("Dimension"); + const [angle, setAngle] = useState(360); + const [axis, setAxis] = useState(""); + const [helixHeight, setHelixHeight] = useState(10); + const [pitch, setPitch] = useState(3); + const [leftHanded, setLeftHanded] = useState(false); + const [helixAngle, setHelixAngle] = useState(0); + const [axisSubelement, setAxisSubelement] = useState(""); + const [rotationMode, setRotationMode] = useState(0); + const [angle2, setAngle2] = useState(90); + const [midplane, setMidplane] = useState(false); + const [rotationFace, setRotationFace] = useState({ object: "", subelement: "" }); + const [referenceMode, setReferenceMode] = useState("CrossReference"); + const [extent, setExtent] = useState>({ Type: "Length", Type2: "Length", SideType: "One side", Length2: 6, Offset: 0, Offset2: 0, TaperAngle: 0, TaperAngle2: 0, AlongSketchNormal: true, Direction: [0, 0, 1] }); + const [helixMode, setHelixMode] = useState("Pitch-Height-Angle"); + const [helixTurns, setHelixTurns] = useState(3); + const [helixGrowth, setHelixGrowth] = useState(0); + const [helixOutside, setHelixOutside] = useState(false); + const [helixReversed, setHelixReversed] = useState(false); + const [multiChildren, setMultiChildren] = useState([]); + const [multiChild, setMultiChild] = useState(""); + const [mirrorOriginals, setMirrorOriginals] = useState([]); + const [mirrorPlane, setMirrorPlane] = useState(""); + const [patternOriginals, setPatternOriginals] = useState([]); + const [patternDirection, setPatternDirection] = useState(""); + const [patternLength, setPatternLength] = useState(12); + const [patternCount, setPatternCount] = useState(3); + const [patternReversed, setPatternReversed] = useState(false); + const [scaledOriginals, setScaledOriginals] = useState([]); + const [scaledFactor, setScaledFactor] = useState(2); + const [scaledCount, setScaledCount] = useState(2); + const [polarOriginals, setPolarOriginals] = useState([]); + const [polarAxis, setPolarAxis] = useState(""); + const [polarAngle, setPolarAngle] = useState(360); + const [polarCount, setPolarCount] = useState(3); + const [polarReversed, setPolarReversed] = useState(false); + const [booleanOperation, setBooleanOperation] = useState<"Fuse" | "Cut" | "Common">("Fuse"); + const [booleanTools, setBooleanTools] = useState([]); + const [datumType, setDatumType] = useState("Plane"); + const [datumOrigin, setDatumOrigin] = useState<[number, number, number]>([0, 0, 0]); + const [datumMapMode, setDatumMapMode] = useState<"FlatFace" | "TwoPointLine" | "Vertex" | "Deactivated">("Deactivated"); + const [datumSupport, setDatumSupport] = useState(""); + const [datumPolicy, setDatumPolicy] = useState<"Independent" | "Dependent" | "CrossReference">("Independent"); + const [datumFace, setDatumFace] = useState(""); + const [datumOffset, setDatumOffset] = useState<[number, number, number]>([0, 0, 0]); + const [cloneSource, setCloneSource] = useState(""); + const [binderKind, setBinderKind] = useState<"ShapeBinder" | "SubShapeBinder">("ShapeBinder"); + const [binderLinks, setBinderLinks] = useState>([]); + const [bindMode, setBindMode] = useState<"Synchronized" | "Frozen" | "Detached">("Synchronized"); + const [binderSource, setBinderSource] = useState(""); + const [binderSubelements, setBinderSubelements] = useState([]); + const [linkDialogOpen, setLinkDialogOpen] = useState(false); + const [linkDialogDraft, setLinkDialogDraft] = useState>([]); + const [linkDialogSelectedObject, setLinkDialogSelectedObject] = useState(""); + const [linkDialogSearch, setLinkDialogSearch] = useState(""); + const [linkDialogFilterType, setLinkDialogFilterType] = useState(false); + const [linkRowMenu, setLinkRowMenu] = useState<{ object: string; x: number; y: number } | null>(null); + const [traceSupport, setTraceSupport] = useState(true); + const [dressUpType, setDressUpType] = useState("Fillet"); + const [base, setBase] = useState(""); + const [edges, setEdges] = useState(["Edge1"]); + const [useAllEdges, setUseAllEdges] = useState(false); + const [size, setSize] = useState(0.5); + const [chamferType, setChamferType] = useState>("Equal distance"); + const [chamferSize2, setChamferSize2] = useState(1); + const [chamferAngle, setChamferAngle] = useState(45); + const [chamferFlip, setChamferFlip] = useState(false); + const [thicknessMode, setThicknessMode] = useState>("Skin"); + const [thicknessJoin, setThicknessJoin] = useState>("Arc"); + const [thicknessIntersection, setThicknessIntersection] = useState(false); + const [reversed, setReversed] = useState(false); + const [busy, setBusy] = useState(false); + const operationInFlight = useRef(false); + const [status, setStatus] = useState("空文档"); + const [failed, setFailed] = useState(false); + const [visibility, setVisibility] = useState>({}); + const [files, setFiles] = useState([]); + const [file, setFile] = useState(""); + const [savedBytes, setSavedBytes] = useState(null); + const [exportedFiles, setExportedFiles] = useState([]); + const [exportFile, setExportFile] = useState(""); + const [exportFormat, setExportFormat] = useState("step"); + const current = embedded ? embedded.snapshot : documents[active]; + const objects = current?.objects ?? []; + const editable = objects.filter(object => object.type.startsWith("PartDesign::") || object.type.startsWith("Part::") || object.type === "Sketcher::SketchObject"); + const bodies = objects.filter(object => object.type === "PartDesign::Body"); + const sketches = objects.filter(object => object.type === "Sketcher::SketchObject" && object.body === body); + const featureProfiles = objects.filter(object => object.body === body && (object.type === "Sketcher::SketchObject" || object.gearType)); + const axes = objects.filter(object => object.type === "App::Line" && object.body === body); + const solids = objects.filter(object => object.body === body && object.type.startsWith("PartDesign::") && (object.volume ?? 0) > 0); + const baseObject = solids.find(object => object.name === base); + const [thicknessFaces, setThicknessFaces] = useState([]); + const [referenceTask, setReferenceTask] = useState<{ + thickness: boolean; base: string; selected: string; document: string; snapshot: DesignResult | undefined; + } | null>(null); + const [referenceDraft, setReferenceDraft] = useState([]); + const [referenceKind, setReferenceKind] = useState<"Edge" | "Face">("Edge"); + const [referenceAction, setReferenceAction] = useState<"toggle" | "add" | "remove">("toggle"); + const [referenceHover, setReferenceHover] = useState(); + const [referenceRows, setReferenceRows] = useState([]); + const [referenceMenu, setReferenceMenu] = useState(false); + const referencePicker = useRef | null>(null); + const referenceActionRef = useRef(referenceAction); + referenceActionRef.current = referenceAction; + const endReferenceTask = () => { + referencePicker.current?.dispose(); referencePicker.current = null; + setReferenceTask(null); setReferenceHover(undefined); setReferenceRows([]); setReferenceMenu(false); + }; + const startReferenceTask = (thickness: boolean) => perform(async () => { + // Picking samples are opt-in on the kernel side because building them for + // every snapshot cost 103 s on a 100-tooth gear; fetch them on demand. + let references = objects.find(item => item.name === base)?.dressUpReferences ?? []; + if (!references.length) { + const result = await request(active, "snapshot", { includeReferences: true }); + apply(result); + // React state is published on the next render, so read the fresh payload. + references = (result.objects ?? []).find(item => item.name === base)?.dressUpReferences ?? []; + } + if (!references.length) { setStatus("The base has no native reference display geometry"); return; } + setReferenceDraft([...(thickness ? thicknessFaces : edges)]); + setReferenceKind(thickness ? "Face" : "Edge"); setReferenceAction("toggle"); setReferenceRows([]); setReferenceMenu(false); + setReferenceTask({ thickness, base, selected, document: active, snapshot: current }); + }); + useEffect(() => { + if (!referenceTask) return; + const sceneName = (name: string) => embedded ? `native:${name}` : name; + const source = objects.find(item => item.name === referenceTask.base); + const picker = renderer.beginReferencePick(embedded?.sceneDocument ?? active, sceneName(referenceTask.base), + objects.filter(item => item.name !== referenceTask.base && (item.body === source?.body || item.name === source?.body)) + .map(item => sceneName(item.name)), source?.dressUpReferences ?? [], subelement => { + setReferenceRows([subelement]); + setReferenceDraft(previous => referenceActionRef.current === "remove" || (referenceActionRef.current === "toggle" && previous.includes(subelement)) ? previous.filter(value => value !== subelement) + : previous.includes(subelement) ? previous : [...previous, subelement]); + }); + referencePicker.current = picker; + return () => { picker.dispose(); if (referencePicker.current === picker) referencePicker.current = null; }; + }, [referenceTask, renderer]); + useEffect(() => { + referencePicker.current?.highlight(referenceDraft, referenceKind, referenceHover); + }, [referenceTask, referenceDraft, referenceKind, referenceHover]); + useEffect(() => { + if (referenceTask && (referenceTask.document !== active || referenceTask.selected !== selected + || referenceTask.base !== base || referenceTask.snapshot !== current || embedded?.workbench === "Sketcher")) endReferenceTask(); + }, [active, selected, base, current, referenceTask, embedded?.workbench]); + const [draftFaces, setDraftFaces] = useState([]); + const [draftAngle, setDraftAngle] = useState(10); + const [draftReversed, setDraftReversed] = useState(false); + const [draftNeutral, setDraftNeutral] = useState(""); + const [draftPull, setDraftPull] = useState(""); + const [materialPreview, setMaterialPreview] = useState(); + const previewLease = useRef<(() => void) | null>(null); + const [wallSize, setWallSize] = useState(1); + const [wallInwards, setWallInwards] = useState(true); + const revolve = featureType === "Revolution" || featureType === "Groove"; + const helix = featureType === "Helix" || featureType === "SubtractiveHelix"; + const hole = featureType === "Hole"; + const loft = featureType === "Loft" || featureType === "SubtractiveLoft"; + const pipe = featureType === "Pipe" || featureType === "SubtractivePipe"; + const nativeFeatureType = `PartDesign::${featureType === "Helix" || featureType === "Loft" || featureType === "Pipe" ? "Additive" : ""}${featureType}`; + const spineObject = objects.find(value => value.name === spine); + const auxiliaryObject = objects.find(value => value.name === auxiliarySpine); + const featureDetails = { body, profile, featureType, reversed, + ...(loft ? { sections, ruled, closed } : pipe ? { sections, referenceMode, spine, spineEdges, pipeMode, transition, auxiliarySpine, auxiliarySpineEdges, auxiliaryCurvilinear, binormal } : hole ? { diameter, depth, depthType } + : helix ? { height: helixHeight, pitch, leftHanded, axis, axisSubelement, angle: helixAngle, helixMode, turns: helixTurns, growth: helixGrowth, outside: helixOutside, helixReversed } : revolve ? { angle, axis, axisSubelement, rotationMode, ...(angle2 !== 0 ? { angle2 } : {}), midplane, rotationFace } : { length, extent: { ...extent, Length: length } }) }; + const featureInvalid = !profile || ((revolve || helix) && !axis) || (loft && (!sections.length || sections.includes(profile))) + || (revolve && ((!Number.isFinite(angle) || angle <= 0 || angle > 360) || (rotationMode === 4 && (!Number.isFinite(angle2) || angle2 <= 0 || angle2 > 360)) || (rotationMode === 3 && !rotationFace.object))) + || (pipe && (!spine || spine === profile || (pipeMode === "Auxiliary" && (!auxiliarySpine || auxiliarySpine === profile)) || (pipeMode === "Binormal" && (binormal.some(value => !Number.isFinite(value)) || Math.hypot(...binormal) <= 1e-7)))) + || (helix && ((helixMode !== "Pitch-Turns-Angle" && (!Number.isFinite(helixHeight) || helixHeight <= 0)) || (helixMode.startsWith("Pitch") && (!Number.isFinite(pitch) || pitch <= 0)) || (helixMode !== "Pitch-Height-Angle" && (!Number.isFinite(helixTurns) || helixTurns <= 0)))) + || (hole && (!Number.isFinite(diameter) || diameter <= 0 || (depthType === "Dimension" && (!Number.isFinite(depth) || depth <= 0)))); + const object = objects.find(value => value.name === selected); + const primitiveType = `${primitiveMode}${primitiveKind}`; + const primitiveInvalid = !body || !primitiveParametersValid(primitiveKind, primitiveParameters) + || primitivePosition.some(value => !Number.isFinite(value)); + const primitiveNeedsBase = primitiveMode === "Subtractive" && !bodies.find(value => value.name === body)?.tip; + const primitiveDetails = { body, primitiveType, parameters: primitiveParameters, position: primitivePosition }; + const multiEditing = object?.type === "PartDesign::MultiTransform" && object.body === body; + const multiOptions = objects.filter(value => value.body === body + && ["PartDesign::LinearPattern", "PartDesign::Mirrored", "PartDesign::PolarPattern", "PartDesign::Scaled"].includes(value.type) + && (!value.transformationOwner || (multiEditing && value.transformationOwner === selected))); + const multiInvalid = !multiChildren.length || new Set(multiChildren).size !== multiChildren.length + || multiChildren.some(name => !multiOptions.some(value => value.name === name)); + const moveMultiChild = (index: number, delta: number) => setMultiChildren(values => { + const next = [...values]; [next[index], next[index + delta]] = [next[index + delta], next[index]]; return next; + }); + const patternDirections = objects.filter(value => value.body === body && value.name !== selected).flatMap(value => { + const elements = value.type === "App::Line" || value.type === "PartDesign::Line" ? [""] + : value.type === "Sketcher::SketchObject" ? ["H_Axis", "V_Axis", "N_Axis", ...Array.from({ length: value.edgeCount ?? 0 }, (_, i) => `Edge${i + 1}`)] + : Array.from({ length: value.edgeCount ?? 0 }, (_, i) => `Edge${i + 1}`); + return elements.map(element => ({ value: JSON.stringify([value.name, element]), label: `${value.label}${element ? ` · ${element}` : ""}` })); + }); + const mirrorOriginalOptions = solids.filter(value => value.name !== (object?.type === "PartDesign::Mirrored" ? selected : "") && !value.transformationOwner); + const mirrorPlanes = objects.filter(value => value.body === body && value.name !== selected).flatMap(value => { + const elements = value.type === "App::Plane" || value.type === "PartDesign::Plane" ? [""] + : value.type === "Sketcher::SketchObject" ? ["H_Axis", "V_Axis", ...Array.from({ length: value.edgeCount ?? 0 }, (_, i) => `Edge${i + 1}`)] + : Array.from({ length: value.faceCount ?? 0 }, (_, i) => `Face${i + 1}`); + return elements.map(element => ({ value: JSON.stringify([value.name, element]), label: `${value.label}${element ? ` · ${element}` : ""}` })); + }); + const draftBases = solids.filter(value => value.name !== (object?.type === "PartDesign::Draft" ? selected : "")); + const draftPlanes = objects.filter(value => value.body === body && value.name !== (object?.type === "PartDesign::Draft" ? selected : "")).flatMap(value => { + const elements = ["App::Plane", "PartDesign::Plane"].includes(value.type) ? [""] + : [...Array.from({ length: value.faceCount ?? 0 }, (_, i) => `Face${i + 1}`), + ...Array.from({ length: value.edgeCount ?? 0 }, (_, i) => `Edge${i + 1}`)]; + return elements.map(element => ({ value: JSON.stringify([value.name, element]), label: `${value.label}${element ? ` · ${element}` : ""}` })); + }); + const draftInvalid = !draftBases.some(value => value.name === base) || !draftFaces.length + || draftFaces.some(face => !Array.from({ length: baseObject?.faceCount ?? 0 }, (_, i) => `Face${i + 1}`).includes(face)) + || !Number.isFinite(draftAngle) || draftAngle <= 1e-7 || draftAngle >= 90 + || (draftNeutral !== "" && !draftPlanes.some(value => value.value === draftNeutral)) + || (draftPull !== "" && !patternDirections.some(value => value.value === draftPull)); + const draftDetails = (): Partial => { + const reference = (value: string) => { const [object, element] = JSON.parse(value) as [string, string]; return { object, subelements: [element] }; }; + return { body, base, dressUpType: "Draft", faces: draftFaces, angle: draftAngle, reversed: draftReversed, + ...(draftNeutral ? { neutralPlane: reference(draftNeutral) } : {}), + ...(draftPull ? { pullDirection: reference(draftPull) } : {}) }; + }; + const mirrorInvalid = !body || !mirrorOriginals.length + || mirrorOriginals.some(name => !mirrorOriginalOptions.some(value => value.name === name)) + || !mirrorPlanes.some(value => value.value === mirrorPlane); + const mirrorDetails = (): Partial => { + const [reference, element] = JSON.parse(mirrorPlane) as [string, string]; + return { body, transformType: "Mirrored", originals: mirrorOriginals, mirrorPlane: { object: reference, subelements: [element] } }; + }; + const patternInvalid = !body || !patternOriginals.length + || patternOriginals.some(name => !solids.some(value => value.name === name && value.name !== (object?.type === "PartDesign::LinearPattern" ? selected : ""))) + || !patternDirections.some(value => value.value === patternDirection) + || !Number.isFinite(patternLength) || patternLength <= 1e-7 + || !Number.isInteger(patternCount) || patternCount < 2 || patternCount > 1000; + const patternDetails = (): Partial => { + const [reference, element] = JSON.parse(patternDirection) as [string, string]; + return { body, transformType: "LinearPattern", originals: patternOriginals, + direction: { object: reference, subelements: [element] }, length: patternLength, + occurrences: patternCount, reversed: patternReversed }; + }; + const polarInvalid = !body || !polarOriginals.length + || polarOriginals.some(name => !solids.some(value => value.name === name && !value.transformationOwner && value.name !== (object?.type === "PartDesign::PolarPattern" ? selected : ""))) + || !patternDirections.some(value => value.value === polarAxis) + || !Number.isFinite(polarAngle) || polarAngle <= 1e-7 || polarAngle > 360 + || !Number.isInteger(polarCount) || polarCount < 2 || polarCount > 1000; + const polarDetails = (): Partial => { + const [reference, element] = JSON.parse(polarAxis) as [string, string]; + return { body, transformType: "PolarPattern", originals: polarOriginals, + rotationAxis: { object: reference, subelements: [element] }, angle: polarAngle, + occurrences: polarCount, reversed: polarReversed }; + }; + const scaledOriginalOptions = solids.filter(value => !value.transformationOwner && value.name !== (object?.type === "PartDesign::Scaled" ? selected : "")); + const scaledInvalid = !body || !scaledOriginals.length + || scaledOriginals.some(name => !scaledOriginalOptions.some(value => value.name === name)) + || !Number.isFinite(scaledFactor) || scaledFactor <= 1e-7 + || !Number.isInteger(scaledCount) || scaledCount < 2 || scaledCount > 1000; + const scaledDetails = (): Partial => ({ body, transformType: "Scaled", originals: scaledOriginals, factor: scaledFactor, occurrences: scaledCount }); + const datumSupports = objects.filter(value => value.name !== body + && (value.name !== selected || object?.type !== `PartDesign::${datumType}`) && ((datumType === "Point" ? value.vertexCount : datumType === "Line" ? value.edgeCount : value.faceCount) ?? 0) > 0); + const datumSupportObject = datumSupports.find(value => value.name === datumSupport); + const datumExternal = !!datumSupportObject && datumSupportObject.body !== body; + const datumAttachable = ["Plane", "Line", "Point", "CoordinateSystem"].includes(datumType); + const datumElement = datumType === "Point" ? "Vertex" : datumType === "Line" ? "Edge" : "Face"; + const datumElementCount = (datumType === "Point" ? datumSupportObject?.vertexCount : datumType === "Line" ? datumSupportObject?.edgeCount : datumSupportObject?.faceCount) ?? 0; + // Mounted PartDesign uses the native current selection as the datum support. + useEffect(() => { + if (!embedded || !selected || selected === datumSupport) return; + const candidate = objects.find(value => value.name === selected); + if (!candidate || candidate.name === object?.name) return; + const count = datumType === "Point" ? (candidate.vertexCount ?? 0) : datumType === "Line" ? (candidate.edgeCount ?? 0) : (candidate.faceCount ?? 0); + if (count > 0) { setDatumSupport(candidate.name); setDatumFace(""); } + }, [embedded, selected, datumSupport, objects, datumType, object?.name]); + const datumAttached = datumAttachable && datumMapMode !== "Deactivated"; + const datumInvalid = datumOrigin.some(value => !Number.isFinite(value)) + || (datumAttached && (!datumSupportObject || !new RegExp(`^${datumElement}[1-9][0-9]*$`).test(datumFace) + || Number(datumFace.slice(datumElement.length)) > datumElementCount || datumOffset.some(value => !Number.isFinite(value)))); + const datumDetails = { body, datumType, origin: datumOrigin, + ...(datumAttachable ? { mapMode: datumMapMode, + support: datumAttached ? [{ object: datumSupport, subelements: [datumFace] }] : [], + ...(datumAttached && datumExternal ? { supportPolicy: datumPolicy } : {}), + ...(datumAttached ? { attachmentOffset: datumOffset } : {}) } : {}) }; + const binderSources = objects.filter(value => value.name !== body + && (value.name !== selected || value.name === binderSource) + && (value.edgeCount ?? 0) > 0); + const binderSupport = objects.find(value => value.name === binderSource); + const binderElements = binderSupport ? [ + ...Array.from({ length: binderSupport.faceCount ?? 0 }, (_, index) => `Face${index + 1}`), + ...Array.from({ length: binderSupport.edgeCount ?? 0 }, (_, index) => `Edge${index + 1}`), + ] : []; + const cloneSources = objects.filter(value => (value.volume ?? 0) > 0 && value.type !== "PartDesign::Body"); + const booleanCandidates = objects.filter(value => value.name !== body && value.name !== selected + && value.body !== body && (value.volume ?? 0) > 0 + && (value.type === "PartDesign::Body" || !value.body)); + const booleanInvalid = !body || !booleanTools.length || booleanTools.some(name => !booleanCandidates.some(value => value.name === name)); + const consumedObjects = () => new Set(objects.flatMap(value => { + const toolNames = value.type === "PartDesign::Boolean" ? value.tools ?? [] : []; + return [value.profile, value.base, ...toolNames, + ...toolNames.map(name => objects.find(tool => tool.name === name)?.tip)].filter(Boolean); + })); + useEffect(() => { if (embedded) return; if (viewport.current) renderer.mount(viewport.current); return () => renderer.dispose(); }, [renderer, Boolean(embedded)]); + // Desktop TreeWidget nests features under their Body (Tree.cpp DocumentItem / + // DocumentObjectItem). Rows carry the same columns and the visibility icon. + const treeNodes = (): DocumentTreeNode[] => { + const consumedHere = consumedObjects(); + const row = (item: DesignObject): DocumentTreeNode => { + // 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 = item.type.startsWith("PartDesign::") ? `/icons/partdesign/PartDesign_${item.type.replace("PartDesign::", "")}.svg` + : item.type === "Sketcher::SketchObject" ? "/icons/part/Sketcher_NewSketch.svg" + : "/icons/part/Part_3D_object.svg"; + return { + id: item.name, + label: item.label || item.name, + internalName: item.name, + description: item.type, + type: item.type, + icon, + visible: visibility[`${active}:${item.name}`] ?? !consumedHere.has(item.name), + toggleable: !!item.mesh, + children: [], + }; + }; + const byName = new Map(editable.map(item => [item.name, row(item)])); + const roots: DocumentTreeNode[] = []; + for (const item of editable) { + const node = byName.get(item.name)!; + const parent = item.body ? byName.get(item.body) : undefined; + if (parent && item.type !== "PartDesign::Body") parent.children!.push(node); else roots.push(node); + } + return roots; + }; + const toggleTreeVisibility = (id: string, visible: boolean) => + setVisibility(previous => ({ ...previous, [`${active}:${id}`]: visible })); + + useEffect(() => () => { if (!sharedRouter) router.dispose(); }, [router, sharedRouter]); + useEffect(() => { void listDocumentFiles().then(setFiles).catch(error => setStatus(String(error))); }, []); + useEffect(() => { + if (embedded) return; + const names = new Set(objects.map(value => value.name)); + for (const entry of renderer.scenes.objects(active)) if (!names.has(String(entry.object.userData.documentObjectId))) renderer.scenes.remove(active, String(entry.object.userData.documentObjectId)); + for (const item of objects) { + const mesh = documentObjectMesh(item); + if (mesh) renderer.scenes.add(active, item.name, mesh); + } + renderer.setMeasurements(active, objects); + renderer.activateDocument(active); + }, [active, current, renderer]); + useEffect(() => { + if (embedded) return; + renderer.onSelect = name => setSelected(name ?? ""); + const consumed = consumedObjects(); + for (const item of objects) renderer.scenes.update(active, item.name, { + visible: visibility[`${active}:${item.name}`] ?? !consumed.has(item.name), selected: item.name === selected, + color: item.type === "Sketcher::SketchObject" ? "#d0ba67" : "#73c6d4", + }); + return () => { renderer.onSelect = null; }; + }, [active, current, selected, visibility, renderer]); + useEffect(() => { + if (!linkDialogOpen) return; + const close = (event: KeyboardEvent) => { + if (event.key !== "Escape") return; + event.preventDefault(); + setLinkDialogOpen(false); + }; + window.addEventListener("keydown", close); + return () => window.removeEventListener("keydown", close); + }, [linkDialogOpen]); + useEffect(() => { + if (!linkRowMenu) return; + const close = (event: PointerEvent | KeyboardEvent) => { + if (event instanceof KeyboardEvent && event.key !== "Escape") return; + if (event instanceof PointerEvent && (event.target as HTMLElement)?.closest('[role="menu"][aria-label="Binder support actions"]')) return; + setLinkRowMenu(null); + }; + window.addEventListener("pointerdown", close, true); window.addEventListener("keydown", close, true); + return () => { window.removeEventListener("pointerdown", close, true); window.removeEventListener("keydown", close, true); }; + }, [linkRowMenu]); + // The embedded viewport belongs to the primary workspace. Updating a task + // must preserve the camera the user positioned to inspect the edited feature. + useEffect(() => { if (!embedded) renderer.fitDocument(); }, [active, current, renderer, Boolean(embedded)]); + useEffect(() => { + const nextBody = bodies.some(value => value.name === body) ? body : bodies[0]?.name ?? ""; + const owned = objects.filter(value => value.body === nextBody); + const profiles = owned.filter(value => value.type === "Sketcher::SketchObject" || value.gearType); + if (nextBody !== body) setBody(nextBody); + // Reopening selects a feature before Body state has caught up. Resolve + // its persisted Profile against the next Body, not the stale empty list. + if (!profiles.some(value => value.name === profile)) + setProfile(profiles.find(value => value.name === object?.profile)?.name ?? profiles.at(-1)?.name ?? ""); + const nativeAxes = owned.filter(value => value.type === "App::Line"); + if (!owned.some(value => value.name === axis)) setAxis(nativeAxes.find(value => value.label === "Y-axis")?.name ?? nativeAxes[0]?.name ?? ""); + const nativeSolids = owned.filter(value => value.type.startsWith("PartDesign::") && (value.volume ?? 0) > 0); + if (!nativeSolids.some(value => value.name === base)) setBase(nativeSolids.at(-1)?.name ?? ""); + if (!cloneSources.some(value => value.name === cloneSource)) setCloneSource(cloneSources.at(-1)?.name ?? ""); + }, [active, current, body, profile, axis, base, cloneSource]); + const previousTips = useRef>({}); + useEffect(() => { + if (embedded) return; + const changed = bodies.filter(value => previousTips.current[`${active}:${value.name}`] !== value.tip); + if (changed.length) setVisibility(previous => { + const next = { ...previous }; + for (const owner of changed) for (const feature of objects) + if (feature.body === owner.name && feature.type.startsWith("PartDesign::") && (feature.volume ?? 0) > 0) + next[`${active}:${feature.name}`] = feature.name === owner.tip; + return next; + }); + previousTips.current = Object.fromEntries(bodies.map(value => [`${active}:${value.name}`, value.tip])); + }, [active, current, Boolean(embedded)]); + const restoreCommittedFields = (resetCreationDefaults = false) => { + setReorderObjects([]); setReorderAfter(""); + setMoveObjects([]); setMoveTargetBody(""); + setDuplicateObjects([]); setDuplicateRecursive(true); setDuplicateBody(""); + if (resetCreationDefaults) { + const nextBody = object?.body ?? (object?.type === "PartDesign::Body" ? object.name + : bodies.some(value => value.name === body) ? body : bodies[0]?.name ?? ""); + const owned = objects.filter(value => value.body === nextBody); + const nativeAxes = owned.filter(value => value.type === "App::Line"); + setBody(nextBody); + setGearKind("InvoluteGear"); setGearParameters({ ...gearDefaults.InvoluteGear }); setGearPreset(""); + setPrimitiveMode("Additive"); setPrimitiveKind("Box"); setPrimitiveParameters({ ...designPrimitiveDefaults.Box }); setPrimitivePosition([0, 0, 0]); + setSketchMapMode("Deactivated"); setSketchSupport(""); setSketchFace(""); setSketchRotation([0, 0, 0, 1]); setSketchRotationMode("XY"); + setProfileType("Rectangle"); setParameters({ Width: 10, Height: 8 }); setPosition([0, 0, 0]); + const reset = defaultSketchProfile(); setSketchGeometries(reset.geometries); setSketchConstraints(reset.constraints); setRequireFullyConstrained(false); + setProfile(owned.filter(value => value.type === "Sketcher::SketchObject" || value.gearType).at(-1)?.name ?? ""); + setFeatureType("Pad"); setLength(6); setReversed(false); + setRotationMode(0); setAngle2(90); setMidplane(false); setRotationFace({ object: "", subelement: "" }); + setHelixMode("Pitch-Height-Angle"); setHelixAngle(0); setHelixTurns(3); setHelixGrowth(0); setHelixOutside(false); setHelixReversed(false); setAxisSubelement(""); setReferenceMode("CrossReference"); + setExtent({ Type: "Length", Type2: "Length", SideType: "One side", Length2: 6, Offset: 0, Offset2: 0, TaperAngle: 0, TaperAngle2: 0, AlongSketchNormal: true, Direction: [0, 0, 1] }); + setAngle(360); setAxis(nativeAxes.find(value => value.label === "Y-axis")?.name ?? nativeAxes[0]?.name ?? ""); + setHelixHeight(10); setPitch(3); setLeftHanded(false); + setDiameter(4); setDepth(5); + setSections([]); setRuled(false); setClosed(false); setSpine(""); setSpineEdges([]); + setPipeMode("Standard"); setTransition("Transformed"); setAuxiliarySpine(""); setAuxiliarySpineEdges([]); + setAuxiliaryCurvilinear(true); setBinormal([0, 0, 1]); + setDatumType("Plane"); setDatumOrigin([0, 0, 0]); + setDatumMapMode("Deactivated"); setDatumSupport(""); setDatumPolicy("Independent"); setDatumFace(""); setDatumOffset([0, 0, 0]); + setCloneSource(cloneSources.at(-1)?.name ?? ""); + setBinderSource(""); setBinderSubelements([]); setTraceSupport(true); + setBinderKind("ShapeBinder"); setBinderLinks([]); setBindMode("Synchronized"); + setMultiChildren([]); setMultiChild(""); + setMirrorOriginals([]); setMirrorPlane(""); + setPatternOriginals([]); setPatternDirection(""); setPatternLength(12); setPatternCount(3); setPatternReversed(false); + setScaledOriginals([]); setScaledFactor(2); setScaledCount(2); + setPolarOriginals([]); setPolarAxis(""); setPolarAngle(360); setPolarCount(3); setPolarReversed(false); + setBooleanOperation("Fuse"); setBooleanTools([]); + setDressUpType("Fillet"); setBase(owned.filter(value => (value.volume ?? 0) > 0).at(-1)?.name ?? ""); + setEdges(["Edge1"]); setUseAllEdges(false); setSize(0.5); + setChamferType("Equal distance"); setChamferSize2(1); setChamferAngle(45); setChamferFlip(false); + setThicknessFaces([]); setWallSize(1); setWallInwards(true); + setDraftFaces([]); setDraftAngle(10); setDraftReversed(false); setDraftNeutral(""); setDraftPull(""); + } + if (!object) return; + if (object.body) setBody(object.body); + if (object.type === "PartDesign::Body") setBody(object.name); + if (object.gearType && object.gearParameters) { + const { SprocketReference: _reference, ...values } = object.gearParameters; + setGearKind(object.gearType); setGearParameters({ ...gearDefaults[object.gearType], ...values }); setGearPreset(""); setProfile(object.name); + } + const primitiveMatch = /^PartDesign::(Additive|Subtractive)(Box|Cylinder|Sphere|Cone|Ellipsoid|Torus|Prism|Wedge)$/.exec(object.type); + if (primitiveMatch) { + setPrimitiveMode(primitiveMatch[1] as "Additive" | "Subtractive"); setPrimitiveKind(primitiveMatch[2]); + setPrimitiveParameters({ ...designPrimitiveDefaults[primitiveMatch[2]], ...object.parameters }); + setPrimitivePosition([...(object.position ?? [0, 0, 0])]); + } + if (object.type === "Sketcher::SketchObject") { + setSketchMapMode(object.mapMode === "FlatFace" ? "FlatFace" : "Deactivated"); + setSketchSupport(object.support?.[0]?.object ?? ""); + setSketchFace(object.support?.[0]?.subelements[0] ?? ""); + } + if (object.profileType) { + setProfileType(object.profileType); setParameters({ ...object.parameters }); setPosition([...(object.position ?? [0, 0, 0])]); + setSketchRotation([...(object.placementRotation ?? [0, 0, 0, 1])] as [number, number, number, number]); setProfile(object.name); + // A Geometry profile is re-edited from the native snapshot: the kernel + // returns the live geometry/constraint arrays so the editor round-trips + // instead of silently resetting to the default rectangle. + if (object.profileType === "Geometry" && Array.isArray(object.geometries) && object.geometries.length) { + setSketchGeometries(object.geometries.map(entry => ({ ...entry }))); + setSketchConstraints((object.constraints ?? []).map(entry => ({ ...entry }))); + } + } + if (object.type === "PartDesign::ShapeBinder" || object.type === "PartDesign::SubShapeBinder") { + setBinderKind(object.type === "PartDesign::SubShapeBinder" ? "SubShapeBinder" : "ShapeBinder"); + setBinderLinks(object.support?.map(link => ({ ...link, subelements: [...link.subelements] })) ?? []); + setBindMode(object.bindMode ?? "Synchronized"); + setBinderSource(object.support?.[0]?.object ?? ""); + setBinderSubelements(object.type === "PartDesign::SubShapeBinder" + ? [...(object.support?.[0]?.subelements ?? [])] : object.support?.flatMap(link => link.subelements) ?? []); + setTraceSupport(object.traceSupport ?? false); + } + if (object.profile) { + setProfile(object.profile); setFeatureType(object.type.replace("PartDesign::", "").replace(/^Additive/, "") as ProfileFeature); + setLength(object.length ?? 6); setAngle(object.angle ?? 360); if (object.axis) setAxis(object.axis); setReversed(object.reversed ?? false); + setRotationMode(object.rotationMode ?? 0); setAngle2(object.angle2 ?? 90); setMidplane(object.midplane ?? false); + setRotationFace({ object: object.extent?.UpToFace?.object ?? "", subelement: object.extent?.UpToFace?.subelements?.[0] ?? "" }); + setDiameter(object.diameter ?? 4); setDepth(object.depth ?? 5); + setDepthType(object.depthType === "ThroughAll" ? "ThroughAll" : "Dimension"); + setHelixHeight(object.height ?? 10); setPitch(object.pitch ?? 3); setLeftHanded(object.leftHanded ?? false); + setHelixAngle(object.angle ?? 0); setAxisSubelement(object.axisSubelement ?? ""); setReferenceMode(object.referenceMode ?? "CrossReference"); // Only Pad and Pocket have the Length/ThroughAll extent modes. A Revolution or + // Helix has no `Type`/`Type2` enumeration at all, so copying `object.extent` + // wholesale let a rotation mode leak into the next Pocket as its stretch + // mode; the kernel then rejected the whole feature with + // "invalid extent mode" and the Pocket silently did nothing. + const extentModes = ["Pad", "Pocket"].includes(object.type.replace("PartDesign::", "").replace(/^Additive/, "")); + setExtent(extentModes + ? object.extent ?? { Type: "Length", Type2: "Length", SideType: "One side", AlongSketchNormal: true, Direction: [0, 0, 1] } + : { Type: "Length", Type2: "Length", SideType: "One side", Length2: 6, Offset: 0, Offset2: 0, TaperAngle: 0, TaperAngle2: 0, AlongSketchNormal: true, Direction: [0, 0, 1] }); + setHelixMode(object.helixMode ?? "Pitch-Height-Angle"); setHelixTurns(object.turns ?? 3); setHelixGrowth(object.growth ?? 0); setHelixOutside(object.outside ?? false); setHelixReversed(object.helixReversed ?? false); + setSections(object.sections ?? []); setRuled(object.ruled ?? false); setClosed(object.closed ?? false); + setSpine(object.spine ?? ""); setSpineEdges(object.spineEdges ?? []); + setPipeMode(object.pipeMode ?? "Standard"); setTransition(object.transition ?? "Transformed"); + setAuxiliarySpine(object.auxiliarySpine ?? ""); setAuxiliarySpineEdges(object.auxiliarySpineEdges ?? []); + setAuxiliaryCurvilinear(object.auxiliaryCurvilinear ?? true); setBinormal(object.binormal ?? [0, 0, 1]); + } + if (object.type === "PartDesign::MultiTransform") { + setMultiChildren([...(object.transformations ?? [])]); setMultiChild(""); + } + const committedOriginals = objects.find(value => value.name === object.transformationOwner)?.originals ?? object.originals ?? []; + if (object.type === "PartDesign::Mirrored") { + setMirrorOriginals(committedOriginals); + setMirrorPlane(object.mirrorPlane ? JSON.stringify([object.mirrorPlane.object, object.mirrorPlane.subelements[0] ?? ""]) : ""); + } + if (object.type === "PartDesign::LinearPattern") { + setPatternOriginals(committedOriginals); + setPatternDirection(object.direction ? JSON.stringify([object.direction.object, object.direction.subelements[0] ?? ""]) : ""); + setPatternLength(object.length ?? 12); setPatternCount(object.occurrences ?? 3); setPatternReversed(object.reversed ?? false); + } + if (object.type === "PartDesign::Scaled") { + setScaledOriginals(committedOriginals); setScaledFactor(object.factor ?? 2); setScaledCount(object.occurrences ?? 2); + } + if (object.type === "PartDesign::PolarPattern") { + setPolarOriginals(committedOriginals); + setPolarAxis(object.rotationAxis ? JSON.stringify([object.rotationAxis.object, object.rotationAxis.subelements[0] ?? ""]) : ""); + setPolarAngle(object.angle ?? 360); setPolarCount(object.occurrences ?? 3); setPolarReversed(object.reversed ?? false); + } + if (object.type === "PartDesign::Boolean") { + setBooleanOperation(object.operation ?? "Fuse"); setBooleanTools(object.tools ?? []); + } + if (object.dressUpType) { if (object.dressUpType === "Fillet" || object.dressUpType === "Chamfer") setDressUpType(object.dressUpType); setBase(object.base ?? ""); setEdges(object.edges ?? []); setUseAllEdges((object.dressUpType === "Fillet" || object.dressUpType === "Chamfer") && (object.useAllEdges ?? false)); setSize(object.size ?? 0.5); } + else if (object.type.startsWith("PartDesign::") && object.body && (object.volume ?? 0) > 0) setBase(object.name); + if (object.dressUpType === "Chamfer") { + setChamferType(object.chamferType ?? "Equal distance"); setChamferSize2(object.size2 ?? 1); + setChamferAngle(object.angle ?? 45); setChamferFlip(object.flipDirection ?? false); + } + if (object.dressUpType === "Thickness") { setThicknessFaces(object.faces ?? []); setWallSize(object.size ?? 1); setWallInwards(object.reversed ?? false); setThicknessMode(object.thicknessMode ?? "Skin"); setThicknessJoin(object.thicknessJoin ?? "Arc"); setThicknessIntersection(object.thicknessIntersection ?? false); } + if (object.dressUpType === "Draft") { + setDraftFaces(object.faces ?? []); setDraftAngle(object.angle ?? 10); setDraftReversed(object.reversed ?? false); + setDraftNeutral(object.neutralPlane ? JSON.stringify([object.neutralPlane.object, object.neutralPlane.subelements[0] ?? ""]) : ""); + setDraftPull(object.pullDirection ? JSON.stringify([object.pullDirection.object, object.pullDirection.subelements[0] ?? ""]) : ""); + } + const datum = object.type.replace("PartDesign::", ""); + if (["Plane", "Line", "Point", "CoordinateSystem"].includes(datum)) { + setDatumType(datum as DatumType); setDatumOrigin([...(object.position ?? [0, 0, 0])]); + setDatumMapMode(object.mapMode === "FlatFace" || object.mapMode === "TwoPointLine" || object.mapMode === "Vertex" ? object.mapMode : "Deactivated"); + setDatumSupport(object.supportSource || object.support?.[0]?.object || ""); setDatumFace(object.supportElement || object.support?.[0]?.subelements[0] || ""); + setDatumPolicy(object.supportPolicy === "Dependent" || object.supportPolicy === "CrossReference" ? object.supportPolicy : "Independent"); + setDatumOffset([...(object.attachmentOffset ?? [0, 0, 0])]); + } + if ((object.volume ?? 0) > 0 && object.type !== "PartDesign::Body") setCloneSource(object.name); + }; + useEffect(() => { + if (!embedded) return; + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== "Escape" || busy || linkDialogOpen) return; + event.preventDefault(); event.stopImmediatePropagation(); + endReferenceTask(); restoreCommittedFields(true); setFailed(false); setStatus("Draft cancelled; document unchanged"); embedded.onStatus("Draft cancelled; document unchanged"); + }; + window.addEventListener("keydown", onKeyDown, true); + return () => window.removeEventListener("keydown", onKeyDown, true); + }, [embedded, busy, linkDialogOpen, endReferenceTask, restoreCommittedFields]); + useLayoutEffect(() => { restoreCommittedFields(); }, [active, object]); + useEffect(() => () => { previewLease.current?.(); previewLease.current = null; renderer.scenes.remove(active, "PartDesignMaterialPreview"); renderer.scenes.remove(active, "PartDesignFinalPreview"); }, [active, renderer]); + useEffect(() => { + if (!materialPreview) return; + for (const [name, mesh] of [["PartDesignMaterialPreview", materialPreview.material], + ["PartDesignFinalPreview", materialPreview.final]] as const) { + // Native JSON contains numeric arrays; use the same validation and buffer + // conversion as committed document meshes before passing it to the renderer. + const payload = documentObjectMesh({ name, label: name, type: "PartDesign::Feature", + mesh: mesh as NativeDocumentObject["mesh"] }); + if (payload) renderer.showForDocument(active, name, payload); + } + return () => { renderer.scenes.remove(active, "PartDesignMaterialPreview"); renderer.scenes.remove(active, "PartDesignFinalPreview"); }; + }, [active, materialPreview, renderer]); + const request = async (document: string, action: DesignPayload["action"], details: Partial = {}) => { + if (embedded) { + if (document !== embedded.document) throw new Error("Select the active document"); + return embedded.request(action, details); + } + const reply = await router.request("PartDesign", PARTDESIGN_DOCUMENT_COMMAND, + { schema: PARTDESIGN_DOCUMENT_SCHEMA, module: "PartDesign", document, action, includeMesh: true, ...details }, document); + if (reply.kind === "error") throw new Error(`${reply.error.code}: ${reply.error.message}`); + return reply.result as DesignResult; + }; + const apply = (result: DesignResult) => { if (embedded) embedded.onSnapshot(result); else setDocuments(previous => ({ ...previous, [result.document]: result })); setSavedBytes(null); }; + const unique = (stem: string) => { let index = 1; while (objects.some(value => value.name === `${stem}${index}`)) index++; return `${stem}${index}`; }; + const perform = async (operation: () => Promise) => { + // React state is published on the next render; guard native transactions + // synchronously so repeated activation cannot submit the same edit twice. + if (operationInFlight.current) return; + operationInFlight.current = true; + setBusy(true); embedded?.onBusy(true); setFailed(false); + try { await operation(); } catch (error) { setFailed(true); setStatus(String(error)); embedded?.onStatus(String(error)); } + finally { operationInFlight.current = false; setBusy(false); embedded?.onBusy(false); } + }; + const edit = (action: DesignAction, details: Partial) => perform(async () => { + endReferenceTask(); + if (!current) apply(await request(active, "create")); + const result = await request(active, action, details); apply(result); + setSelected(result.selectedObjects?.[0] ?? (details.object && result.objects?.some(value => value.name === details.object) ? details.object : "")); + setStatus(`${action}: ${details.object ?? active}`); + }); + const previewFeature = () => perform(async () => { + if (!current || !body || !profile || !["Pad", "Pocket", "Helix", "SubtractiveHelix"].includes(featureType) || featureInvalid) return; + const result = await request(active, "previewFeature", { object: selected || unique(featureType), ...featureDetails }); + previewLease.current?.(); + previewLease.current = renderer.hideForTaskPreview(active, objects.filter(value => value.body === body && value.mesh).map(value => value.name)); + setMaterialPreview(result.preview); + setStatus("Material preview ready"); + }); + const clearMaterialPreview = () => { previewLease.current?.(); previewLease.current = null; renderer.scenes.remove(active, "PartDesignMaterialPreview"); renderer.scenes.remove(active, "PartDesignFinalPreview"); setMaterialPreview(undefined); }; + const createDocument = () => perform(async () => { const name = `Design${++serial.current}`; const result = await request(name, "create"); apply(result); setActive(name); setSelected(""); setBody(""); setStatus(name); }); + const profilePayload = profileType === "Geometry" + ? { profileType, geometries: sketchGeometries, constraints: sketchConstraints, requireFullyConstrained } + : { profileType, parameters }; + const editSketch = () => { + if (embedded) return edit("setSketch", { object: selected, body, ...profilePayload, position, placementRotation: sketchRotation }); + return perform(async () => { + const reply = await executePartDesignDesktop(router, "Sketcher_EditSketch", { + body, ...profilePayload, position, placementRotation: sketchRotation, selection: [{ documentId: active, object: selected }], includeMesh: true, + }, active, (_document, selection) => setSelected(selection[0]?.object ?? "")); + if (!reply || reply.kind === "error") throw new Error(reply?.error.message ?? "Sketch edit failed"); + apply(reply.result as DesignResult); setStatus(`Sketcher_EditSketch: ${selected}`); + }); + }; + const createSketch = () => perform(async () => { + endReferenceTask(); + if (!current) apply(await request(active, "create")); + const name = unique("Sketch"); + let result = await request(active, "setSketch", { object: name, body, ...profilePayload, position, placementRotation: sketchRotation }); + apply(result); + if (sketchMapMode === "FlatFace") { + try { + result = await request(active, "mapSketch", { object: name, body, mapMode: "FlatFace", support: [{ object: sketchSupport, subelements: [sketchFace] }] }); + apply(result); + } catch (error) { + try { apply(await request(active, "remove", { object: name })); } catch { /* Preserve the original attachment failure. */ } + throw error; + } + } + setSelected(result.selectedObjects?.[0] ?? name); + setStatus(`setSketch: ${name}`); + }); + const editBinder = (target: string) => { + const details = { object: target, body, ...(binderKind === "SubShapeBinder" + ? { support: binderLinks, bindMode } : { support: [{ object: binderSource, subelements: binderSubelements }], traceSupport }) }; + if (embedded) return edit(binderKind === "SubShapeBinder" ? "setSubShapeBinder" : "setShapeBinder", details); + return perform(async () => { + const reply = await executePartDesignDesktop(router, `PartDesign_${binderKind}`, { + ...details, includeMesh: true, + }, active, (_document, selection) => setSelected(selection[0]?.object ?? "")); + if (!reply || reply.kind === "error") throw new Error(reply?.error.message ?? "ShapeBinder edit failed"); + apply(reply.result as DesignResult); setStatus(`PartDesign_${binderKind}: ${target}`); + }); + }; + const openDocument = (source: ArrayBuffer | Promise, filename: string) => perform(async () => { + const bytes = await source; + const name = `Design${++serial.current}`; const result = await request(name, "open", { path: `/tmp/${name}.FCStd`, bytes }); + apply(result); setActive(name); setSelected(result.objects?.find(value => value.type === "PartDesign::Body")?.tip ?? ""); setStatus(`已打开 ${filename}`); + }); + const save = () => perform(async () => { + const filename = `${active}.FCStd`; const result = await request(active, "save", { path: `/tmp/${filename}` }); + if (!result.bytes) throw new Error("Native FCStd bytes missing"); + await writeDocumentFile(filename, result.bytes); apply(result); setSavedBytes(result.bytes); setFiles(await listDocumentFiles()); setFile(filename); setStatus(`已保存 ${filename} (${result.bytes.byteLength} bytes)`); + }); + const close = () => perform(async () => { + await request(active, "close", { includeMesh: false }); + const next = { ...documents }; delete next[active]; setDocuments(next); renderer.removeDocument(active); + setActive(Object.keys(next)[0] ?? `Design${++serial.current}`); setSelected(""); setSavedBytes(null); setStatus("文档已关闭"); + }); + const downloadBytes = (bytes: ArrayBuffer, filename: string) => { + const url = URL.createObjectURL(new Blob([bytes], { type: "application/octet-stream" })); + const link = document.createElement("a"); link.href = url; link.download = filename; link.click(); window.setTimeout(() => URL.revokeObjectURL(url), 1000); + }; + const download = () => { if (savedBytes) downloadBytes(savedBytes, `${active}.FCStd`); }; + // Exports land in OPFS; a browser download only happens when the user asks. + const exportGeometry = () => perform(async () => { + const filename = `${active}_${selected}.${exportFormat}`; + const result = await request(active, "export", { object: selected, path: `/tmp/${filename}`, includeMesh: false }); + if (!result.bytes) throw new Error("Native export returned no bytes"); + const stored = await writeExportFile(filename, result.bytes); + setExportedFiles(await listExportFiles()); setExportFile(stored); + setStatus(`已写入 OPFS:${stored} (${result.bytes.byteLength} bytes)`); + }); + const downloadExport = () => perform(async () => { + if (!exportFile) throw new Error("先在 OPFS 导出列表里选择一个文件"); + const bytes = await readExportFile(exportFile); + downloadBytes(bytes, exportFile); setStatus(`已下载到本地:${exportFile}`); + }); + const importGeometry = (file: File) => perform(async () => { + const extension = file.name.split(".").at(-1)?.toLowerCase(); + if (!extension || !["step", "stp", "brep", "brp", "iges", "igs", "stl"].includes(extension)) throw new Error("Unsupported geometry format"); + const bytes = await file.arrayBuffer(); + if (!current) apply(await request(active, "create")); + const name = unique("Imported"); + const result = await request(active, "importShape", { object: name, label: file.name, path: `/tmp/${active}_${name}.${extension}`, bytes }); + apply(result); setSelected(name); setStatus(`已导入 ${file.name}`); + }); + const consumed = consumedObjects(); + const tool = (label: string, icon: IconNode, action: () => void, disabled = false) => ; + const sketchSupports = objects.filter(value => value.body === body + && (value.name !== selected || value.type !== "Sketcher::SketchObject") && (value.faceCount ?? 0) > 0); + const sketchSupportObject = sketchSupports.find(value => value.name === sketchSupport); + const sketchGeometryInvalid = !sketchGeometries.length || sketchGeometries.some(geometry => + ["line", "circle", "arc", "ellipse", "bspline"].some(entry => entry === geometry.type) && ( + (geometry.type === "line" && !(geometry.start && geometry.end)) + || (["circle", "arc"].includes(geometry.type) && !(geometry.center && Number(geometry.radius) > 0)) + || (geometry.type === "arc" && !(Number.isFinite(geometry.startAngle) && Number.isFinite(geometry.endAngle))) + || (geometry.type === "ellipse" && !(geometry.center && Number(geometry.majorRadius) > 0 + && Number(geometry.minorRadius) > 0 && Number(geometry.minorRadius) <= Number(geometry.majorRadius))) + || (geometry.type === "bspline" && !(geometry.points && geometry.points.length >= 2)))) + || (profileType === "Geometry" && sketchConstraints.some(constraint => constraint.value !== undefined && !Number.isFinite(constraint.value))); + const sketchProfileInvalid = (profileType === "Geometry" ? sketchGeometryInvalid : Object.values(parameters).some(value => !Number.isFinite(value) || value <= 0)) + || position.some(value => !Number.isFinite(value)); + const sketchAttachmentInvalid = sketchMapMode === "FlatFace" + && (!sketchSupportObject || !/^Face[1-9][0-9]*$/.test(sketchFace) + || Number(sketchFace.slice(4)) > (sketchSupportObject.faceCount ?? 0)); + const sketchMappingInvalid = object?.type !== "Sketcher::SketchObject" || object.body !== body + || sketchAttachmentInvalid; + const sketchControls =
约束草图
{(["Rectangle", "Circle", "Geometry"] as ProfileType[]).map(kind => )}
+ {profileType === "Geometry" + ? { setSketchGeometries(next.geometries); setSketchConstraints(next.constraints); setRequireFullyConstrained(next.requireFullyConstrained); }} /> + : (profileType === "Circle" ? ["Radius"] : ["Width", "Height"]).map(field => )} +
{["X", "Y", "Z"].map((axis, index) => )}
+ + {sketchRotationMode === "Custom" &&
{["W", "X", "Y", "Z"].map((axis, index) => )}
} +
+ + + {sketchMapMode === "FlatFace" && <> + + +

Select a planar face. Curved faces and cyclic references are rejected without changing the committed sketch.

+ } + +
; + const mirrorControls =
Mirrored + + +

Choose an origin or datum plane, planar face, or sketch axis / straight edge. Unsupported references preserve the committed feature.

+
+
+
; + const patternControls =
LinearPattern + + + + + +
+
+
; + const multiControls =
MultiTransform + + +
    {multiChildren.map((name, index) =>
  1. {objects.find(value => value.name === name)?.label ?? name} + + + +
  2. )}
+
+
+
; + const scaledControls =
Scaled + + + +
+
+
; + const polarControls =
PolarPattern + + + + + +
+
+
; + const featureControls =
基于草图的特征
{(["Pad", "Pocket", "Hole", "Revolution", "Groove", "Helix", "Loft", "Pipe", "SubtractiveHelix", "SubtractiveLoft", "SubtractivePipe"] as ProfileFeature[]).map(type => )}
+ + {loft ? <> + + + : pipe ? <> + + + +
    {sections.map((section, index) =>
  1. {section}
  2. )}
+ + + + + + {pipeMode === "Auxiliary" && <> + + + + + } + {pipeMode === "Binormal" && binormal.map((value, index) => )} + + : hole ? <> + + {depthType === "Dimension" && } + : helix ? <> + + + + + : revolve ? <> + + {(rotationMode === 0 || rotationMode === 4) && } + {rotationMode === 4 && } + + + {rotationMode === 3 && <> + + + } + + : } + {(featureType === "Pad" || featureType === "Pocket") && <> + + {["", "2"].map(suffix =>
Side {suffix || "1"} + + {(suffix ? ["Length", "Offset", "TaperAngle"] : ["Offset", "TaperAngle"]).map(field => )} + {["UpToFace", "UpToShape"].filter(mode => extent[`Type${suffix}`] === mode).map(mode => { const key = `${mode}${suffix}`; const ref = extent[key] ?? { object: "", subelements: [] }; const target = objects.find(item => item.name === ref.object); return
+ + +
; })} +
)} + + {!(extent.AlongSketchNormal ?? true) && [0, 1, 2].map(index => )} + } + +
+
; + const referenceControls = <> +
基准对象 + + {datumAttachable && } + {datumAttached ? <> + + {datumExternal && } + +
{["X", "Y", "Z"].map((axis, index) => )}
+

偏移沿支撑局部坐标;不支持的曲线或曲面会保留原对象并提示错误。

+ :
{["X", "Y", "Z"].map((axis, index) => )}
} +
+
+
+
关联克隆 + +
+
+
Binder + + + + {binderKind === "SubShapeBinder" ? <> + +
    {binderLinks.map(link =>
  • { event.preventDefault(); setLinkRowMenu({ object: link.object, x: Math.min(event.clientX, innerWidth - 180), y: Math.min(event.clientY, innerHeight - 48) }); }} onKeyDown={event => { if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) { event.preventDefault(); const rect = event.currentTarget.getBoundingClientRect(); setLinkRowMenu({ object: link.object, x: Math.min(rect.left + 12, innerWidth - 180), y: Math.min(rect.bottom, innerHeight - 48) }); return; } if (!(event.key === "Delete" || event.key === "Backspace")) return; event.preventDefault(); setBinderLinks(previous => previous.filter(item => item.object !== link.object)); }}> + + + +
  • )}
+ {linkRowMenu && <>
} + +

Synchronized follows source changes. Frozen retains links and geometry. Detached removes links and keeps geometry; add supports to reattach.

+ : } +
+
+ {linkDialogOpen && <> +

Link

+
+
    + {objects.filter(item => item.name !== body && ((item.edgeCount ?? 0) > 0 || linkDialogDraft.some(link => link.object === item.name))).filter(item => !linkDialogFilterType || item.type.startsWith("PartDesign::")).filter(item => !linkDialogSearch || `${item.label} ${item.name}`.toLowerCase().includes(linkDialogSearch.toLowerCase())).map(item => { + const linked = linkDialogDraft.some(link => link.object === item.name); + return
  • ; + })} +
+ {(() => { const selected = objects.find(item => item.name === linkDialogSelectedObject); const current = linkDialogDraft.find(link => link.object === linkDialogSelectedObject); if (!selected || !current) return null; const elements = [...Array.from({ length: selected.faceCount ?? 0 }, (_, i) => `Face${i + 1}`), ...Array.from({ length: selected.edgeCount ?? 0 }, (_, i) => `Edge${i + 1}`)]; return ; })()} +
+
} + ; + const chamferFields: Partial = dressUpType === "Chamfer" + ? { chamferType, size2: chamferSize2, angle: chamferAngle, flipDirection: chamferFlip } : {}; + const dressUpInvalid = !base || (!edges.length && !useAllEdges) || !Number.isFinite(size) || size <= 1e-7 + || (dressUpType === "Chamfer" && (size > 3.4028234663852886e38 + || !Number.isFinite(chamferSize2) || chamferSize2 < 0 || chamferSize2 > 3.4028234663852886e38 + || !Number.isFinite(chamferAngle) || chamferAngle < 0 || chamferAngle > 180 + || (chamferType === "Two distances" && chamferSize2 <= 0) + || (chamferType === "Distance and Angle" && (chamferAngle <= 0 || chamferAngle >= 180)))); + const finishingControls = <> + {referenceTask &&
{ + if (event.key === "Delete" && referenceRows.length) { + event.preventDefault(); event.stopPropagation(); + setReferenceDraft(previous => previous.filter(value => !referenceRows.includes(value))); setReferenceMenu(false); + } else if (event.ctrlKey && event.shiftKey && event.key.toLowerCase() === "a" && !referenceTask.thickness) { + event.preventDefault(); event.stopPropagation(); + setReferenceDraft(previous => [...new Set([...previous, ...Array.from({ length: baseObject?.edgeCount ?? 0 }, (_, index) => `Edge${index + 1}`)])]); + } + }}>Inspect {referenceTask.base} references + + +

Pick on the base in the viewport, or select a reference below. Confirm to use this selection in the draft.

+
{(baseObject?.dressUpReferences ?? []).filter(value => !referenceTask.thickness || value.subelement.startsWith("Face")).map(value => + )}
+ {referenceMenu &&
} +
+ {!referenceTask.thickness && } + + + +
+
} + {embedded &&
Part datum / attachment +
{(["Part_DatumPoint", "Part_DatumLine", "Part_DatumPlane", "Part_CoordinateSystem"] as PartDatumCommand[]).map(command => + )}
+ {partDatumCommand && { throw new Error("Embedded datum task requires the current document owner"); }} + embedded={{ + snapshot: embedded.snapshot as unknown as PartDocumentResult, + initialObject: embedded.snapshot?.objects?.find(item => item.name === selected)?.type === PART_DATUM_TYPES[partDatumCommand] ? selected : "", + selection: embedded.datumSelection ?? (selected ? [{ object: selected, subelements: [] }] : []), + request: async (action, details) => { + embedded.onBusy(true); + try { return await embedded.request(action, details) as unknown as PartDocumentResult; } + finally { embedded.onBusy(false); } + }, + onSnapshot: result => embedded.onSnapshot(result as unknown as DesignResult), + onClose: () => setPartDatumCommand(undefined), + }} />} +
} +
Draft + + + + + + +
+
+
+
Thickness + + + + + + + + +
+
+
+
Body 布尔运算 +
{(["Fuse", "Cut", "Common"] as const).map(operation => )}
+ +
+
+
+
边缘特征 + +
{(["Fillet", "Chamfer"] as DressUpFeature[]).map(type => )}
+ + {dressUpType === "Chamfer" && <> + + {chamferType === "Two distances" && } + {chamferType === "Distance and Angle" && } + {chamferType !== "Equal distance" && } + } + + +
{[...Array.from({ length: baseObject?.edgeCount ?? 0 }, (_, index) => `Edge${index + 1}`), ...Array.from({ length: baseObject?.faceCount ?? 0 }, (_, index) => `Face${index + 1}`)].map(edge => )}
+
+
+
+
+ ; + const gearValues = gearPreset ? { NumberOfTeeth: gearParameters.NumberOfTeeth, SprocketReference: gearPreset } : gearParameters; + const gearRollerInvalid = invalidSprocketRoller(gearKind, gearParameters, gearPreset); + const gearInvalid = gearRollerInvalid || !Number.isInteger(gearParameters.NumberOfTeeth) || Number(gearParameters.NumberOfTeeth) < 3 + || Number(gearParameters.NumberOfTeeth) > 1000 || Object.values(gearValues).some(value => typeof value === "number" && !Number.isFinite(value)); + const gearControls =
Gear / Sprocket + + value.gearReferences)?.gearReferences ?? []} onParameters={setGearParameters} onPreset={setGearPreset} /> +
{["X", "Y", "Z"].map((axis, index) => )}
+ + {gearPlane === "Custom" &&
{["W", "X", "Y", "Z"].map((axis, index) => )}
} + {gearRollerInvalid &&

Roller diameter must be less than pitch.

} +
+
+
; + const currentBody = bodies.find(value => value.name === body); + const tipEligible = Boolean(object && object.body === body && solids.some(value => value.name === selected)); + const tipControls =
Body Tip +

Current Tip: {currentBody?.tip || "None"}

+

Select one solid feature in the model tree for the current Body.

+ +
; + const duplicateCandidates = editable.filter(value => value.type !== "PartDesign::Body"); + const duplicateInvalid = !duplicateObjects.length || duplicateObjects.some(name => !duplicateCandidates.some(value => value.name === name)) + || Boolean(duplicateBody && !bodies.some(value => value.name === duplicateBody)); + const duplicateControls =
Duplicate features + + + + +
; + const moveCandidates = editable.filter(value => value.body === body && value.type !== "PartDesign::Body"); + const moveInvalid = !body || !moveObjects.length || moveObjects.some(name => !moveCandidates.some(value => value.name === name)) + || !bodies.some(value => value.name === moveTargetBody && value.name !== body); + const moveControls =
Move features to another Body + + +

Sketch dependencies move automatically. Features required by features left in the source Body cannot move.

+ +
; + const reorderCandidates = (currentBody?.group ?? []).filter(name => moveCandidates.some(value => value.name === name)); + const reorderInvalid = !body || !reorderObjects.length || reorderObjects.some(name => !reorderCandidates.includes(name)) + || Boolean(reorderAfter && (!reorderCandidates.includes(reorderAfter) || reorderObjects.includes(reorderAfter))); + const reorderControls =
Reorder features within Body + + +

Selected features retain their listed order. Features must remain after their dependencies.

+ +
; + const primitiveControls =
加料 / 减料基本体 + + + {Object.entries(primitiveParameters).map(([field, value]) => { const constraint = primitiveFieldConstraint(primitiveKind, primitiveParameters, field); return ; })} +
{["X", "Y", "Z"].map((axis, index) => )}
+ {primitiveNeedsBase &&

减料需要当前 Body 中已有实体。

} +
+
+
; + if (embedded) return
+ + + {embedded.workbench === "Sketcher" ? sketchControls : <> + {tipControls} + {duplicateControls} + {moveControls} + {reorderControls} +
加料与减料基本体{primitiveControls}
+
Gear and sprocket{gearControls}
+ {featureControls} +
Transformation Features{mirrorControls}{patternControls}{polarControls}{scaledControls}{multiControls}
+
基准对象与关联引用{referenceControls}
+
{ if (!event.currentTarget.open) endReferenceTask(); }}>厚度、布尔与边缘特征{finishingControls}
+ } + +

{busy ? "计算中..." : status}

+
; + return
+
FreeCAD

PartDesign

{active}
+ +
{busy ? "计算中..." : status}
+
+
; +} diff --git a/web/src/partdesign-workspace.css b/web/src/partdesign-workspace.css new file mode 100644 index 00000000..ab8b6ee5 --- /dev/null +++ b/web/src/partdesign-workspace.css @@ -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} diff --git a/web/src/partdesign-workspace.tsx b/web/src/partdesign-workspace.tsx new file mode 100644 index 00000000..c5f2fe10 --- /dev/null +++ b/web/src/partdesign-workspace.tsx @@ -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("#app")!).render(); diff --git a/web/src/project-shell.tsx b/web/src/project-shell.tsx index 03215db7..c6339553 100644 --- a/web/src/project-shell.tsx +++ b/web/src/project-shell.tsx @@ -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 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()); const [partSnapshots, setPartSnapshots] = useState>({}); const [designSnapshots, setDesignSnapshots] = useState>({}); - const [workbenches, setWorkbenches] = useState>(() => initialWorkbench ? { [initialDocumentId]: initialWorkbench } : {}); + const [workbenches, setWorkbenches] = useState>(() => 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(() => { 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(() => 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 } = {}) => { 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 | 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 = {}) => { 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
FCFreeCAD 1.2 Web{active || "Workspace"}
{startVisible && { 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))); - }}> + }}> {csvPanel && } - {workbench === "Spreadsheet" && <> - } - {workbench === "Spreadsheet" && } + {workbench === "Spreadsheet" && 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)))} + />} {workbench === "Part" && }
} {panelSeparator("tree")}

{active || "Workspace"}

{workbench === "Spreadsheet" && (selectedObject?.type === "Spreadsheet::Sheet" ? setReferenceOpen(open => !open)}>参考模型 GLB + {viewCommand && ({ 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))); }} /> } -
+ {/* Spreadsheet has no 3D scene; keeping the empty viewport only pushes the + grid down on narrow screens (UI-GAP-14). */} +
{workbench === "Part" && active && workspaceTask === "sketcher-new-sketch" &&
} - {isExternalWorkbench(workbench) && } + {isExternalWorkbench(workbench) && }
{([["translate", "移动"], ["rotate", "旋转"], ["off", "关闭"]] as const).map(([mode, label]) => (
欧拉角
{["X", "Y", "Z"].map((axis, index) => ( ))}
+ 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) }); }} />))}
- - + +
} @@ -2185,7 +2306,7 @@ function App() { onClick={() => void exportSelectedShape()}> - + @@ -2255,8 +2376,13 @@ function App() { {selectedObject.type === "Part::Box" && <>

Data

{(["Length", "Width", "Height"] as const).map((name, index) => { const expression = (selectedObject.properties.primitiveExpressions as Record | undefined)?.[name]; return ; })} + 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"); }} />; })} } {selectedPrimitiveDefinition && selectedObject.type !== "Part::Box" && <>

Data

@@ -2264,8 +2390,13 @@ function App() { setPrimitiveParameters(previous => ({ ...previous, [field]: Number(event.target.value) }))} - onBlur={() => { if (!importing && selectedObject.properties.NativeName) void createOrEditPrimitive(true); }} />; })} + 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"); }} />; })} } {["Part::Fuse", "Part::Cut", "Part::Common"].includes(selectedObject.type) && <>

Data

@@ -2957,12 +3088,19 @@ function App() { })()} />} {workspaceTask === "position" &&
Placement
{["X", "Y", "Z"].map((axis, index) => )}
+ 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 }); + }} />)}
{["X", "Y", "Z"].map((axisName, index) => )}
+ 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 }); + }} />)} + onChange={event => { const next = Number(event.target.value); setRotationAngle(next); schedulePlacementPreview({ position, axis: rotationAxis, angle: next }); }} /> -