1
0
Fork 0
polaris-task-force/tests/audit/mobile-audit.ts
Z8MB1E 61535aba58 test(audit): correct mobile viewport emulation and grid heuristic
The harness was measuring against a viewport Chromium had already widened:
with isMobile true it grows the layout viewport to fit overflowing content,
so scrollWidth > innerWidth could never fire and real overflows were masked.
hasTouch alone gives (pointer: coarse) while keeping the 390px viewport
fixed, which is what surfaced the remaining resources overflow.

- grid class: flag only grids that overflow a non-scrolling container;
  drop the narrow-track rule (it flagged intentional icon columns) and
  skip min-w-max boards, which scroll by design
- structures detail now resolves from game-structures (the page's
  collection), so the previous phantom 404 is gone
- refreshed baseline: overflow, grid and hoverOnly all at zero
2026-10-12 20:17:27 -04:00

486 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Pass 2 Session A - mobile layout audit.
*
* Walks every frontend route at 390x844 against a running dev server and
* classifies issues into pattern classes:
* overflow horizontal scroll / elements crossing the viewport edge
* dialog dialogs/panels taller than the viewport
* grid multi-track grids that are cramped at mobile width
* hoverOnly affordances revealed only via (group-)hover
* hiddenMobile content gated behind md:/lg: breakpoints (invisible on mobile)
* tapTarget interactive elements under 24px (WCAG 2.5.8 violation)
* tapTargetMarginal interactive elements 24-39px (review tier)
*
* Usage: bun run tests/audit/mobile-audit.ts
* Env: AUDIT_BASE_URL (default http://localhost:3000)
* AUDIT_USER / AUDIT_PASS (default dev / Test123)
* E2E_BROWSER_PATH (browser executable override)
*
* Outputs tests/audit/mobile-audit-report.json (regression gate artifact for
* Sessions B-D) and mobile-audit-report.md (human issue matrix).
*/
import { chromium, type BrowserContext, type Page } from "@playwright/test";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
const BASE_URL = process.env.AUDIT_BASE_URL ?? "http://localhost:3000";
const USER = process.env.AUDIT_USER ?? "dev";
const PASS = process.env.AUDIT_PASS ?? "Test123";
const VIEWPORT = { width: 390, height: 844 };
const OUT_DIR = join(__dirname);
// Optional substring filter for targeted re-audits (Sessions B-D). When set,
// reports go to mobile-audit-filtered.{json,md} so the baseline is untouched.
const ROUTE_FILTER = process.env.AUDIT_ROUTE_FILTER ?? "";
let authToken: string | null = null;
type Issue = { kind: string; detail: string; selector?: string; size?: string };
type RouteResult = {
route: string;
url: string;
status: "ok" | "skipped" | "error";
httpStatus?: number;
note?: string;
issues: Issue[];
};
/** Static routes, straight from the filesystem. */
const STATIC_ROUTES = [
"/", "/account", "/awards", "/awards/design", "/awards/review",
"/contributions", "/events", "/helpdesk", "/intelligence",
"/intelligence/campaigns", "/intelligence/factions",
"/intelligence/missions", "/intelligence/missions/calendar",
"/journals", "/locker", "/logistics", "/logistics/banking",
"/logistics/game-vehicles", "/logistics/market", "/logistics/resources",
"/logistics/shipments", "/logistics/supply-boxes", "/logistics/vehicles",
"/map", "/notifications",
"/operations", "/operations/ledger", "/operations/reservations",
"/personnel/contacts", "/personnel/promotions", "/personnel/statistics",
"/projects", "/projects/search", "/roster", "/story",
"/surveys", "/transfers", "/voiceover", "/wiki", "/wiki/new",
"/minigames/blackjack", "/minigames/call-for-fire",
"/minigames/call-for-fire-versus", "/minigames/eod", "/minigames/eod/custom",
"/minigames/flappy", "/minigames/leaderboards", "/minigames/opord",
"/minigames/poker", "/minigames/qualification", "/minigames/radio",
"/minigames/radio/custom",
];
/**
* Dynamic routes: template -> REST collection to resolve a real doc from the
* dev DB, plus the field substituted into the path. `null` collection means
* the route is skipped if no candidate resolves.
*/
const DYNAMIC_ROUTES: { template: string; collection: string | null; field: string; fallback?: string }[] = [
{ template: "/helpdesk/[id]", collection: "tickets", field: "id" },
{ template: "/journals/[id]", collection: "journals", field: "id" },
{ template: "/surveys/[id]", collection: "forms", field: "id" },
{ template: "/profile/[username]", collection: null, field: "", fallback: USER },
{ template: "/operations/[operationId]", collection: "operations", field: "id" },
{ template: "/operations/reservations/[id]", collection: "operation-reservations", field: "id" },
{ template: "/intelligence/factions/[id]", collection: "factions", field: "id" },
{ template: "/intelligence/campaigns/[id]", collection: "campaigns", field: "id" },
{ template: "/intelligence/missions/[id]", collection: "missions", field: "id" },
{ template: "/projects/[key]", collection: "projects", field: "key", fallback: "" },
{ template: "/voiceover/[id]", collection: "voice-scripts", field: "id" },
{ template: "/map/[id]", collection: "maps", field: "id" },
{ template: "/personnel/contacts/[id]", collection: "contacts", field: "id" },
{ template: "/logistics/supply-boxes/[id]", collection: "supply-boxes", field: "id" },
{ template: "/logistics/structures/[id]", collection: "game-structures", field: "id" },
{ template: "/logistics/banking/[id]", collection: "bank-accounts", field: "id" },
{ template: "/logistics/resources/[id]", collection: "resources", field: "id" },
{ template: "/logistics/shipments/[id]", collection: "shipments", field: "id" },
{ template: "/logistics/game-vehicles/[id]", collection: "game-vehicles", field: "id" },
{ template: "/logistics/vehicles/[id]", collection: "vehicles", field: "id" },
{ template: "/minigames/eod/custom/[id]", collection: "custom-minefields", field: "id" },
{ template: "/minigames/radio/custom/[id]", collection: "custom-radio-tests", field: "id" },
];
/** Wiki routes need a slug/category instead of an id. */
const WIKI_ROUTES = [
{ template: "/wiki/[slug]", suffix: "" },
{ template: "/wiki/[slug]", suffix: "/history" },
{ template: "/wiki/[slug]", suffix: "/edit" },
];
async function resolveDoc(collection: string): Promise<Record<string, unknown> | null> {
try {
const res = await fetch(`${BASE_URL}/api/${collection}?limit=1&sort=-createdAt`, {
headers: authToken ? { Cookie: `payload-token=${authToken}` } : {},
});
if (!res.ok) return null;
const body = (await res.json()) as { docs?: Record<string, unknown>[] };
return body.docs?.[0] ?? null;
} catch {
return null;
}
}
/** Runs inside the page; returns raw issue records. */
async function collectIssues(): Promise<Issue[]> {
const issues: Issue[] = [];
const vw = window.innerWidth;
const vh = window.innerHeight;
const path = (el: Element): string => {
const parts: string[] = [el.tagName.toLowerCase()];
if (el.id) parts.push("#" + el.id);
const cls = typeof el.className === "string" ? el.className.split(/\s+/).filter(Boolean).slice(0, 3) : [];
if (cls.length) parts.push("." + cls.join("."));
const parent = el.parentElement;
return (parent ? path(parent).split(" > ").pop() + " > " : "") + parts.join("");
};
// 1. Horizontal overflow
const docW = document.documentElement.scrollWidth;
if (docW > vw + 1) {
issues.push({ kind: "overflow", detail: `document scrollWidth ${docW}px > ${vw}px` });
const offenders: { el: Element; over: number }[] = [];
for (const el of Array.from(document.querySelectorAll("body *"))) {
const rect = el.getBoundingClientRect();
if (rect.width < 8 || rect.height < 2) continue;
const style = getComputedStyle(el);
if (style.position === "fixed") continue;
const over = Math.max(rect.right - vw, -rect.left);
if (over > 4) offenders.push({ el, over });
}
offenders.sort((a, b) => b.over - a.over);
for (const o of offenders.slice(0, 4)) {
issues.push({
kind: "overflow",
detail: `crosses edge by ${Math.round(o.over)}px`,
selector: path(o.el),
});
}
}
// 2. Dialogs taller than viewport
for (const dlg of Array.from(document.querySelectorAll('[role="dialog"],[role="alertdialog"]'))) {
const rect = dlg.getBoundingClientRect();
if (rect.height > vh + 1 || rect.bottom > vh + 1) {
issues.push({
kind: "dialog",
detail: `height ${Math.round(rect.height)}px > viewport ${vh}px`,
selector: path(dlg),
});
}
}
// 3. Grids that overflow a container which cannot scroll. Wide-by-design
// layouts (min-w-max boards) and grids inside scroll containers are
// intentional, and narrow icon tracks are not cramped layouts.
const hasScrollAncestor = (el: Element): boolean => {
let node = el.parentElement;
while (node && node !== document.body) {
if (/(auto|scroll)/.test(getComputedStyle(node).overflowX)) return true;
node = node.parentElement;
}
return false;
};
for (const el of Array.from(document.querySelectorAll("*"))) {
const style = getComputedStyle(el);
if (style.display !== "grid") continue;
const tracks = style.gridTemplateColumns.split(" ").filter(Boolean);
if (tracks.length < 2) continue;
const rect = el.getBoundingClientRect();
if (rect.width < 40) continue;
if (style.minWidth === "max-content" || hasScrollAncestor(el)) continue;
const overflowing = el.scrollWidth > el.clientWidth + 1 || rect.right > vw + 4;
if (overflowing) {
issues.push({
kind: "grid",
detail: `${tracks.length}-track grid overflows its container (${Math.round(rect.width)}px wide)`,
selector: path(el),
});
}
}
// 4. Hover-only affordances (invisible until hover/group-hover)
for (const el of Array.from(document.querySelectorAll('[class*="group-hover:"],[class*="hover:opacity"],[class*="hover:visible"],[class*="hover:block"],[class*="hover:flex"]'))) {
const style = getComputedStyle(el);
const cls: string = typeof el.className === "string" ? el.className : "";
const revealsOpacity = /(?:group-)?hover:opacity-\d/.test(cls) && parseFloat(style.opacity) < 0.05;
const revealsDisplay = /(?:group-)?hover:(block|flex)/.test(cls) && style.display === "none";
if (revealsOpacity || revealsDisplay) {
issues.push({ kind: "hoverOnly", detail: "affordance only visible on hover", selector: path(el) });
}
}
// 5. Content hidden at mobile behind md:/lg: reveal utilities. shadcn's
// Sidebar ships desktop-only scaffolding (peer spacer + fixed container)
// and Tailwind `peer` helpers are styling aids, never user content.
for (const el of Array.from(document.querySelectorAll('[class*="md:block"],[class*="md:flex"],[class*="lg:block"],[class*="lg:flex"],[class*="md:inline"],[class*="lg:inline"]'))) {
const cls: string = typeof el.className === "string" ? el.className : "";
if (!/(?:^|\s)hidden(?=\s|$)/.test(cls)) continue;
if (el.closest(".peer") || el.closest("aside")) continue;
const style = getComputedStyle(el);
if (style.display !== "none") continue;
issues.push({ kind: "hiddenMobile", detail: "hidden on mobile (md:/lg: reveal)", selector: path(el) });
}
// 6. Tap targets: WCAG 2.5.8 floor is 24px; 24-39px is a marginal tier for
// review (shadcn defaults live there). Labels are excluded - their
// associated control is the actual tap target.
const interactive = 'a,button,[role="button"],[role="tab"],input:not([type="hidden"]),select';
for (const el of Array.from(document.querySelectorAll(interactive))) {
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) continue;
const style = getComputedStyle(el);
if (style.visibility === "hidden" || style.opacity === "0") continue;
const minSide = Math.min(rect.width, rect.height);
if (minSide >= 40) continue;
const kind = minSide < 24 ? "tapTarget" : "tapTargetMarginal";
const label = (el.textContent || el.getAttribute("aria-label") || el.getAttribute("title") || "").trim().slice(0, 30);
issues.push({
kind,
detail: `${Math.round(rect.width)}x${Math.round(rect.height)}px${label ? ` "${label}"` : ""}`,
selector: path(el),
});
}
return issues;
}
async function auditRoute(context: BrowserContext, route: string): Promise<RouteResult> {
const url = `${BASE_URL}${route}`;
const page: Page = await context.newPage();
try {
// The realtime SSE stream never finishes and competes for the per-host
// connection cap; it adds nothing to a layout audit.
await page.route("**/api/realtime**", (r) => r.abort());
const res = await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 });
const httpStatus = res?.status();
// Let client components render.
await page.waitForTimeout(2000);
if (httpStatus && httpStatus >= 400) {
return { route, url, status: "skipped", httpStatus, note: `HTTP ${httpStatus}`, issues: [] };
}
const issues = await page.evaluate(collectIssues);
return { route, url, status: "ok", httpStatus, issues };
} catch (err) {
return { route, url, status: "error", note: String(err).slice(0, 200), issues: [] };
} finally {
await page.close();
}
}
async function main() {
// Fail fast if the server dies mid-audit instead of retrying every route.
let consecutiveConnectionFailures = 0;
const serverAlive = async (): Promise<boolean> => {
try {
const res = await fetch(`${BASE_URL}/api/version`, { signal: AbortSignal.timeout(5000) });
return res.ok;
} catch {
return false;
}
};
const browser = await chromium.launch({
executablePath: process.env.E2E_BROWSER_PATH || undefined,
headless: true,
});
const context = await browser.newContext({
viewport: VIEWPORT,
// hasTouch gives (pointer: coarse) so touch-only affordances are judged as
// a phone user sees them. isMobile must stay FALSE: it makes Chromium
// widen the layout viewport to fit overflowing content, which hides the
// very overflows this audit exists to catch (innerWidth silently becomes
// the content width, so scrollWidth > innerWidth never fires).
hasTouch: true,
isMobile: false,
deviceScaleFactor: 2,
});
// Authenticate via REST so gated routes render the app shell instead of the
// landing page. Playwright's request context is flaky under Bun, so use the
// global fetch and inject the resulting cookie into the browser context.
const login = await fetch(`${BASE_URL}/api/users/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: USER, password: PASS }),
});
if (!login.ok) {
console.error(`Login failed (${login.status}). Is the dev server up at ${BASE_URL}?`);
await browser.close();
process.exit(1);
}
const loginBody = (await login.json()) as { token?: string };
if (!loginBody.token) {
console.error("Login response had no token; cannot authenticate the audit context.");
await browser.close();
process.exit(1);
}
authToken = loginBody.token;
await context.addCookies([{ name: "payload-token", value: authToken, url: BASE_URL }]);
const routes: string[] = [...STATIC_ROUTES];
const results: RouteResult[] = [];
for (const dyn of DYNAMIC_ROUTES) {
let value = dyn.fallback ?? null;
if (!value && dyn.collection) {
const doc = await resolveDoc(dyn.collection);
if (doc) {
const raw = (doc as Record<string, unknown>)[dyn.field] ?? doc.id;
if (raw != null) value = String(raw);
}
}
if (!value) {
// Navigating to the literal bracket URL would render a bogus page;
// record an explicit skip instead.
results.push({
route: dyn.template,
url: "-",
status: "skipped",
note: dyn.collection ? `no resolvable doc in dev DB (${dyn.collection})` : "unresolved",
issues: [],
});
continue;
}
routes.push(dyn.template.replace(/\[[^\]]+\]/, value));
}
const wikiDoc = await resolveDoc("wiki-pages");
for (const w of WIKI_ROUTES) {
const slug = wikiDoc?.slug ? String(wikiDoc.slug) : null;
if (!slug) {
results.push({
route: w.template + w.suffix,
url: "-",
status: "skipped",
note: "no wiki page in dev DB",
issues: [],
});
continue;
}
routes.push(w.template.replace("[slug]", slug) + w.suffix);
}
const category = wikiDoc?.category ? String((wikiDoc.category as { category?: string }).category ?? wikiDoc.category) : "general";
routes.push(`/wiki/category/${encodeURIComponent(category || "general")}`);
console.log(`Auditing ${routes.length} routes at ${VIEWPORT.width}x${VIEWPORT.height} against ${BASE_URL}`);
const auditedRoutes = ROUTE_FILTER ? routes.filter((r) => r.includes(ROUTE_FILTER)) : routes;
if (ROUTE_FILTER) {
// Targeted run: drop pre-seeded skips that did not match the filter.
results.length = 0;
}
if (ROUTE_FILTER) console.log(`Filter "${ROUTE_FILTER}" matched ${auditedRoutes.length} route(s)`);
for (const route of auditedRoutes) {
let result = await auditRoute(context, route);
// Cold-compile can transiently 5xx or stall on first visit; retry once.
if (result.status === "skipped" && (result.httpStatus === 500 || result.httpStatus === 503)) {
console.log(` ~ ${route} returned ${result.httpStatus}, retrying once`);
result = await auditRoute(context, route);
} else if (result.status === "error") {
console.log(` ~ ${route} errored (${(result.note ?? "").slice(0, 60)}), retrying once`);
result = await auditRoute(context, route);
}
if (result.status === "error" && /CONNECTION_REFUSED|CONNECTION_RESET|ECONNREFUSED/.test(result.note ?? "")) {
consecutiveConnectionFailures += 1;
if (consecutiveConnectionFailures >= 2 && !(await serverAlive())) {
console.error("\nDev server stopped responding mid-audit. Restart it and re-run; results are incomplete.");
await browser.close();
process.exit(1);
}
} else {
consecutiveConnectionFailures = 0;
}
const counts = result.issues.reduce<Record<string, number>>((acc, i) => {
acc[i.kind] = (acc[i.kind] ?? 0) + 1;
return acc;
}, {});
console.log(
`${result.status === "ok" ? "✓" : result.status === "skipped" ? "–" : "✗"} ${route} [${result.status}]${result.note ? ` (${result.note})` : ""} ${Object.entries(counts).map(([k, v]) => `${k}:${v}`).join(" ")}`,
);
results.push(result);
}
// Dedupe identical issues per route (same kind+selector repeats across children).
for (const r of results) {
const seen = new Set<string>();
r.issues = r.issues.filter((i) => {
const key = `${i.kind}|${i.selector ?? ""}|${i.detail}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
const byKind: Record<string, { route: string; issue: Issue }[]> = {};
for (const r of results) {
for (const issue of r.issues) {
(byKind[issue.kind] ??= []).push({ route: r.route, issue });
}
}
const summary = Object.fromEntries(
Object.entries(byKind).map(([kind, list]) => [kind, { routes: new Set(list.map((l) => l.route)).size, findings: list.length }]),
);
const report = {
generatedAt: new Date().toISOString(),
baseUrl: BASE_URL,
viewport: VIEWPORT,
routesAudited: results.length,
routesOk: results.filter((r) => r.status === "ok").length,
summary,
results,
};
const suffix = ROUTE_FILTER ? "filtered" : "report";
writeFileSync(join(OUT_DIR, `mobile-audit-${suffix}.json`), JSON.stringify(report, null, 2));
let md = `# Mobile audit (${VIEWPORT.width}x${VIEWPORT.height}) - ${new Date().toISOString()}\n\n`;
md += `Base: ${BASE_URL} | routes audited: ${results.length} (ok: ${report.routesOk})\n\n`;
md += `| Pattern class | Routes affected | Findings |\n|---|---|---|\n`;
for (const [kind, s] of Object.entries(summary)) md += `| ${kind} | ${s.routes} | ${s.findings} |\n`;
// Cross-route clustering: same selector shape recurring across routes is
// one fixable pattern, not N findings. Sessions B-D work per cluster.
const signature = (selector?: string): string => {
if (!selector) return "(document)";
const last = selector.split(" > ").pop() ?? selector;
return last.replace(/#[a-zA-Z0-9_-]+/g, "").slice(0, 60);
};
for (const [kind, list] of Object.entries(byKind)) {
const clusters = new Map<string, { count: number; routes: Set<string>; example: string }>();
for (const item of list) {
const key = signature(item.issue.selector);
const c = clusters.get(key) ?? { count: 0, routes: new Set<string>(), example: item.issue.detail };
c.count += 1;
c.routes.add(item.route);
clusters.set(key, c);
}
const sorted = [...clusters.entries()].sort((a, b) => b[1].routes.size - a[1].routes.size);
md += `\n## ${kind}: pattern clusters\n\n| Selector shape | Findings | Routes | Example |\n|---|---|---|---|\n`;
for (const [sig, c] of sorted.slice(0, 12)) {
md += `| \`${sig}\` | ${c.count} | ${c.routes.size} | ${c.example.slice(0, 50)} |\n`;
}
}
md += `\n---\n\n# Per-route detail\n`;
for (const [kind, list] of Object.entries(byKind)) {
md += `\n## ${kind}\n\n`;
const byRoute = new Map<string, Issue[]>();
for (const item of list) {
const arr = byRoute.get(item.route) ?? [];
arr.push(item.issue);
byRoute.set(item.route, arr);
}
for (const [route, issues] of byRoute) {
md += `### ${route}\n`;
for (const i of issues.slice(0, 8)) md += `- ${i.detail}${i.selector ? ` \`${i.selector}\`` : ""}\n`;
if (issues.length > 8) md += `- ...and ${issues.length - 8} more\n`;
md += "\n";
}
}
mkdirSync(dirname(join(OUT_DIR, `mobile-audit-${suffix}.md`)), { recursive: true });
writeFileSync(join(OUT_DIR, `mobile-audit-${suffix}.md`), md);
console.log(`\nSummary: ${JSON.stringify(summary)}`);
console.log(`Wrote tests/audit/mobile-audit-${suffix}.json and .md`);
await browser.close();
}
main().catch((err) => {
console.error(err);
process.exit(1);
});