stocks / scripts /responsive-audit.mjs
user
python version
ee446e8
Raw History Blame Contribute Delete
7.37 kB
// scripts/responsive-audit.mjs
// Responsive regression audit: opens every page at desktop/tablet/mobile
// viewports and fails on:
// 1. Horizontal overflow — document wider than the viewport (the classic
// mobile breakage: grids with fixed minmax floors, tables without a
// scroll wrapper). Reports the widest offending elements.
// 2. Touch targets — interactive elements smaller than 28px on mobile.
// 3. Clipping — an element with overflow hidden whose content is wider than
// its box (scrollWidth > clientWidth). That is how a delete control or a
// volume cell disappears on a phone without a horizontal scrollbar.
// Exempt by class, because the clipping is the design: CLIP_EXEMPT.
// Run with: node scripts/responsive-audit.mjs (server on :8080)
// AUDIT_BASE_URL points it at another port, so a one-off run can use a plain
// server instead of the `make dev` watcher (AGENTS.md): the watcher restarts on
// any static/ edit, which drops connections mid-audit.
// Pass a page name to audit just that page: node scripts/responsive-audit.mjs discover
import { chromium } from "playwright";
const BASE = process.env.AUDIT_BASE_URL ?? "http://localhost:8080";
const only = process.argv[2];
// Pages the app actually serves. Retired pages are removed rather than kept as
// a 404: /market-pulse (the session-aware movers page, retired with its route)
// and /levels both answered 404, and a missing document is reported here as a
// console error, so the entry could only ever fail the audit.
const PAGES = [
["level2", "/level2"],
["trades", "/trades"],
["playbook", "/trades?tab=playbook"],
["watchlist", "/chart?panel=watchlist"],
["discover", "/discover"],
["scan", "/scan"],
["analyze", "/analyze"],
["settings", "/settings"],
["risk", "/risk"],
// The At Risk screens live at /at-risk (risk is the calculator). Dilution is the
// widest table of the tabs, so it is the one audited.
["at-risk", "/at-risk?tab=dilution"],
["chart", "/chart"],
["backtest", "/backtest"],
["events", "/events"],
["3ds", "/3ds"],
["dashboard", "/dashboard"],
["research", "/research"],
].filter(([name]) => !only || name === only);
const VIEWPORTS = [
["desktop-1440", 1440, 900],
["laptop-1280", 1280, 800],
["tablet-1024", 1024, 768],
["tablet-768", 768, 1024],
["mobile-390", 390, 844],
["mobile-320", 320, 568],
];
// Elements whose own class says the clipping is intended. Keep this list short
// and add a class only when the element is meant to truncate or scroll itself.
// status-inline the scan toolbar status line truncates with an ellipsis
// filter-textarea the filter textarea scrolls its own content
const CLIP_EXEMPT = ["status-inline", "filter-textarea", "dash-cell--sym", "dash-alert--up", "dash-alert--down", "dash-cell--time", "dash-cell--dim"];
const MOBILE_ONLY = VIEWPORTS.filter(([n]) => n.startsWith("mobile"));
const isMobile = (name) => MOBILE_ONLY.some(([n]) => n === name);
const browser = await chromium.launch();
let totalIssues = 0;
for (const [name, path] of PAGES) {
for (const [vwName, width, height] of VIEWPORTS) {
const ctx = await browser.newContext({ viewport: { width, height } });
const page = await ctx.newPage();
const errors = [];
page.on("console", (m) => m.type() === "error" && errors.push("CONSOLE: " + m.text()));
page.on("pageerror", (e) => errors.push("PAGEERROR: " + e.message));
try {
await page.goto(BASE + path, {
// networkidle never settles on live pages (level2 tape, chart),
// so use domcontentloaded + a fixed settle wait.
waitUntil: "domcontentloaded",
timeout: 15000,
});
} catch (e) {
errors.push("GOTO FAILED: " + e.message);
}
await page.waitForTimeout(3500);
const report = await page.evaluate((clipExempt) => {
const docW = document.documentElement.scrollWidth;
const vw = window.innerWidth;
const over = docW - vw;
const offenders = [];
const tiny = [];
if (over > 1) {
for (const el of document.querySelectorAll("body *")) {
const r = el.getBoundingClientRect();
if (r.right > vw + 2 || r.left < -2) {
offenders.push({
tag: el.tagName.toLowerCase(),
id: el.id || null,
cls: String(el.className || "").slice(0, 60),
right: Math.round(r.right),
width: Math.round(r.width),
});
}
}
offenders.sort((a, b) => b.right - a.right);
}
// Touch targets: only on mobile viewports, interactive only.
// Links inside data tables have content-driven width (a 3-letter
// symbol can't be 28px wide) — judge them by height; buttons,
// inputs and selects must clear both axes.
const isMobileViewport = vw <= 480;
if (isMobileViewport) {
for (const el of document.querySelectorAll("button,a,input,select")) {
const r = el.getBoundingClientRect();
if (r.width <= 0 || r.height <= 0) continue;
const bad =
el.tagName.toLowerCase() === "a"
? r.height < 28
: r.height < 28 || r.width < 28;
if (bad) {
tiny.push({
tag: el.tagName.toLowerCase(),
id: el.id || null,
cls: String(el.className || "").slice(0, 50),
w: Math.round(r.width),
h: Math.round(r.height),
});
}
}
}
// Clipping: overflow hidden + content wider than the box. Inline boxes
// report clientWidth 0 and are not clipped boxes, so they are skipped.
// A 1px tolerance absorbs subpixel rounding.
const clipped = [];
for (const el of document.querySelectorAll("body *")) {
if (getComputedStyle(el).overflowX !== "hidden") continue;
if (el.clientWidth === 0 || el.scrollWidth <= el.clientWidth + 1) continue;
if (clipExempt.some((c) => el.classList.contains(c))) continue;
clipped.push({
tag: el.tagName.toLowerCase(),
id: el.id || null,
cls: String(el.className || "").slice(0, 50),
sw: el.scrollWidth,
cw: el.clientWidth,
});
}
return { over, docW, vw, offenders, tiny, clipped };
}, CLIP_EXEMPT);
const flags = [];
if (report.over > 1) { totalIssues++; flags.push(`OVERFLOW ${report.over}px (doc ${report.docW} vs vw ${report.vw})`); }
if (report.clipped.length) { totalIssues++; flags.push(`CLIPPED ${report.clipped.length}`); }
if (isMobile(vwName) && report.tiny.length > 8) { totalIssues++; flags.push(`TINY-TARGETS ${report.tiny.length}`); }
if (errors.length) { totalIssues += errors.length; flags.push(`ERRORS(${errors.length})`); }
if (!flags.length) continue;
console.log(`\n${name}@${vwName} (${width}x${height}): ${flags.join(", ")}`);
report.offenders.slice(0, 8).forEach((o) =>
console.log(` <${o.tag}${o.id ? "#" + o.id : ""}${o.cls ? "." + o.cls.split(" ").join(".") : ""}> right=${o.right} w=${o.width}`),
);
if (report.tiny.length > 8) {
report.tiny.slice(0, 8).forEach((t) =>
console.log(` TINY <${t.tag}${t.id ? "#" + t.id : ""}.${t.cls}> ${t.w}x${t.h}`),
);
console.log(` ... +${report.tiny.length - 8} more`);
}
report.clipped.slice(0, 8).forEach((c) =>
console.log(` CLIP <${c.tag}${c.id ? "#" + c.id : ""}.${c.cls.split(" ").join(".")}> scroll=${c.sw} client=${c.cw}`),
);
errors.slice(0, 3).forEach((e) => console.log(" " + e));
await ctx.close();
}
}
await browser.close();
console.log(`\n=== TOTAL ISSUES: ${totalIssues} ===`);
process.exit(totalIssues > 0 ? 1 : 0);