#!/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);