#!/usr/bin/env bun // Measures pages against docs/ui-language.md in a real headless browser. For every path and window it // reads the computed look of every control and checks it against the one set of shapes, sizes and // fonts, checks the page's skeleton, then opens each menu and disclosure on the page and checks the // panel keeps the one look and stays in the window. // // Usage: bun scripts/audit/measure.ts BASE SESSION_COOKIE PATHS_FILE OUT_DIR [--shots] [--menus] // PATHS_FILE has one path a line. Results go to OUT_DIR/measure.json; shots to OUT_DIR/shots. import { mkdirSync, readFileSync, writeFileSync, readdirSync, existsSync } from "fs"; import { homedir } from "os"; const [forge, cookie, pathsFile, out] = process.argv.slice(2); const shots = process.argv.includes("--shots"); const menus = process.argv.includes("--menus"); const FLOATING = "details.menu, details.pins-menu, details.ref-select, details.clone, details.corner, details.strip-runs, details.row-menu, details.commit-status, details.reaction-picker"; const paths = readFileSync(pathsFile, "utf8").split("\n").map((l) => l.trim()).filter(Boolean); // AUDIT_WINDOWS=1440x900,390x844 picks the windows, AUDIT_THEME=dark the theme, AUDIT_LANG=tr the language. const windows = (process.env.AUDIT_WINDOWS ?? "1920x1080,2560x1440,390x844").split(",").map((w) => w.split("x").map(Number)); const theme = process.env.AUDIT_THEME ?? "light"; // A port of its own, so several audits can run at once without reading each other's browser. const PORT = Number(process.env.AUDIT_CDP_PORT) || 9400 + Math.floor(Math.random() * 500); // A __Host- cookie cannot live on plain http, so a small proxy adds it. Streams never end and would // starve the browser's connections, so they answer at once. const proxy = Bun.serve({ port: 0, idleTimeout: 60, async fetch(req) { const url = new URL(req.url); if (/\/(stream|events)$/.test(url.pathname)) return new Response(null, { status: 204 }); // AUDIT_CSS=file serves that stylesheet, to compare two stylesheets on the same data. if (process.env.AUDIT_CSS && url.pathname === "/assets/main.css") { return new Response(Bun.file(process.env.AUDIT_CSS), { headers: { "content-type": "text/css" } }); } const headers = new Headers(req.headers); headers.delete("host"); if (cookie !== "-") headers.set("cookie", cookie); if (process.env.AUDIT_LANG) headers.set("accept-language", process.env.AUDIT_LANG); const r = await fetch(forge + url.pathname + url.search, { method: req.method, headers, body: req.body, redirect: "manual" }); const back = new Headers(r.headers); back.delete("content-encoding"); back.delete("content-length"); const location = back.get("location"); if (location?.startsWith(forge)) back.set("location", location.slice(forge.length)); return new Response(r.body, { status: r.status, headers: back }); }, }); const base = `http://127.0.0.1:${proxy.port}`; function chrome(): string { const root = `${homedir()}/.cache/ms-playwright`; const dir = readdirSync(root).find((d) => d.startsWith("chromium_headless_shell")); if (!dir) throw new Error("no headless shell"); const sub = readdirSync(`${root}/${dir}`).find((d) => existsSync(`${root}/${dir}/${d}/chrome-headless-shell`)); return `${root}/${dir}/${sub}/chrome-headless-shell`; } const proc = Bun.spawn( [chrome(), `--remote-debugging-port=${PORT}`, "--no-sandbox", "--disable-gpu", "--hide-scrollbars", `--user-data-dir=${out}/profile`, "about:blank"], { stdout: "ignore", stderr: "ignore" }, ); let target = ""; for (let i = 0; i < 100 && !target; i++) { await Bun.sleep(100); try { const list = (await (await fetch(`http://127.0.0.1:${PORT}/json`)).json()) as { type: string; webSocketDebuggerUrl: string }[]; target = list.find((t) => t.type === "page")?.webSocketDebuggerUrl ?? ""; } catch {} } if (!target) throw new Error("browser did not start"); const ws = new WebSocket(target); await new Promise((r) => (ws.onopen = r)); let id = 0; const waiting = new Map void>(); const events = new Map void>(); ws.onmessage = (e) => { const m = JSON.parse(e.data as string); if (m.id) { waiting.get(m.id)?.(m.result ?? m.error); waiting.delete(m.id); } else if (m.method) { events.get(m.method)?.(); } }; function send(method: string, params: object = {}): Promise { return new Promise((r) => { waiting.set(++id, r); ws.send(JSON.stringify({ id, method, params })); }); } async function js(expression: string): Promise { const r = await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }); return r?.result?.value; } async function go(url: string) { const loaded = new Promise((r) => events.set("Page.loadEventFired", r)); await send("Page.navigate", { url }); await Promise.race([loaded, Bun.sleep(8000)]); await Bun.sleep(150); } async function shot(name: string) { const r = await send("Page.captureScreenshot", { format: "png" }); if (r?.data) await Bun.write(`${out}/shots/${name}.png`, Buffer.from(r.data, "base64")); } // Runs in the page. Everything it reports is a broken rule of docs/ui-language.md. const DESIGN = `(() => { const bad = []; const ALLOWED_FONT = new Set(['11','12','12.5','13','13.5','14','15','17','22','24','26']); const ALLOWED_RADIUS = new Set(['0','2','3','5','6','10','11','12','14','15','16','18','19','20','30','50%','999','9999']); const seen = (e) => { const r = e.getBoundingClientRect(); return r.width > 0 && r.height > 0 && getComputedStyle(e).visibility !== 'hidden'; }; const name = (e) => e.tagName.toLowerCase() + (e.classList.length ? '.' + [...e.classList].join('.') : '') + ' < ' + (e.parentElement.classList[0] || e.parentElement.tagName.toLowerCase()); const num = (v) => String(Math.round(parseFloat(v) * 10) / 10); const px = (e) => { const c = getComputedStyle(e), r = e.getBoundingClientRect(); return { h: Math.round(r.height), r: c.borderTopLeftRadius.endsWith('%') ? c.borderTopLeftRadius : num(c.borderTopLeftRadius), fs: num(c.fontSize), w: c.fontWeight, ff: c.fontFamily, bg: c.backgroundColor, b: parseFloat(c.borderTopWidth) + parseFloat(c.borderLeftWidth) + parseFloat(c.borderRightWidth) + parseFloat(c.borderBottomWidth) }; }; const none = (bg) => bg === 'rgba(0, 0, 0, 0)' || bg === 'transparent'; // Every kind of control has these shapes and no others: height, radius, font size. const CONTROLS = [[38,'19','15'],[32,'15','13'],[32,'15','14'],[32,'16','14'],[30,'12','14'],[34,'12','14'],[28,'14','14'],[36,'18','14']]; const root = document.querySelector('main'); if (!root) return ['no main']; // The page's skeleton. // A live wrapper with display: contents is not a part of the page: its children are. const flat = (e) => [...e.children].flatMap((c) => getComputedStyle(c).display === 'contents' ? flat(c) : [c]); const parts = flat(root); const heads = parts.filter((c) => c.matches('.head')); if (heads.length !== 1 && !root.querySelector(':scope > .auth')) bad.push('page: ' + heads.length + ' heads'); const h1 = [...document.querySelectorAll('h1')].filter((h) => seen(h) && !h.closest('.markdown-body') && !h.classList.contains('sr-only')); if (h1.length !== 1) bad.push('page: ' + h1.length + ' visible h1'); for (const c of parts) { if (!c.matches('.head, .tabs, .sheet, .work, .state, .alert, .strip, .jobs, .diff-section, .auth, script, style, template, dialog, [hidden], svg, .recent-pushes') ) bad.push('page: stray child of main: ' + name(c)); } // Every control, found by what it is and not by its class. const scope = [...document.querySelectorAll('.topbar *, main *')]; for (const e of scope) { if (!seen(e) || e.closest('.markdown-body, pre, .sr-only, svg')) continue; const c = getComputedStyle(e); const p = px(e); const label = name(e); const tag = e.tagName; const isText = tag === 'INPUT' && !['checkbox','radio','color','file','range','hidden'].includes(e.type); const isBtn = tag === 'BUTTON' || (tag === 'INPUT' && ['submit','button'].includes(e.type)) || e.matches('summary.button, a.button, summary.act, a.act'); if (isBtn && !e.closest('.heat-grid, .choice, .swatches, .colour-grid') && !e.matches('.icon-btn, .rail-item, .line, .corner-link, .swatch')) { if (!CONTROLS.some(([h, r, fs]) => p.h === h && p.r === r && p.fs === fs)) bad.push('control shape ' + p.h + '/' + p.r + '/' + p.fs + ': ' + label); } if (isText || tag === 'SELECT') { // One height a place: 32 in a tools row or a list's search, 36 in the top bar, 38 everywhere else. const want = e.closest('.sheet-tools, .sec-tools, .list-find, .find-filter') ? 32 : e.closest('.topbar, .pathbar, .top-search') ? 36 : 38; if (p.h !== want) bad.push('field height ' + p.h + ' (want ' + want + '): ' + label); if (p.b) bad.push('field border: ' + label); if (none(p.bg) && !e.closest('.plain-search, .top-search')) bad.push('field without fill: ' + label); } if (tag === 'TEXTAREA' && p.b) bad.push('field border: ' + label); if (tag === 'TEXTAREA' && p.r !== '12') bad.push('textarea radius ' + p.r + ': ' + label); if (!/figtree/i.test(p.ff) && !/plex/i.test(p.ff) && !e.matches('input[type=checkbox], input[type=radio]')) bad.push('font ' + p.ff.split(',')[0] + ': ' + label); if (e.childNodes.length && [...e.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim())) { if (!ALLOWED_FONT.has(p.fs)) bad.push('font size ' + p.fs + ': ' + label); if (c.textTransform === 'uppercase') bad.push('uppercase: ' + label); if (c.fontStretch !== '100%') bad.push('font stretch ' + c.fontStretch + ': ' + label); } if (!none(p.bg) || p.b) { if (!ALLOWED_RADIUS.has(p.r) && !p.r.endsWith('%')) bad.push('radius ' + p.r + ': ' + label); } const sides = [c.borderTopWidth, c.borderRightWidth, c.borderBottomWidth, c.borderLeftWidth].filter((v) => parseFloat(v) > 0).length; if (sides === 4 && !e.closest('table') && !e.matches('input[type=checkbox], input[type=radio]')) bad.push('box border: ' + label); if (parseFloat(c.borderLeftWidth) >= 2 && sides === 1) bad.push('side stripe: ' + label); if (c.boxShadow !== 'none' && /\\) -?\\d+px -?\\d+px [1-9]\\d*px/.test(c.boxShadow) && !e.matches('.corner-menu, .menu-list, .pop-panel, .ref-menu, .row-menu-panel, .tab-more-list, .strip-list, .palette-box, .decide, .decide-panel, .status-list, .ci-pop')) bad.push('shadow: ' + label); } // A form's submit and its Cancel are one row: neither sits alone as a child of the fields. for (const e of root.querySelectorAll('.fields > a.act, .fields > button.act')) { if (seen(e)) bad.push('act outside its acts row: ' + name(e)); } // Field widths by kind, in a labelled field: a word 280, a sentence or more 560. for (const e of root.querySelectorAll('.field > input[type=text], .field > input[type=email], .field > input[type=password], .field > input[type=url], .field > input:not([type]), .field > textarea')) { if (!seen(e) || e.closest('.sheet-tools, .decide-panel, .review-inline-form')) continue; const w = Math.round(e.getBoundingClientRect().width); const room = Math.round(e.parentElement.getBoundingClientRect().width); const want = e.tagName === 'TEXTAREA' || e.matches('[name=title], [name=summary], [name=description]') ? 560 : 280; if (w !== want && w < room - 4) bad.push('field width ' + w + ' (want ' + want + '): ' + name(e)); } if (document.documentElement.scrollWidth > innerWidth + 1) { const over = [...root.querySelectorAll('*')].find((e) => e.getBoundingClientRect().right > innerWidth + 1 && !e.closest('pre, table, .diff, .log')); bad.push('sideways overflow ' + document.documentElement.scrollWidth + ' at ' + (over ? name(over) : '?')); } // A pane that lost its height: its content is there and nothing of it can be seen. for (const e of root.querySelectorAll('div, section, ul, ol, pre, article')) { const r = e.getBoundingClientRect(); if (r.height >= 4 || r.width < 40 || e.closest('.sr-only, [hidden]') || !e.innerText?.trim()) continue; if (e.children.length === 1 && e.firstElementChild.matches('.sr-only')) continue; if (getComputedStyle(e).display !== 'none') bad.push('collapsed: ' + name(e)); } return [...new Set(bad)]; })()`; // Alignment inside `root`: a form's controls share one edge, a label stands on its control's line, // an actions row is one centred line on the control edge. const ALIGN = `((root) => { const bad = []; const seen = (e) => { const r = e.getBoundingClientRect(); return r.width > 0 && r.height > 0 && getComputedStyle(e).visibility !== 'hidden'; }; const name = (e) => e.tagName.toLowerCase() + (e.classList.length ? '.' + [...e.classList].join('.') : '') + ' < ' + (e.parentElement.classList[0] || e.parentElement.tagName.toLowerCase()); const mid = (r) => r.top + r.height / 2; // The first line box of an element's text, or its box when it has no text. const line = (e) => { const t = [...e.childNodes].find((n) => n.nodeType === 3 && n.textContent.trim()); if (t) { const g = document.createRange(); g.selectNodeContents(t); const rs = g.getClientRects(); if (rs.length) return rs[0]; } return e.getBoundingClientRect(); }; // One line of an actions row: its visible children sharing the first child's line are centred on it. for (const row of root.querySelectorAll('.acts')) { if (!seen(row) || getComputedStyle(row).display !== 'flex' || getComputedStyle(row).flexDirection !== 'row') continue; const kids = [...row.children].filter((k) => seen(k) && !k.matches('.hint, input[type=hidden]')); if (kids.length < 2) continue; const a = kids[0].getBoundingClientRect(); for (const k of kids.slice(1)) { const b = k.getBoundingClientRect(); if (b.top > a.bottom || b.bottom < a.top) continue; // wrapped to another line // A word action is centred by its text, a control by its box. const kb = k.matches('a.act, span.act, button.act:not([class*=pill])') && getComputedStyle(k).backgroundColor === 'rgba(0, 0, 0, 0)' ? line(k) : b; if (Math.abs(mid(kb) - mid(a)) > 2) bad.push('acts row off centre ' + Math.round(mid(kb) - mid(a)) + 'px: ' + name(k)); } } // A filled action is as wide as its words: one stretched across its row reads as a banner. for (const e of root.querySelectorAll('a, button, summary')) { if (!seen(e) || getComputedStyle(e).backgroundColor === 'rgba(0, 0, 0, 0)' || e.closest('.choice, .rail, .tabs, .menu-list, .tab-more-list, .palette-box, .swatches')) continue; const t = line(e), b = e.getBoundingClientRect(); if (t !== b && b.width - t.width > 120 && b.width > 2 * t.width) bad.push('stretched action ' + Math.round(b.width) + 'px for ' + Math.round(t.width) + 'px of words: ' + name(e)); } // Every line of a sheet starts on the sheet's text edge, or clearly away from it: a few pixels in reads as a slip. for (const sheet of root.querySelectorAll('.sheet')) { if (!seen(sheet) || sheet.parentElement.closest('.sheet')) continue; const sc = getComputedStyle(sheet), sr = sheet.getBoundingClientRect(); const edge = sr.left + parseFloat(sc.borderLeftWidth) + parseFloat(sc.paddingLeft); const items = []; const walk = document.createTreeWalker(sheet, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT); for (let n = walk.nextNode(); n && items.length < 2000; n = walk.nextNode()) { const host = n.nodeType === 3 ? n.parentElement : n; if (host.closest('pre, .markdown-body, .sr-only, table, .diff, .log, .tree, svg, [hidden], details:not([open]) > :not(summary)')) continue; let r; const pill = host.closest('button, summary, a, label, .tag, .pill'); if (pill && sheet.contains(pill) && getComputedStyle(pill).backgroundColor !== 'rgba(0, 0, 0, 0)') { if (n !== pill) continue; r = pill.getBoundingClientRect(); } else if (n.nodeType === 3) { if (!n.textContent.trim()) continue; const g = document.createRange(); g.selectNodeContents(n); r = g.getClientRects()[0]; } else if (n.matches('img, input:not([type=hidden]), select, textarea, button, svg')) r = n.getBoundingClientRect(); if (!r || !r.width || !r.height || getComputedStyle(host).visibility === 'hidden') continue; items.push({ r, host }); } const starts = items.filter((a) => !items.some((b) => b !== a && b.r.left < a.r.left - 1 && b.r.top < a.r.bottom - 2 && b.r.bottom > a.r.top + 2)); const count = new Map(); for (const a of starts) { const k = Math.round(a.r.left - edge); count.set(k, (count.get(k) || 0) + 1); } if (!count.size) continue; const main = [...count].sort((x, y) => y[1] - x[1])[0][0]; for (const a of starts) { const off = Math.round(a.r.left - edge) - main; if (Math.abs(off) < 3 || Math.abs(off) > 40) continue; bad.push('line starts ' + off + 'px off the sheet text edge: ' + name(a.host)); } } for (const form of root.querySelectorAll('.fields')) { if (!seen(form) || form.getBoundingClientRect().width < 500) continue; const fields = [...form.querySelectorAll('.field')].filter((f) => seen(f) && f.closest('.fields') === form && getComputedStyle(f).display === 'grid'); const edges = new Map(); for (const f of fields) { const lab = f.querySelector(':scope > label:not(.switch), :scope > .field-label'); const ctl = [...f.children].find((k) => seen(k) && k !== lab && !k.matches('.hint')); if (!ctl) continue; const left = Math.round(ctl.getBoundingClientRect().left); edges.set(left, (edges.get(left) || 0) + 1); if (lab && seen(lab)) { const target = ctl.matches('.checks') ? (ctl.querySelector('label, .switch') || ctl) : ctl; const tb = target.getBoundingClientRect(); // A tall control (a box of text, a choice) is read by its first line, 38 high. const lm = mid(line(lab)), cm = target.matches('input, select, textarea, button, .choice') ? (tb.height > 40 ? tb.top + 19 : mid(tb)) : mid(line(target.querySelector('span') || target)); if (Math.abs(lm - cm) > 3) bad.push('label off its control line ' + Math.round(cm - lm) + 'px: ' + name(lab)); } // A heading standing over a field with an empty label column: the name belongs in that column. const prev = f.previousElementSibling; if (!lab && prev && prev.matches('h2, h3, h4') && seen(prev)) bad.push('group name on its own line over an empty label column: ' + name(prev)); } if (!edges.size) continue; const edge = [...edges].sort((x, y) => y[1] - x[1])[0][0]; for (const [left, n] of edges) if (left !== edge && edges.size > 1) bad.push('control edge ' + left + ' (form edge ' + edge + ', ' + n + ' fields): ' + name(form)); // The actions after the fields: on the control edge, with room above. const acts = form.querySelector(':scope > .acts:last-child') || (form.nextElementSibling?.matches('.acts') ? form.nextElementSibling : null); const first = acts && [...acts.children].find(seen); if (first && fields.length > 1) { const r = first.getBoundingClientRect(); if (Math.abs(Math.round(r.left) - edge) > 1) bad.push('actions off the control edge ' + (Math.round(r.left) - edge) + 'px: ' + name(acts)); } } return bad; })`; // The rules a floating panel must keep, run while it is open. const PANEL = `((root) => { const bad = []; const shaped = (e) => { const c = getComputedStyle(e); return c.position === 'absolute' || c.position === 'fixed'; }; const panel = [...root.querySelectorAll('*')].find((e) => shaped(e) && e.getBoundingClientRect().width > 80 && !e.closest('summary')); if (panel) { const c = getComputedStyle(panel); if (c.borderTopLeftRadius !== '20px') bad.push('panel radius ' + c.borderTopLeftRadius + ': ' + panel.className); if (c.boxShadow === 'none') bad.push('panel without shadow: ' + panel.className); } return bad; })`; // Opens each closed disclosure and popover in turn, checks its panel, shuts it. const OPEN = `(async () => { const bad = []; let opened = 0; const wait = () => new Promise((r) => setTimeout(r, 30)); const all = [...document.querySelectorAll('details:not([open]), [popovertarget]')].filter((e) => e.getClientRects().length || e.tagName === 'DETAILS'); for (const e of all.slice(0, 60)) { const summary = e.tagName === 'DETAILS' ? e.querySelector(':scope > summary') : e; if (!summary || !summary.getClientRects().length || e.parentElement.closest('details:not([open])')) continue; summary.click(); await wait(); opened++; const root = e.tagName === 'DETAILS' ? e : document.querySelector(':popover-open'); if (root) { for (const k of root.querySelectorAll('*')) { const r = k.getBoundingClientRect(); if (!r.width || !r.height || k.closest('pre')) continue; if (r.right > innerWidth + 1 || r.left < -1) { bad.push('open panel leaves the window: ' + (summary.textContent || '').trim().slice(0, 30) + ' at ' + k.tagName + '.' + k.className + ' ' + Math.round(r.left) + '-' + Math.round(r.right)); break; } } bad.push(...${PANEL}(root)); bad.push(...(${PANEL})(root)); bad.push(...(${ALIGN})(root).map((l) => 'open ' + (summary.textContent || '').trim().slice(0, 30) + ': ' + l)); if (document.documentElement.scrollWidth > innerWidth + 1) bad.push('opening makes the page wide: ' + (summary.textContent || '').trim().slice(0, 30)); } if (e.tagName === 'DETAILS') { e.open = false; } else { document.querySelector(':popover-open')?.hidePopover(); } await wait(); } return { opened, bad: [...new Set(bad)] }; })()`; await send("Page.enable"); await send("Runtime.enable"); await send("Network.enable"); await send("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: theme }] }); mkdirSync(`${out}/shots`, { recursive: true }); const report: Record = {}; let openedTotal = 0; for (const path of paths) { for (const [width, height] of windows) { await send("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 1, mobile: false }); await go(base + path); // An account's own theme wins over the system's: the audit asks for the one it measures. if (process.env.AUDIT_THEME) await js(`document.documentElement.setAttribute('data-theme', ${JSON.stringify(theme)})`); const bad: string[] = (await js(DESIGN)) ?? ["page did not answer"]; bad.push(...((await js(`(${ALIGN})(document.querySelector('main') || document.body)`)) ?? [])); const code = await js("document.title"); if (/not found|error/i.test(code ?? "")) bad.push("title: " + code); const name = path.replace(/[^a-z0-9]+/gi, "_").slice(0, 120) + "_" + width + (theme === "dark" ? "_dark" : ""); if (shots) await shot(name); // --menus: one shot per floating panel, open, for review by eye. if (menus) { const count = (await js(`document.querySelectorAll(${JSON.stringify(FLOATING)}).length`)) ?? 0; for (let i = 0; i < Math.min(count, 12); i++) { const ok = await js(`(() => { const d = document.querySelectorAll(${JSON.stringify(FLOATING)})[${i}]; const s = d?.querySelector(':scope > summary'); if (!s || !s.getClientRects().length) return false; s.click(); return true; })()`); if (!ok) continue; await Bun.sleep(80); await shot(`${name}_menu${i}`); await js(`document.querySelectorAll(${JSON.stringify(FLOATING)})[${i}].open = false`); } } const open = await js(OPEN); if (open) { openedTotal += open.opened; bad.push(...open.bad); } if (bad.length) report[`${path} @${width}`] = bad; } } proc.kill(); writeFileSync(`${out}/measure.json`, JSON.stringify(report, null, 1)); // The same problems grouped, worst first, with one page for each. const groups = new Map(); for (const [view, list] of Object.entries(report)) { for (const line of list) { const g = groups.get(line) ?? { n: 0, at: view }; g.n++; groups.set(line, g); } } const sorted = [...groups].sort((a, b) => b[1].n - a[1].n).map(([line, g]) => `${String(g.n).padStart(4)} ${line} (${g.at})`); writeFileSync(`${out}/measure.txt`, sorted.join("\n") + "\n"); console.log(`${paths.length} paths, ${paths.length * windows.length} views, ${openedTotal} panels opened, ${Object.keys(report).length} views with problems`); process.exit(0);