Files
FreeCADWasmDev/tools/parity/audit-web-gui.mjs
2026-11-13 23:37:22 +08:00

92 lines
5.1 KiB
JavaScript

#!/usr/bin/env node
// Baseline Web GUI audit for one workbench: menus/toolbars/docks/status, page
// errors and overflow, compared with desktop-gui-manifest.json.
import fs from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(here, "../..");
const webRoot = path.join(repoRoot, "web");
const require = createRequire(path.join(webRoot, "package.json"));
const { chromium } = require("playwright");
const args = process.argv.slice(2);
const option = (name, fallback) => {
const index = args.indexOf(name);
return index < 0 ? fallback : args[index + 1] ?? fallback;
};
const workbench = option("--workbench", "Part");
const origin = option("--origin", "http://127.0.0.1:5181");
const manifest = JSON.parse(fs.readFileSync(path.join(webRoot, "public/api/desktop-gui-manifest.json"), "utf8"));
const desktop = manifest.workbenches.find(item => item.id === workbench);
if (!desktop) throw new Error(`manifest has no workbench ${workbench}`);
const outDir = path.join(webRoot, "docs/current/desktop-parity-evidence");
fs.mkdirSync(outDir, { recursive: true });
const browser = await chromium.launch({ executablePath: "/usr/bin/google-chrome", headless: true,
args: ["--no-sandbox", "--enable-unsafe-swiftshader", "--use-gl=angle", "--use-angle=swiftshader"] });
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
const errors = []; const failed = [];
page.on("pageerror", error => errors.push(String(error)));
page.on("console", message => { if (message.type() === "error") errors.push(message.text().slice(0, 200)); });
page.on("response", response => { if (response.status() >= 400) failed.push(`${response.status()} ${response.url()}`); });
const url = `${origin}/project.html?workbench=${encodeURIComponent(workbench)}`;
const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: 120000 });
await page.waitForSelector('select[aria-label="Workbench"]', { timeout: 120000 }).catch(() => {});
await page.waitForTimeout(1500);
if (workbench !== "Part") {
await page.locator('nav[aria-label="Application menus"] > details').first().locator(':scope > summary').click();
await page.getByRole("button", { name: "新建 Document", exact: true }).click();
await page.waitForTimeout(1800);
await page.evaluate(() => { for (const details of document.querySelectorAll('nav[aria-label="Application menus"] details[open]')) details.open = false; });
const selector = page.locator('select[aria-label="Workbench"]');
if (await selector.count() && !(await selector.isDisabled())) {
await selector.selectOption(workbench).catch(() => {});
await page.waitForTimeout(1600);
}
}
const metrics = await page.evaluate(() => ({
menus: [...document.querySelectorAll('nav[aria-label="Application menus"] details > summary')]
.map(node => node.textContent.trim()),
toolbarButtons: document.querySelectorAll('[role="toolbar"] button, .part-tool-button, .toolbar-workspace button').length,
docks: [...document.querySelectorAll('aside[aria-label], section[aria-label], [role="region"]')]
.map(node => node.getAttribute("aria-label")).filter(Boolean),
hasTree: Boolean(document.querySelector('.fc-tree, aside[aria-label="Model tree"]')),
hasProperties: Boolean(document.querySelector('aside.properties')),
hasTask: Boolean(document.querySelector('[role="region"]')),
status: document.querySelector('footer [role="status"]')?.textContent?.trim() ?? "",
workbenchValue: document.querySelector('select[aria-label="Workbench"]')?.value ?? "",
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
}));
const expectedMenus = desktop.menus.map(menu => menu.label);
let submenus = [];
if (workbench !== "Part") {
const toggle = page.locator(`summary[aria-label="${workbench} menu"]`).first();
if (await toggle.count()) {
await toggle.click();
for (let attempt = 0; attempt < 12; attempt++) {
await page.waitForTimeout(400);
submenus = await page.locator(".parity-menu-items>details>summary").allTextContents();
if (submenus.length) break;
}
await toggle.click().catch(() => {});
}
}
const missingMenus = expectedMenus.filter(label => !metrics.menus.includes(label) && !submenus.includes(label));
const shot = path.join(outDir, `${workbench}-web.png`);
await page.screenshot({ path: shot, fullPage: false });
const report = {
schema: "freecad-web-desktop-parity/web-gui-audit/v1",
generatedAt: new Date().toISOString(), workbench, url,
desktop: { menus: expectedMenus, toolbars: desktop.toolbars.map(bar => bar.name),
menuCommandCount: desktop.menus.reduce((sum, menu) => sum + menu.items.length, 0) },
web: { ...metrics, submenus }, missingMenus,
status: response?.status(), errors, failed,
ok: response?.status() === 200 && errors.length === 0 && failed.length === 0 && metrics.overflow === 0,
};
fs.writeFileSync(path.join(outDir, `${workbench}-web-audit.json`), `${JSON.stringify(report, null, 2)}\n`);
console.log(JSON.stringify(report));
await browser.close();
process.exitCode = report.ok ? 0 : 1;