forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits
| 1 | #!/usr/bin/env bun |
| 2 | // Measures pages against docs/ui-language.md in a real headless browser. For every path and window it |
| 3 | // reads the computed look of every control and checks it against the one set of shapes, sizes and |
| 4 | // fonts, checks the page's skeleton, then opens each menu and disclosure on the page and checks the |
| 5 | // panel keeps the one look and stays in the window. |
| 6 | // |
| 7 | // Usage: bun scripts/audit/measure.ts BASE SESSION_COOKIE PATHS_FILE OUT_DIR [--shots] [--menus] |
| 8 | // PATHS_FILE has one path a line. Results go to OUT_DIR/measure.json; shots to OUT_DIR/shots. |
| 9 | |
| 10 | import { mkdirSync, readFileSync, writeFileSync, readdirSync, existsSync } from "fs"; |
| 11 | import { homedir } from "os"; |
| 12 | |
| 13 | const [forge, cookie, pathsFile, out] = process.argv.slice(2); |
| 14 | const shots = process.argv.includes("--shots"); |
| 15 | const menus = process.argv.includes("--menus"); |
| 16 | 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"; |
| 17 | const paths = readFileSync(pathsFile, "utf8").split("\n").map((l) => l.trim()).filter(Boolean); |
| 18 | // AUDIT_WINDOWS=1440x900,390x844 picks the windows, AUDIT_THEME=dark the theme, AUDIT_LANG=tr the language. |
| 19 | const windows = (process.env.AUDIT_WINDOWS ?? "1920x1080,2560x1440,390x844").split(",").map((w) => w.split("x").map(Number)); |
| 20 | const theme = process.env.AUDIT_THEME ?? "light"; |
| 21 | // A port of its own, so several audits can run at once without reading each other's browser. |
| 22 | const PORT = Number(process.env.AUDIT_CDP_PORT) || 9400 + Math.floor(Math.random() * 500); |
| 23 | |
| 24 | // A __Host- cookie cannot live on plain http, so a small proxy adds it. Streams never end and would |
| 25 | // starve the browser's connections, so they answer at once. |
| 26 | const proxy = Bun.serve({ |
| 27 | port: 0, |
| 28 | idleTimeout: 60, |
| 29 | async fetch(req) { |
| 30 | const url = new URL(req.url); |
| 31 | if (/\/(stream|events)$/.test(url.pathname)) return new Response(null, { status: 204 }); |
| 32 | // AUDIT_CSS=file serves that stylesheet, to compare two stylesheets on the same data. |
| 33 | if (process.env.AUDIT_CSS && url.pathname === "/assets/main.css") { |
| 34 | return new Response(Bun.file(process.env.AUDIT_CSS), { headers: { "content-type": "text/css" } }); |
| 35 | } |
| 36 | const headers = new Headers(req.headers); |
| 37 | headers.delete("host"); |
| 38 | if (cookie !== "-") headers.set("cookie", cookie); |
| 39 | if (process.env.AUDIT_LANG) headers.set("accept-language", process.env.AUDIT_LANG); |
| 40 | const r = await fetch(forge + url.pathname + url.search, { method: req.method, headers, body: req.body, redirect: "manual" }); |
| 41 | const back = new Headers(r.headers); |
| 42 | back.delete("content-encoding"); |
| 43 | back.delete("content-length"); |
| 44 | const location = back.get("location"); |
| 45 | if (location?.startsWith(forge)) back.set("location", location.slice(forge.length)); |
| 46 | return new Response(r.body, { status: r.status, headers: back }); |
| 47 | }, |
| 48 | }); |
| 49 | const base = `http://127.0.0.1:${proxy.port}`; |
| 50 | |
| 51 | function chrome(): string { |
| 52 | const root = `${homedir()}/.cache/ms-playwright`; |
| 53 | const dir = readdirSync(root).find((d) => d.startsWith("chromium_headless_shell")); |
| 54 | if (!dir) throw new Error("no headless shell"); |
| 55 | const sub = readdirSync(`${root}/${dir}`).find((d) => existsSync(`${root}/${dir}/${d}/chrome-headless-shell`)); |
| 56 | return `${root}/${dir}/${sub}/chrome-headless-shell`; |
| 57 | } |
| 58 | |
| 59 | const proc = Bun.spawn( |
| 60 | [chrome(), `--remote-debugging-port=${PORT}`, "--no-sandbox", "--disable-gpu", "--hide-scrollbars", `--user-data-dir=${out}/profile`, "about:blank"], |
| 61 | { stdout: "ignore", stderr: "ignore" }, |
| 62 | ); |
| 63 | |
| 64 | let target = ""; |
| 65 | for (let i = 0; i < 100 && !target; i++) { |
| 66 | await Bun.sleep(100); |
| 67 | try { |
| 68 | const list = (await (await fetch(`http://127.0.0.1:${PORT}/json`)).json()) as { type: string; webSocketDebuggerUrl: string }[]; |
| 69 | target = list.find((t) => t.type === "page")?.webSocketDebuggerUrl ?? ""; |
| 70 | } catch {} |
| 71 | } |
| 72 | if (!target) throw new Error("browser did not start"); |
| 73 | |
| 74 | const ws = new WebSocket(target); |
| 75 | await new Promise((r) => (ws.onopen = r)); |
| 76 | let id = 0; |
| 77 | const waiting = new Map<number, (v: any) => void>(); |
| 78 | const events = new Map<string, () => void>(); |
| 79 | ws.onmessage = (e) => { |
| 80 | const m = JSON.parse(e.data as string); |
| 81 | if (m.id) { |
| 82 | waiting.get(m.id)?.(m.result ?? m.error); |
| 83 | waiting.delete(m.id); |
| 84 | } else if (m.method) { |
| 85 | events.get(m.method)?.(); |
| 86 | } |
| 87 | }; |
| 88 | function send(method: string, params: object = {}): Promise<any> { |
| 89 | return new Promise((r) => { |
| 90 | waiting.set(++id, r); |
| 91 | ws.send(JSON.stringify({ id, method, params })); |
| 92 | }); |
| 93 | } |
| 94 | async function js(expression: string): Promise<any> { |
| 95 | const r = await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }); |
| 96 | return r?.result?.value; |
| 97 | } |
| 98 | |
| 99 | async function go(url: string) { |
| 100 | const loaded = new Promise<void>((r) => events.set("Page.loadEventFired", r)); |
| 101 | await send("Page.navigate", { url }); |
| 102 | await Promise.race([loaded, Bun.sleep(8000)]); |
| 103 | await Bun.sleep(150); |
| 104 | } |
| 105 | |
| 106 | async function shot(name: string) { |
| 107 | const r = await send("Page.captureScreenshot", { format: "png" }); |
| 108 | if (r?.data) await Bun.write(`${out}/shots/${name}.png`, Buffer.from(r.data, "base64")); |
| 109 | } |
| 110 | |
| 111 | // Runs in the page. Everything it reports is a broken rule of docs/ui-language.md. |
| 112 | const DESIGN = `(() => { |
| 113 | const bad = []; |
| 114 | const ALLOWED_FONT = new Set(['11','12','12.5','13','13.5','14','15','17','22','24','26']); |
| 115 | const ALLOWED_RADIUS = new Set(['0','2','3','5','6','10','11','12','14','15','16','18','19','20','30','50%','999','9999']); |
| 116 | const seen = (e) => { const r = e.getBoundingClientRect(); return r.width > 0 && r.height > 0 && getComputedStyle(e).visibility !== 'hidden'; }; |
| 117 | const name = (e) => e.tagName.toLowerCase() + (e.classList.length ? '.' + [...e.classList].join('.') : '') + ' < ' + (e.parentElement.classList[0] || e.parentElement.tagName.toLowerCase()); |
| 118 | const num = (v) => String(Math.round(parseFloat(v) * 10) / 10); |
| 119 | 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) }; }; |
| 120 | const none = (bg) => bg === 'rgba(0, 0, 0, 0)' || bg === 'transparent'; |
| 121 | // Every kind of control has these shapes and no others: height, radius, font size. |
| 122 | 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']]; |
| 123 | const root = document.querySelector('main'); |
| 124 | if (!root) return ['no main']; |
| 125 | // The page's skeleton. |
| 126 | // A live wrapper with display: contents is not a part of the page: its children are. |
| 127 | const flat = (e) => [...e.children].flatMap((c) => getComputedStyle(c).display === 'contents' ? flat(c) : [c]); |
| 128 | const parts = flat(root); |
| 129 | const heads = parts.filter((c) => c.matches('.head')); |
| 130 | if (heads.length !== 1 && !root.querySelector(':scope > .auth')) bad.push('page: ' + heads.length + ' heads'); |
| 131 | const h1 = [...document.querySelectorAll('h1')].filter((h) => seen(h) && !h.closest('.markdown-body') && !h.classList.contains('sr-only')); |
| 132 | if (h1.length !== 1) bad.push('page: ' + h1.length + ' visible h1'); |
| 133 | for (const c of parts) { |
| 134 | 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)); |
| 135 | } |
| 136 | // Every control, found by what it is and not by its class. |
| 137 | const scope = [...document.querySelectorAll('.topbar *, main *')]; |
| 138 | for (const e of scope) { |
| 139 | if (!seen(e) || e.closest('.markdown-body, pre, .sr-only, svg')) continue; |
| 140 | const c = getComputedStyle(e); |
| 141 | const p = px(e); |
| 142 | const label = name(e); |
| 143 | const tag = e.tagName; |
| 144 | const isText = tag === 'INPUT' && !['checkbox','radio','color','file','range','hidden'].includes(e.type); |
| 145 | const isBtn = tag === 'BUTTON' || (tag === 'INPUT' && ['submit','button'].includes(e.type)) || e.matches('summary.button, a.button, summary.act, a.act'); |
| 146 | if (isBtn && !e.closest('.heat-grid, .choice, .swatches, .colour-grid') && !e.matches('.icon-btn, .rail-item, .line, .corner-link, .swatch')) { |
| 147 | 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); |
| 148 | } |
| 149 | if (isText || tag === 'SELECT') { |
| 150 | // One height a place: 32 in a tools row or a list's search, 36 in the top bar, 38 everywhere else. |
| 151 | const want = e.closest('.sheet-tools, .sec-tools, .list-find, .find-filter') ? 32 : e.closest('.topbar, .pathbar, .top-search') ? 36 : 38; |
| 152 | if (p.h !== want) bad.push('field height ' + p.h + ' (want ' + want + '): ' + label); |
| 153 | if (p.b) bad.push('field border: ' + label); |
| 154 | if (none(p.bg) && !e.closest('.plain-search, .top-search')) bad.push('field without fill: ' + label); |
| 155 | } |
| 156 | if (tag === 'TEXTAREA' && p.b) bad.push('field border: ' + label); |
| 157 | if (tag === 'TEXTAREA' && p.r !== '12') bad.push('textarea radius ' + p.r + ': ' + label); |
| 158 | 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); |
| 159 | if (e.childNodes.length && [...e.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim())) { |
| 160 | if (!ALLOWED_FONT.has(p.fs)) bad.push('font size ' + p.fs + ': ' + label); |
| 161 | if (c.textTransform === 'uppercase') bad.push('uppercase: ' + label); |
| 162 | if (c.fontStretch !== '100%') bad.push('font stretch ' + c.fontStretch + ': ' + label); |
| 163 | } |
| 164 | if (!none(p.bg) || p.b) { |
| 165 | if (!ALLOWED_RADIUS.has(p.r) && !p.r.endsWith('%')) bad.push('radius ' + p.r + ': ' + label); |
| 166 | } |
| 167 | const sides = [c.borderTopWidth, c.borderRightWidth, c.borderBottomWidth, c.borderLeftWidth].filter((v) => parseFloat(v) > 0).length; |
| 168 | if (sides === 4 && !e.closest('table') && !e.matches('input[type=checkbox], input[type=radio]')) bad.push('box border: ' + label); |
| 169 | if (parseFloat(c.borderLeftWidth) >= 2 && sides === 1) bad.push('side stripe: ' + label); |
| 170 | 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); |
| 171 | } |
| 172 | // A form's submit and its Cancel are one row: neither sits alone as a child of the fields. |
| 173 | for (const e of root.querySelectorAll('.fields > a.act, .fields > button.act')) { |
| 174 | if (seen(e)) bad.push('act outside its acts row: ' + name(e)); |
| 175 | } |
| 176 | // Field widths by kind, in a labelled field: a word 280, a sentence or more 560. |
| 177 | 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')) { |
| 178 | if (!seen(e) || e.closest('.sheet-tools, .decide-panel, .review-inline-form')) continue; |
| 179 | const w = Math.round(e.getBoundingClientRect().width); |
| 180 | const room = Math.round(e.parentElement.getBoundingClientRect().width); |
| 181 | const want = e.tagName === 'TEXTAREA' || e.matches('[name=title], [name=summary], [name=description]') ? 560 : 280; |
| 182 | if (w !== want && w < room - 4) bad.push('field width ' + w + ' (want ' + want + '): ' + name(e)); |
| 183 | } |
| 184 | if (document.documentElement.scrollWidth > innerWidth + 1) { |
| 185 | const over = [...root.querySelectorAll('*')].find((e) => e.getBoundingClientRect().right > innerWidth + 1 && !e.closest('pre, table, .diff, .log')); |
| 186 | bad.push('sideways overflow ' + document.documentElement.scrollWidth + ' at ' + (over ? name(over) : '?')); |
| 187 | } |
| 188 | // A pane that lost its height: its content is there and nothing of it can be seen. |
| 189 | for (const e of root.querySelectorAll('div, section, ul, ol, pre, article')) { |
| 190 | const r = e.getBoundingClientRect(); |
| 191 | if (r.height >= 4 || r.width < 40 || e.closest('.sr-only, [hidden]') || !e.innerText?.trim()) continue; |
| 192 | if (e.children.length === 1 && e.firstElementChild.matches('.sr-only')) continue; |
| 193 | if (getComputedStyle(e).display !== 'none') bad.push('collapsed: ' + name(e)); |
| 194 | } |
| 195 | return [...new Set(bad)]; |
| 196 | })()`; |
| 197 | |
| 198 | // Alignment inside `root`: a form's controls share one edge, a label stands on its control's line, |
| 199 | // an actions row is one centred line on the control edge. |
| 200 | const ALIGN = `((root) => { |
| 201 | const bad = []; |
| 202 | const seen = (e) => { const r = e.getBoundingClientRect(); return r.width > 0 && r.height > 0 && getComputedStyle(e).visibility !== 'hidden'; }; |
| 203 | const name = (e) => e.tagName.toLowerCase() + (e.classList.length ? '.' + [...e.classList].join('.') : '') + ' < ' + (e.parentElement.classList[0] || e.parentElement.tagName.toLowerCase()); |
| 204 | const mid = (r) => r.top + r.height / 2; |
| 205 | // The first line box of an element's text, or its box when it has no text. |
| 206 | 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(); }; |
| 207 | // One line of an actions row: its visible children sharing the first child's line are centred on it. |
| 208 | for (const row of root.querySelectorAll('.acts')) { |
| 209 | if (!seen(row) || getComputedStyle(row).display !== 'flex' || getComputedStyle(row).flexDirection !== 'row') continue; |
| 210 | const kids = [...row.children].filter((k) => seen(k) && !k.matches('.hint, input[type=hidden]')); |
| 211 | if (kids.length < 2) continue; |
| 212 | const a = kids[0].getBoundingClientRect(); |
| 213 | for (const k of kids.slice(1)) { |
| 214 | const b = k.getBoundingClientRect(); |
| 215 | if (b.top > a.bottom || b.bottom < a.top) continue; // wrapped to another line |
| 216 | // A word action is centred by its text, a control by its box. |
| 217 | const kb = k.matches('a.act, span.act, button.act:not([class*=pill])') && getComputedStyle(k).backgroundColor === 'rgba(0, 0, 0, 0)' ? line(k) : b; |
| 218 | if (Math.abs(mid(kb) - mid(a)) > 2) bad.push('acts row off centre ' + Math.round(mid(kb) - mid(a)) + 'px: ' + name(k)); |
| 219 | } |
| 220 | } |
| 221 | // A filled action is as wide as its words: one stretched across its row reads as a banner. |
| 222 | for (const e of root.querySelectorAll('a, button, summary')) { |
| 223 | 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; |
| 224 | const t = line(e), b = e.getBoundingClientRect(); |
| 225 | 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)); |
| 226 | } |
| 227 | // 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. |
| 228 | for (const sheet of root.querySelectorAll('.sheet')) { |
| 229 | if (!seen(sheet) || sheet.parentElement.closest('.sheet')) continue; |
| 230 | const sc = getComputedStyle(sheet), sr = sheet.getBoundingClientRect(); |
| 231 | const edge = sr.left + parseFloat(sc.borderLeftWidth) + parseFloat(sc.paddingLeft); |
| 232 | const items = []; |
| 233 | const walk = document.createTreeWalker(sheet, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT); |
| 234 | for (let n = walk.nextNode(); n && items.length < 2000; n = walk.nextNode()) { |
| 235 | const host = n.nodeType === 3 ? n.parentElement : n; |
| 236 | if (host.closest('pre, .markdown-body, .sr-only, table, .diff, .log, .tree, svg, [hidden], details:not([open]) > :not(summary)')) continue; |
| 237 | let r; |
| 238 | const pill = host.closest('button, summary, a, label, .tag, .pill'); |
| 239 | if (pill && sheet.contains(pill) && getComputedStyle(pill).backgroundColor !== 'rgba(0, 0, 0, 0)') { if (n !== pill) continue; r = pill.getBoundingClientRect(); } |
| 240 | else if (n.nodeType === 3) { if (!n.textContent.trim()) continue; const g = document.createRange(); g.selectNodeContents(n); r = g.getClientRects()[0]; } |
| 241 | else if (n.matches('img, input:not([type=hidden]), select, textarea, button, svg')) r = n.getBoundingClientRect(); |
| 242 | if (!r || !r.width || !r.height || getComputedStyle(host).visibility === 'hidden') continue; |
| 243 | items.push({ r, host }); |
| 244 | } |
| 245 | 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)); |
| 246 | const count = new Map(); |
| 247 | for (const a of starts) { const k = Math.round(a.r.left - edge); count.set(k, (count.get(k) || 0) + 1); } |
| 248 | if (!count.size) continue; |
| 249 | const main = [...count].sort((x, y) => y[1] - x[1])[0][0]; |
| 250 | for (const a of starts) { |
| 251 | const off = Math.round(a.r.left - edge) - main; |
| 252 | if (Math.abs(off) < 3 || Math.abs(off) > 40) continue; |
| 253 | bad.push('line starts ' + off + 'px off the sheet text edge: ' + name(a.host)); |
| 254 | } |
| 255 | } |
| 256 | for (const form of root.querySelectorAll('.fields')) { |
| 257 | if (!seen(form) || form.getBoundingClientRect().width < 500) continue; |
| 258 | const fields = [...form.querySelectorAll('.field')].filter((f) => seen(f) && f.closest('.fields') === form && getComputedStyle(f).display === 'grid'); |
| 259 | const edges = new Map(); |
| 260 | for (const f of fields) { |
| 261 | const lab = f.querySelector(':scope > label:not(.switch), :scope > .field-label'); |
| 262 | const ctl = [...f.children].find((k) => seen(k) && k !== lab && !k.matches('.hint')); |
| 263 | if (!ctl) continue; |
| 264 | const left = Math.round(ctl.getBoundingClientRect().left); |
| 265 | edges.set(left, (edges.get(left) || 0) + 1); |
| 266 | if (lab && seen(lab)) { |
| 267 | const target = ctl.matches('.checks') ? (ctl.querySelector('label, .switch') || ctl) : ctl; |
| 268 | const tb = target.getBoundingClientRect(); |
| 269 | // A tall control (a box of text, a choice) is read by its first line, 38 high. |
| 270 | 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)); |
| 271 | if (Math.abs(lm - cm) > 3) bad.push('label off its control line ' + Math.round(cm - lm) + 'px: ' + name(lab)); |
| 272 | } |
| 273 | // A heading standing over a field with an empty label column: the name belongs in that column. |
| 274 | const prev = f.previousElementSibling; |
| 275 | 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)); |
| 276 | } |
| 277 | if (!edges.size) continue; |
| 278 | const edge = [...edges].sort((x, y) => y[1] - x[1])[0][0]; |
| 279 | for (const [left, n] of edges) if (left !== edge && edges.size > 1) bad.push('control edge ' + left + ' (form edge ' + edge + ', ' + n + ' fields): ' + name(form)); |
| 280 | // The actions after the fields: on the control edge, with room above. |
| 281 | const acts = form.querySelector(':scope > .acts:last-child') || (form.nextElementSibling?.matches('.acts') ? form.nextElementSibling : null); |
| 282 | const first = acts && [...acts.children].find(seen); |
| 283 | if (first && fields.length > 1) { |
| 284 | const r = first.getBoundingClientRect(); |
| 285 | if (Math.abs(Math.round(r.left) - edge) > 1) bad.push('actions off the control edge ' + (Math.round(r.left) - edge) + 'px: ' + name(acts)); |
| 286 | } |
| 287 | } |
| 288 | return bad; |
| 289 | })`; |
| 290 | |
| 291 | // The rules a floating panel must keep, run while it is open. |
| 292 | const PANEL = `((root) => { |
| 293 | const bad = []; |
| 294 | const shaped = (e) => { const c = getComputedStyle(e); return c.position === 'absolute' || c.position === 'fixed'; }; |
| 295 | const panel = [...root.querySelectorAll('*')].find((e) => shaped(e) && e.getBoundingClientRect().width > 80 && !e.closest('summary')); |
| 296 | if (panel) { |
| 297 | const c = getComputedStyle(panel); |
| 298 | if (c.borderTopLeftRadius !== '20px') bad.push('panel radius ' + c.borderTopLeftRadius + ': ' + panel.className); |
| 299 | if (c.boxShadow === 'none') bad.push('panel without shadow: ' + panel.className); |
| 300 | } |
| 301 | return bad; |
| 302 | })`; |
| 303 | |
| 304 | // Opens each closed disclosure and popover in turn, checks its panel, shuts it. |
| 305 | const OPEN = `(async () => { |
| 306 | const bad = []; |
| 307 | let opened = 0; |
| 308 | const wait = () => new Promise((r) => setTimeout(r, 30)); |
| 309 | const all = [...document.querySelectorAll('details:not([open]), [popovertarget]')].filter((e) => e.getClientRects().length || e.tagName === 'DETAILS'); |
| 310 | for (const e of all.slice(0, 60)) { |
| 311 | const summary = e.tagName === 'DETAILS' ? e.querySelector(':scope > summary') : e; |
| 312 | if (!summary || !summary.getClientRects().length || e.parentElement.closest('details:not([open])')) continue; |
| 313 | summary.click(); |
| 314 | await wait(); |
| 315 | opened++; |
| 316 | const root = e.tagName === 'DETAILS' ? e : document.querySelector(':popover-open'); |
| 317 | if (root) { |
| 318 | for (const k of root.querySelectorAll('*')) { |
| 319 | const r = k.getBoundingClientRect(); |
| 320 | if (!r.width || !r.height || k.closest('pre')) continue; |
| 321 | 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; } |
| 322 | } |
| 323 | bad.push(...${PANEL}(root)); |
| 324 | bad.push(...(${PANEL})(root)); |
| 325 | bad.push(...(${ALIGN})(root).map((l) => 'open ' + (summary.textContent || '').trim().slice(0, 30) + ': ' + l)); |
| 326 | if (document.documentElement.scrollWidth > innerWidth + 1) bad.push('opening makes the page wide: ' + (summary.textContent || '').trim().slice(0, 30)); |
| 327 | } |
| 328 | if (e.tagName === 'DETAILS') { e.open = false; } else { document.querySelector(':popover-open')?.hidePopover(); } |
| 329 | await wait(); |
| 330 | } |
| 331 | return { opened, bad: [...new Set(bad)] }; |
| 332 | })()`; |
| 333 | |
| 334 | await send("Page.enable"); |
| 335 | await send("Runtime.enable"); |
| 336 | await send("Network.enable"); |
| 337 | await send("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: theme }] }); |
| 338 | mkdirSync(`${out}/shots`, { recursive: true }); |
| 339 | const report: Record<string, string[]> = {}; |
| 340 | let openedTotal = 0; |
| 341 | for (const path of paths) { |
| 342 | for (const [width, height] of windows) { |
| 343 | await send("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 1, mobile: false }); |
| 344 | await go(base + path); |
| 345 | // An account's own theme wins over the system's: the audit asks for the one it measures. |
| 346 | if (process.env.AUDIT_THEME) await js(`document.documentElement.setAttribute('data-theme', ${JSON.stringify(theme)})`); |
| 347 | const bad: string[] = (await js(DESIGN)) ?? ["page did not answer"]; |
| 348 | bad.push(...((await js(`(${ALIGN})(document.querySelector('main') || document.body)`)) ?? [])); |
| 349 | const code = await js("document.title"); |
| 350 | if (/not found|error/i.test(code ?? "")) bad.push("title: " + code); |
| 351 | const name = path.replace(/[^a-z0-9]+/gi, "_").slice(0, 120) + "_" + width + (theme === "dark" ? "_dark" : ""); |
| 352 | if (shots) await shot(name); |
| 353 | // --menus: one shot per floating panel, open, for review by eye. |
| 354 | if (menus) { |
| 355 | const count = (await js(`document.querySelectorAll(${JSON.stringify(FLOATING)}).length`)) ?? 0; |
| 356 | for (let i = 0; i < Math.min(count, 12); i++) { |
| 357 | 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; })()`); |
| 358 | if (!ok) continue; |
| 359 | await Bun.sleep(80); |
| 360 | await shot(`${name}_menu${i}`); |
| 361 | await js(`document.querySelectorAll(${JSON.stringify(FLOATING)})[${i}].open = false`); |
| 362 | } |
| 363 | } |
| 364 | const open = await js(OPEN); |
| 365 | if (open) { |
| 366 | openedTotal += open.opened; |
| 367 | bad.push(...open.bad); |
| 368 | } |
| 369 | if (bad.length) report[`${path} @${width}`] = bad; |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | proc.kill(); |
| 374 | writeFileSync(`${out}/measure.json`, JSON.stringify(report, null, 1)); |
| 375 | // The same problems grouped, worst first, with one page for each. |
| 376 | const groups = new Map<string, { n: number; at: string }>(); |
| 377 | for (const [view, list] of Object.entries(report)) { |
| 378 | for (const line of list) { |
| 379 | const g = groups.get(line) ?? { n: 0, at: view }; |
| 380 | g.n++; |
| 381 | groups.set(line, g); |
| 382 | } |
| 383 | } |
| 384 | const sorted = [...groups].sort((a, b) => b[1].n - a[1].n).map(([line, g]) => `${String(g.n).padStart(4)} ${line} (${g.at})`); |
| 385 | writeFileSync(`${out}/measure.txt`, sorted.join("\n") + "\n"); |
| 386 | console.log(`${paths.length} paths, ${paths.length * windows.length} views, ${openedTotal} panels opened, ${Object.keys(report).length} views with problems`); |
| 387 | process.exit(0); |