// 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 }; }); }, }, ];