diff --git a/docs/mobile-check.md b/docs/mobile-check.md new file mode 100644 index 0000000..097ea30 --- /dev/null +++ b/docs/mobile-check.md @@ -0,0 +1,60 @@ +# Mobile check (developer tool) + +`scripts/mobile-check.mjs` loads the site under **true device emulation** and fails when a page has a mobile +defect. It is a developer tool: it is not part of the build and nothing in CI runs it. + +## Why not `chrome --headless --window-size=390,844` + +Headless Chrome will not go narrower than about 500px. With `--window-size=390,844` it lays the page out at +about 500px and crops the screenshot, which fakes a cut-off. The script instead drives Chrome through +[puppeteer-core](https://pptr.dev) with `Emulation.setDeviceMetricsOverride` (real layout width), a mobile user +agent, touch, and a device pixel ratio of 2 or 3. It uses your installed Google Chrome; nothing is downloaded. + +## Run it + +```bash +npm install # puppeteer-core is a devDependency; axe-core already was +npm run build +find dist functions lib src -name '._*' -delete # macOS sidecar files break wrangler on external drives +npx wrangler pages dev dist --port 8799 --kv CLAIMS & # run it directly; the preview launcher hangs +npm run mobile-check # all pages x all devices, light/dark/warm axe at 375 +``` + +Useful options: + +```bash +npm run mobile-check -- --pages /,/the-81 --devices iphone-se-1,iphone-se,phone-large +npm run mobile-check -- --axe-all # axe at every device, not just 375 +npm run mobile-check -- --no-axe -v # fast; -v also prints warnings +npm run mobile-check -- --shots /tmp/shots # JPEG screenshots, sliced every 1400px +npm run mobile-check -- --json out.json # raw measurements +npm run mobile-check -- --no-fail # report only (exit code 0) +CHROME_PATH=/path/to/chrome npm run mobile-check +``` + +Devices (`--devices`): `iphone-se-1` 320x568, `android-s` 360x800, `iphone-se` 375x667, `iphone-14` 390x844, +`phone-large` 430x932, `landscape` 844x390, `tablet` 768x1024. Default is all seven. + +## What fails the run (exit code 1) + +| Check | Rule | +|---|---| +| Horizontal overflow | `scrollWidth` of the page greater than the viewport, measured with the `overflow-x:hidden` safety net on `html, body` **lifted**, plus a list of the elements that pass the edge outside an intentional scroller | +| Tap targets | any link, button, field, summary or tab smaller than 44x44 CSS px. Inline links inside running text are listed as warnings (WCAG 2.2 exempts them) | +| Text fields | font size under 16px (iOS Safari zooms the page on focus) | +| Dock bar | its controls under 44px, or the bar covering the last lines of the page | +| axe | any violation in light, dark or warm (at 375; `--axe-all` for every device) | +| Console | any console error or page error (a CSP refusal shows up here) | + +Warnings (printed with `-v`, never fail): content clipped by `overflow:hidden`, horizontal scrollers that hide +content, text under 12px, inline links under 44px, a viewport meta without `viewport-fit=cover`. + +Reader pages are loaded in a fresh browser context (signed out, so the gate is what you see). `/read/NN/full` +signs a test address (`mobile-check@example.test`) into the local KV, so run it against `wrangler pages dev`, +never against production. + +## What it cannot tell you + +Headless Chrome is not iOS Safari. The script cannot see the dynamic toolbar (`100vh` vs `100dvh`), +`env(safe-area-inset-*)` (always 0 here), iOS-specific `position:sticky`, mask or backdrop behaviour, pinch-zoom, +or what a thumb actually reaches. See the checklist at the end of `drafts/mobile/AUDIT.md`. diff --git a/drafts/mobile/AUDIT.md b/drafts/mobile/AUDIT.md new file mode 100644 index 0000000..5dae4a8 --- /dev/null +++ b/drafts/mobile/AUDIT.md @@ -0,0 +1,207 @@ +# Knowware mobile audit + +Baseline: `origin/main` @ `d61b634`, built with `astro build`, served by `wrangler pages dev`. +Measured **2026-10-17** under true device emulation (puppeteer-core driving the system Chrome through +`Emulation.setDeviceMetricsOverride` + mobile user agent + touch; no cropped desktop window). +Tool: [`scripts/mobile-check.mjs`](../../scripts/mobile-check.mjs) (see [docs/mobile-check.md](../../docs/mobile-check.md)). + +| Device | Size (CSS px) | DPR | +|---|---|---| +| iPhone SE (1st gen) | 320×568 | 2 | +| Small Android | 360×800 | 3 | +| iPhone SE (2nd/3rd gen) | 375×667 | 2 | +| iPhone 14 | 390×844 | 3 | +| Large phone | 430×932 | 3 | +| Landscape phone | 844×390 | 3 | +| Tablet | 768×1024 | 2 | + +20 pages × 7 devices = 140 runs. Reader pages (`/read/NN`, `/read/x`) were loaded **signed out** (fresh browser +context) so the gate is what the reader sees; `/read/01/full` was loaded after a test sign-up against local KV. +Overflow was measured with the `overflow-x:hidden` safety net on `html, body` lifted, so hidden overflow is +not mistaken for none. Axe-core 4.14 in light, dark and warm at 375. *Correction:* the first baseline run +reported 40 dark/warm colour-contrast violations; they were an artefact of running axe while the 0.7s theme +transition was still animating colours. Re-measured with transitions off (320 and 375, 11 pages): **zero axe +violations on `main`**, so there is no contrast fix to make and none is claimed. + +## Verdict in one paragraph + +The site reflows better than the report suggested: body copy, `/method`, `/definition`, `/stories`, `/order`, +`/rules`, `/colophon`, the dossier reading order and the cold-open box (with its asterisk footnote) are all +single-column and readable at 320. What is genuinely broken is concentrated in a few places: **the nav** +(26px-wide tap targets on phones; seven tabs plus the theme button measure 868px, so tablets and landscape +phones lose the last tab *and the theme button* behind an invisible scroll), **the home wordmark** (clipped, and +the only page-level horizontal overflow on the site), **The 81** (a 9-column ELEMENTS grid you must swipe, and a +GRAPH that is 81 overlapping labels in 343px with hover-only interaction), **/read/NN** (tier badges overflow +at 320/360, quote boxes squeezed into two-thirds of the screen, a causal-diagram SVG whose labels render at +about 7px), **/agents** (two tables cropped to half their width), and **everywhere** a long tail of 41px buttons, +41–42px inputs, a 14px text field that makes iOS zoom on focus, 11px mono labels, and dark/warm contrast +failures. Page weight is not a problem (three JetBrains Mono weights = 64 KB of woff2; the largest page HTML is +`/the-81` at 134 KB; no photographic images on pages). + +## Measurements + +**Before** (`main` @ `d61b634`, 20 pages per width; axe row is the corrected figure, see above): + +| Check | 320 | 360 | 375 | 390 | 430 | 844 (land.) | 768 (tab.) | +|---|---|---|---|---|---|---|---| +| Pages with horizontal overflow | 2 / 20 | 2 / 20 | 1 / 20 | 1 / 20 | 0 / 20 | 0 / 20 | 0 / 20 | +| Tap targets under 44px (non-inline, summed over pages) | 251 | 255 | 255 | 255 | 259 | 98 | 98 | +| ...of which in nav/footer/dock | 180 | 180 | 180 | 180 | 181 | 29 | 29 | +| Text nodes under 12px (summed) | 772 | 772 | 772 | 772 | 760 | 860 | 860 | +| Pages failing any check except axe | 20 / 20 | 20 / 20 | 20 / 20 | 20 / 20 | 20 / 20 | 20 / 20 | 20 / 20 | +| axe violations (rules, all themes) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | + +**After** (all fix PRs merged into one scratch branch, same 140 runs): see [Results after the fixes](#results-after-the-fixes). + +Nav row width: **868px** (`scrollWidth` of `.kw-nav-shell`) vs 768 / 844 available, so `07 Agents` and the theme button +were clipped at 768 and 844. At 320–430 every tab was **26×51px**, the theme button 40×51px. + +Tap targets under 44px at 375 (non-inline, unique): + +| Element | Size | Where (all fixed, see the issue table) | +|---|---|---| +| `.kw-nav-tab` ×7 | 26×51 | every page | +| `#kw-theme-btn` | 40×51 | every page | +| `.kw-btn` (all variants) | 41px tall | home, definition, stories, story pages, dossier, read gate, 404, contribute, order | +| `.field-input` / gate input | 41–42px tall | contribute, read gate, order | +| `.kw-spine-bar` ×9 | 33px wide | home | +| `.kw-spine-read-btn` | 134×28 | home | +| `#kw-motion-btn` (Pause motion) | 120×35 | home | +| home inline links "What is knowware? →" | 125×16, 145×16 | home | +| `.cast-vtab` ×3 (CAST/ELEMENTS/GRAPH) | 32px tall | /the-81 | +| `.dos-nav-btn` | 32×32 | dossier | +| `.dos-back-btn` | 133×28 | dossier | +| `.dos-cta` ×2 | 38px tall | dossier | +| `.chapter-nav-link` | 34px tall | /read/NN | +| `.kw-full-nav-link--next` | 39px tall | /read/NN/full | +| `.kw-foot-email` | 156×18 | every page | +| `#kw-dock-cta` | 129×30 | every page (after 240px scroll) | + +Text under 12px (text nodes at 375): home 95, /the-81 229, dossier 36–42, /read 31, /read/01 38, /method 43, /stories 36, /contribute 21, others 12–23. Almost all are +11px JetBrains Mono uppercase labels, badges and captions. + +Page weight: JetBrains Mono 400/500/600 woff2 = 21.2 + 21.8 + 21.9 KB; CSS 23 KB (Base) + per-page ≤ 7 KB; largest JS +9 KB (story motion). Largest document: `/the-81` 134 KB (81 rows twice: list + grid). No image heavier than the 176 KB +`assets/00-blanche-slate.png`, which no page loads. Nothing to fix for slow connections beyond possibly dropping the +600 weight. + +## Issue table + +Severity: **High** = content hidden, clipped or unusable; **Med** = usability / WCAG target / zoom; **Low** = polish. +"Fix PR" links the pull request that fixes the row. Nothing is merged: each PR is independent and branched off `main`. + +| # | Page | Widths | What is wrong | Sev | Evidence | Fix PR | +|---|---|---|---|---|---|---| +| G1 | all | 320–430 | Nav shows seven numbers only (no labels) as 26×51px tap targets; theme button 40px | High | [nav](shots/audit/home-hero-375.jpg) | [#32](https://github.com/fromknowware/knowware-now/pull/32) | +| G2 | all | 768, 844 | Nav row is 868px in a `height:52px; overflow-x:auto` bar: `07 Agents` and the theme button are hidden behind a scroll with no affordance | High | [768](shots/audit/nav-tablet-768.jpg) [844](shots/audit/nav-landscape-844.jpg) | [#32](https://github.com/fromknowware/knowware-now/pull/32) | +| G3 | all | all | Dock bar: no safe-area padding (sits on the iPhone home indicator and the landscape notch), CTA 30px tall, 11px type, cannot be dismissed | Med | — | [#32](https://github.com/fromknowware/knowware-now/pull/32) | +| G4 | all | all | Viewport meta lacks `viewport-fit=cover`, so `env(safe-area-inset-*)` is always 0 | Med | — | [#32](https://github.com/fromknowware/knowware-now/pull/32) | +| G5 | all | all | Footer email link 156×18; colophon strip 11px; dock reserve hard-coded 48px | Med | — | [#32](https://github.com/fromknowware/knowware-now/pull/32) | +| G6 | all | all | No `text-size-adjust`: iOS inflates fonts on rotation | Low | — | [#32](https://github.com/fromknowware/knowware-now/pull/32) | +| G7 | `/the-81`, `/voices/NN` | all | `position:sticky; top:52px` on the cast chapter header and the dossier top bar, but the nav is **not** sticky: a 52px hole opens above them and list rows scroll visibly through it | Med | [sticky](shots/audit/the81-sticky-375.jpg) | [#35](https://github.com/fromknowware/knowware-now/pull/35), [#36](https://github.com/fromknowware/knowware-now/pull/36) | +| G8 | all | all | `.kw-btn` 41px, text fields 41–42px tall | Med | — | [#38](https://github.com/fromknowware/knowware-now/pull/38) | +| G9 | all | all | ~~Dark/warm colour contrast~~ **withdrawn**: first reported by axe mid-transition; with transitions off there are no violations and every token pair computes ≥ 4.5:1 | — | — | none needed | +| G10 | all | all | 11px mono labels, badges and captions (see measurements) | Low | — | [#42](https://github.com/fromknowware/knowware-now/pull/42) (+ area PRs) | +| H1 | `/` | 320–390 | Hero wordmark `KNOWWARE` is `clamp(64px,15vw,…)`: 64px minimum makes the text 392px wide in a 288–358px box; the last letter is clipped and the page overflows by 17–72px. Together with R1 this is the only page-level horizontal overflow on the site | High | [hero](shots/audit/home-hero-375.jpg) | [#34](https://github.com/fromknowware/knowware-now/pull/34) | +| H2 | `/` | all | Marquee strip: items cut mid-word is intentional, but the **Pause motion** button (120×35) sits inside the clipped strip, on the right edge | Med | [hero](shots/audit/home-hero-375.jpg) | [#34](https://github.com/fromknowware/knowware-now/pull/34) | +| H3 | `/` | all | Spine bar chart: nine 33px-wide link targets; rotated labels truncated ("The Coordina…") with no full title | Med | — | [#34](https://github.com/fromknowware/knowware-now/pull/34) | +| H4 | `/` | all | Home buttons 41px; inline links "What is knowware? →" 16px tall; "Read manuscript" 28px | Med | — | [#34](https://github.com/fromknowware/knowware-now/pull/34) | +| T1 | `/the-81` | all | CAST / ELEMENTS / GRAPH view tabs 32px tall, 11px type | Med | — | [#35](https://github.com/fromknowware/knowware-now/pull/35) | +| T2 | `/the-81` | 320–430 | Legend is nine items plus stray "·" separators wrapping to 4–5 lines before the list starts | Med | — | [#35](https://github.com/fromknowware/knowware-now/pull/35) | +| T3 | `/the-81` | ≤900 | ELEMENTS: nine fixed 130px columns; about 2.3 visible at 375, swipe sideways, chapter headers detach, no affordance | High | [elements](shots/audit/the81-elements-375.jpg) | [#35](https://github.com/fromknowware/knowware-now/pull/35) | +| T4 | `/the-81` | ≤900 | GRAPH: 81 nodes with labels on a 343px canvas, overlapping text, hover-only affordances, tiny hit radius; the 280px sidebar stacks below with its own 260px scroller (nested scroll) | High | [graph](shots/audit/the81-graph-375.jpg) | [#35](https://github.com/fromknowware/knowware-now/pull/35) | +| D1 | `/voices/NN` | all | Breadcrumb "DOSSIER · №01 OF 81 · …" is clipped by `overflow:hidden`; prev/next arrow 32×32; "Back to The 81" 133×28; CTAs 38px | Med | [dossier](shots/audit/dossier-375.jpg) | [#36](https://github.com/fromknowware/knowware-now/pull/36) | +| D2 | `/voices/NN` | all | Contrast (dark/warm) `.dos-alias`, `.dos-section-hd` count; 11px labels | Low | — | [#36](https://github.com/fromknowware/knowware-now/pull/36) | +| R1 | `/read/NN` (nine voices) | 320, 360 | Tier badge ("PRACTITIONER") passes the right edge: page is 367px wide in a 320/360 viewport; quote box is squeezed into about 65% of the width by the 40px number gutter | High | [cards](shots/audit/read01-cards-320.jpg) | [#37](https://github.com/fromknowware/knowware-now/pull/37) | +| R2 | `/read/NN` | all | Causal-diagram SVG scales to the viewport: node labels render at about 7px and cannot be read at 375 | High | — | [#37](https://github.com/fromknowware/knowware-now/pull/37) | +| R3 | `/read/NN`, `/read/x` | all | Gate: input 41px, button 41px, chapter-nav link 34px, 11px labels | Med | [gate](shots/audit/read-gate-375.jpg) | [#37](https://github.com/fromknowware/knowware-now/pull/37) | +| R4 | `/read`, `/read/NN/full` | all | 11px chapter titles/numbers; next-chapter link 39px | Low | — | [#37](https://github.com/fromknowware/knowware-now/pull/37) | +| F1 | `/contribute` | all | Text fields are **14px**: iOS Safari zooms the page on focus (and does not zoom back); fields 42px | High | [form](shots/audit/contribute-375.jpg) | [#38](https://github.com/fromknowware/knowware-now/pull/38) | +| F2 | `/order`, `/order/listed` | all | Waiting-list button/inputs 41px, 11px legal line | Med | — | [#38](https://github.com/fromknowware/knowware-now/pull/38) | +| S1 | `/stories`, `/stories/` | all | Buttons 41px (share, atom feed), 8–16 inline links, 11px badges/captions. Canvases: diagram animates continuously — check cost on slow phones | Med | — | stories | +| A1 | `/agents` | all | Two tables (`.ag-table-wrap`) are 520px wide inside 286–341px: second column cut mid-word with no scroll cue ("Knowware: Systems o…", "NOT OP…") | High | [agents](shots/audit/agents-table-375.jpg) | [#41](https://github.com/fromknowware/knowware-now/pull/41) | +| A2 | `/agents` | all | 22 small inline links, long mono endpoints in prose | Low | — | [#41](https://github.com/fromknowware/knowware-now/pull/41) | +| X1 | `/404` | all | Buttons 41px | Low | — | [#38](https://github.com/fromknowware/knowware-now/pull/38) | +| X2 | all | all | `html, body { overflow-x:hidden }` hides overflow instead of fixing it | Info | — | kept as a safety net; the check tool lifts it | +| X3 | `/read/NN` | all | Gate: `display:flex` beat the `hidden` attribute, so a signed-in reader saw the sign-up form under *Continue reading* (found while testing, not in the first scan) | Med | — | [#37](https://github.com/fromknowware/knowware-now/pull/37) | +| X4 | `/the-81` graph | touch | `touchmove` called `preventDefault`: a swipe starting on the canvas never scrolled the page (0px measured) | High | — | [#35](https://github.com/fromknowware/knowware-now/pull/35) | + +## Not a problem (checked and left alone) + +- Body-copy measure and wrapping at 320–430 (`/method`, `/definition`, `/rules`, `/colophon`, story text). +- Dossier order: name → tier → meta → cold-open box with its asterisk footnote intact → bio → works. +- Cold-open box and footnote in the nine-voices cards render intact (only the layout around them is cramped: R1). +- `/read/NN/full` signed-in reading is one column with comfortable measure. +- Fonts and images (see page weight). +- Landscape 844×390: content reflows; the only landscape-specific defect is the nav (G2). + +## Constraints the fixes keep + +No analytics, no cookies beyond the reader flag (the dismissible dock uses `sessionStorage` for the current tab +only), strict CSP (any new inline script is hashed by `integrations/security-headers.mjs`; the new code lives in +the bundled module `src/scripts/kw.ts`), WCAG 2.2 AA, identity untouched (navy, cream, signal blue, Helvetica Neue, +JetBrains Mono, hairline rules, bar field). + +## Results after the fixes + +All fix PRs (#32, #34–#38, #41, #42, #62) merged into one scratch branch (not pushed, not for merging), built, and run +through the same tool: 20 pages × 7 devices = 140 runs, axe in light/dark/warm at 375, reader pages signed out, +`/read/01/full` signed in. + +| Check | 320 | 360 | 375 | 390 | 430 | 844 (land.) | 768 (tab.) | +|---|---|---|---|---|---|---|---| +| Pages with horizontal overflow | 0 / 20 | 0 / 20 | 0 / 20 | 0 / 20 | 0 / 20 | 0 / 20 | 0 / 20 | +| Tap targets under 44px (non-inline, summed over pages) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ...of which in nav/footer/dock | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| Text nodes under 12px (summed) | 18 | 18 | 18 | 18 | 18 | 18 | 18 | +| Pages failing any check except axe | 0 / 20 | 0 / 20 | 0 / 20 | 0 / 20 | 0 / 20 | 0 / 20 | 0 / 20 | +| axe violations (rules, all themes) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | + +**140 runs, 0 failures** (re-run on the newest `main` with the new `/old-link` and `/systems-of-intelligence` pages: 154 runs, 0 failures once #62 is in; without it, two new links fail: the footer's *Systems of Intelligence* link at 33px and the source URLs at 22px). What the tool still lists as warnings (none fail the run): inline links under 44px inside +running text (exempt under WCAG 2.2 target size), the marquee strip clipping its own scrolling items on purpose, the +cast role column ellipsis on wide screens, and the 11px labels drawn on the graph canvas. "Pages failing" is zero +because the check is the pass criterion: overflow, 44px targets, 16px text fields, dock bar clearance and controls, +console/CSP errors, axe. + +Measured by hand in addition to the tool (true emulation): the graph taps select nodes and a swipe from the canvas +scrolls the page (before: 0px); a text field in focus hides the dock bar; the signed-in gate no longer shows the +form; the hero wordmark fits at 320, 375 and 430; the menu opens, closes on Esc and on a tap outside. + +## What could not be tested here, and what to check on your own phone + +Everything above was measured in headless Chrome under device emulation (viewport size, device pixel ratio, +touch events, mobile user agent). That is real layout at the real width, but it is not a phone. Not covered: + +| Not testable here | Why it matters | What to look at | +|---|---|---| +| iOS Safari rendering | WebKit differs from Chrome: dynamic toolbar (`100vh`), `position: sticky` inside scrollers, `-webkit-mask-image` fades, `backdrop-filter`, canvas text | Scroll the home page and `/the-81` with the toolbar collapsing: nothing should jump, the sticky strip on the graph should stay put | +| Safe-area insets | `env(safe-area-inset-*)` is always 0 in headless Chrome | iPhone with a home indicator: the pre-order bar must sit above it, in portrait and landscape; in landscape neither bar nor menu may touch the notch | +| iOS zoom on focus | Emulation cannot trigger it | Focus the fields on `/contribute`, `/order`, the gate on `/read/01`, the token form on `/agents`: the page must not zoom | +| On-screen keyboard | The pre-order bar hides while a field is focused; the field must stay visible | Same fields; type a long email | +| Real touch | Tap accuracy, scroll inertia, pinch-zoom on the graph canvas | `/the-81` graph: tap a node, swipe the page from the canvas, pinch | +| Android Chrome | Different default fonts (Roboto instead of Helvetica Neue): the home wordmark is sized from its measured width with 7% slack | `/` at 360 and 412: the whole word KNOWWARE visible | +| Performance | Emulation does not throttle the CPU of an older phone | `/the-81` graph and the animated story diagrams on an older phone: no stutter, no heat | +| Dark and warm on OLED | Emulation does not show panel behaviour | Switch theme in the menu: band sections, the dock bar and the graph canvas should not smear or glow | +| 200% text and OS font size | Layout with large text | iOS Settings > Display > Text Size and Android font scale to the largest: nav menu, forms and dossier still usable | + +URLs to open on the phone (use the production domain once the PRs are merged; before that use the Pages preview): + +- https://knowware.press/ +- https://knowware.press/the-81 (tap CAST / ELEMENTS / GRAPH; tap two nodes on the graph) +- https://knowware.press/voices/42 +- https://knowware.press/read, /read/01 (gate, causal diagram, voice cards), /read/x +- https://knowware.press/read/01/full after signing up (signed-in reading) +- https://knowware.press/method, /definition +- https://knowware.press/stories, /stories/knight-capital-2012 +- https://knowware.press/contribute, /order +- https://knowware.press/agents (the two tables) +- https://knowware.press/rules, /colophon, /no-such-page + +## Not done, on purpose + +- **Contrast tokens**: nothing to fix (see the correction above). +- **Story canvas cost**: reviewed in code (on-screen only, DPR capped at 2, honours reduced motion), not measured on a + slow phone. +- **Webfont weights**: three weights, 64 KB in total; dropping the 600 weight would save 22 KB but changes the look. +- The nav stays non-sticky as it is on `main` (the brief called it sticky; the code never made it so). The sticky bars + that assumed a 52px sticky nav were fixed instead. diff --git a/drafts/mobile/shots/audit/agents-table-375.jpg b/drafts/mobile/shots/audit/agents-table-375.jpg new file mode 100644 index 0000000..5e36825 Binary files /dev/null and b/drafts/mobile/shots/audit/agents-table-375.jpg differ diff --git a/drafts/mobile/shots/audit/contribute-375.jpg b/drafts/mobile/shots/audit/contribute-375.jpg new file mode 100644 index 0000000..9c84226 Binary files /dev/null and b/drafts/mobile/shots/audit/contribute-375.jpg differ diff --git a/drafts/mobile/shots/audit/dossier-375.jpg b/drafts/mobile/shots/audit/dossier-375.jpg new file mode 100644 index 0000000..f6becbc Binary files /dev/null and b/drafts/mobile/shots/audit/dossier-375.jpg differ diff --git a/drafts/mobile/shots/audit/home-hero-375.jpg b/drafts/mobile/shots/audit/home-hero-375.jpg new file mode 100644 index 0000000..708ad9e Binary files /dev/null and b/drafts/mobile/shots/audit/home-hero-375.jpg differ diff --git a/drafts/mobile/shots/audit/nav-landscape-844.jpg b/drafts/mobile/shots/audit/nav-landscape-844.jpg new file mode 100644 index 0000000..0fb8317 Binary files /dev/null and b/drafts/mobile/shots/audit/nav-landscape-844.jpg differ diff --git a/drafts/mobile/shots/audit/nav-tablet-768.jpg b/drafts/mobile/shots/audit/nav-tablet-768.jpg new file mode 100644 index 0000000..48929fa Binary files /dev/null and b/drafts/mobile/shots/audit/nav-tablet-768.jpg differ diff --git a/drafts/mobile/shots/audit/read-gate-375.jpg b/drafts/mobile/shots/audit/read-gate-375.jpg new file mode 100644 index 0000000..3e0eed2 Binary files /dev/null and b/drafts/mobile/shots/audit/read-gate-375.jpg differ diff --git a/drafts/mobile/shots/audit/read01-cards-320.jpg b/drafts/mobile/shots/audit/read01-cards-320.jpg new file mode 100644 index 0000000..242fb2f Binary files /dev/null and b/drafts/mobile/shots/audit/read01-cards-320.jpg differ diff --git a/drafts/mobile/shots/audit/the81-elements-375.jpg b/drafts/mobile/shots/audit/the81-elements-375.jpg new file mode 100644 index 0000000..7f91f87 Binary files /dev/null and b/drafts/mobile/shots/audit/the81-elements-375.jpg differ diff --git a/drafts/mobile/shots/audit/the81-graph-375.jpg b/drafts/mobile/shots/audit/the81-graph-375.jpg new file mode 100644 index 0000000..f1c8623 Binary files /dev/null and b/drafts/mobile/shots/audit/the81-graph-375.jpg differ diff --git a/drafts/mobile/shots/audit/the81-sticky-375.jpg b/drafts/mobile/shots/audit/the81-sticky-375.jpg new file mode 100644 index 0000000..04a8669 Binary files /dev/null and b/drafts/mobile/shots/audit/the81-sticky-375.jpg differ diff --git a/drafts/mobile/tools/README.md b/drafts/mobile/tools/README.md new file mode 100644 index 0000000..406d615 --- /dev/null +++ b/drafts/mobile/tools/README.md @@ -0,0 +1,9 @@ +# Screenshot helpers for the mobile audit + +Throw-away helpers used to make the before/after images in the PRs. They need `pillow` (Python) and the +emulation setup from `docs/mobile-check.md`. + +- `shot.mjs [js] [wait-ms] [--full] [--theme=dark]` one emulated screenshot +- `probe.mjs ''` evaluate an expression in an emulated viewport (`BASE=` picks the server) +- `sheet.py` / `grid.py` tile screenshots side by side or in a captioned grid (small JPEGs) +- `mkgrid.sh` before/after grid at 320, 375 and 430 diff --git a/drafts/mobile/tools/graph-tap.mjs b/drafts/mobile/tools/graph-tap.mjs new file mode 100644 index 0000000..150f4f5 --- /dev/null +++ b/drafts/mobile/tools/graph-tap.mjs @@ -0,0 +1,35 @@ +// usage: node graph-tap.mjs — open GRAPH, tap nodes by touch, report strip state, screenshot +import { createRequire } from 'node:module'; +import { DEVICES } from '../../../scripts/mobile-check.mjs'; +const require = createRequire(import.meta.url.replace('drafts/mobile/tools/graph-tap.mjs', 'scripts/x.mjs')); +const puppeteer = require('puppeteer-core'); +const [base, dev, out] = process.argv.slice(2); +const d = DEVICES[dev]; +const b = await puppeteer.launch({ executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', headless: 'new' }); +const p = await b.newPage(); +await p.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1'); +await p.setViewport({ width: d.w, height: d.h, deviceScaleFactor: 1.5, isMobile: true, hasTouch: true }); +await p.goto(base + '/the-81', { waitUntil: 'networkidle2' }); +await p.evaluate(() => document.getElementById('btn-graph').click()); +await new Promise(r => setTimeout(r, 3500)); +await p.evaluate(() => document.getElementById('graph-canvas').scrollIntoView({ block: 'start' })); +await new Promise(r => setTimeout(r, 300)); +const box = await p.evaluate(() => { const r = document.getElementById('graph-canvas').getBoundingClientRect(); return { x: r.left, y: r.top, w: r.width, h: r.height, vh: innerHeight }; }); +console.log('canvas', JSON.stringify(box)); +let tapped = 0, picked = []; +for (let gy = 0.1; gy < 0.9 && picked.length < 2; gy += 0.07) for (let gx = 0.1; gx < 0.9 && picked.length < 2; gx += 0.07) { + const y = box.y + box.h * gy; if (y > box.vh - 10 || y < 10) continue; + await p.touchscreen.tap(box.x + box.w * gx, y); tapped++; + const st = await p.evaluate(() => { const s = document.getElementById('graph-strip'); return s.hidden ? null : document.getElementById('graph-strip-name').textContent + '|' + document.getElementById('graph-sel-count').textContent; }); + if (st && !picked.includes(st)) picked.push(st); +} +console.log('taps', tapped, 'picked', JSON.stringify(picked)); +await p.screenshot({ path: out, type: 'jpeg', quality: 60 }); +// page must still scroll when a swipe starts on the canvas +const y0 = await p.evaluate(() => scrollY); +await p.touchscreen.touchStart(box.x + box.w / 2, Math.min(box.y + 300, box.vh - 100)); +await p.touchscreen.touchMove(box.x + box.w / 2, Math.min(box.y + 300, box.vh - 100) - 150); +await p.touchscreen.touchEnd(); +await new Promise(r => setTimeout(r, 400)); +console.log('scroll moved by swipe on canvas:', (await p.evaluate(() => scrollY)) - y0); +await b.close(); diff --git a/drafts/mobile/tools/grid.py b/drafts/mobile/tools/grid.py new file mode 100644 index 0000000..77acc89 --- /dev/null +++ b/drafts/mobile/tools/grid.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +# Lay screenshots out in a grid with captions, as one small JPEG (for PR descriptions). +# usage: grid.py out.jpg cellwidth cols "caption1|file1" "caption2|file2" ... +import sys +from PIL import Image, ImageDraw, ImageFont +out, cw, cols, *items = sys.argv[1:] +cw, cols = int(cw), int(cols) +cells = [] +for it in items: + cap, path = it.split('|', 1) + im = Image.open(path).convert('RGB') + im = im.resize((cw, round(im.height * cw / im.width)), Image.LANCZOS) + cells.append((cap, im)) +try: + font = ImageFont.truetype('/System/Library/Fonts/Menlo.ttc', 13) +except Exception: + font = ImageFont.load_default() +rows = [cells[i:i + cols] for i in range(0, len(cells), cols)] +gap, cap_h = 8, 22 +rh = [max(im.height for _, im in r) + cap_h for r in rows] +sheet = Image.new('RGB', (cols * cw + gap * (cols - 1), sum(rh) + gap * (len(rows) - 1)), (255, 255, 255)) +d = ImageDraw.Draw(sheet) +y = 0 +for r, h in zip(rows, rh): + for c, (cap, im) in enumerate(r): + x = c * (cw + gap) + d.text((x + 4, y + 3), cap, fill=(20, 20, 20), font=font) + sheet.paste(im, (x, y + cap_h)) + y += h + gap +sheet.save(out, 'JPEG', quality=62, optimize=True) +print(out, sheet.size) diff --git a/drafts/mobile/tools/mkgrid.sh b/drafts/mobile/tools/mkgrid.sh new file mode 100644 index 0000000..fefaf55 --- /dev/null +++ b/drafts/mobile/tools/mkgrid.sh @@ -0,0 +1,13 @@ +#!/bin/zsh +# usage: mkgrid.sh name1:"caption" name2:"caption" ... (each name has -before/-after-.jpg; use name@before / name@after for single-sided rows) +dir=$1; out=$2; shift 2 +items=() +for spec in "$@"; do + key=${spec%%:*}; cap=${spec#*:} + tag=${key##*@}; name=${key%%@*} + for dev in iphone-se-1 iphone-se phone-large; do + case $dev in iphone-se-1) w=320;; iphone-se) w=375;; *) w=430;; esac + items+=("$cap @${w}|$dir/$name-$tag-$dev.jpg") + done +done +python3 ${0:A:h}/grid.py $out 300 3 "${items[@]}" diff --git a/drafts/mobile/tools/probe.mjs b/drafts/mobile/tools/probe.mjs new file mode 100644 index 0000000..b132d3e --- /dev/null +++ b/drafts/mobile/tools/probe.mjs @@ -0,0 +1,14 @@ +// usage: BASE=http://localhost:8799 node probe.mjs '' +// Evaluates an expression in an emulated phone viewport (DPR 2) and prints the JSON result. +import { createRequire } from 'node:module'; +const require = createRequire(import.meta.url.replace('drafts/mobile/tools/probe.mjs', 'scripts/x.mjs')); +const puppeteer = require('puppeteer-core'); +const [url, w, h, expr] = process.argv.slice(2); +const b = await puppeteer.launch({ executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', headless: 'new' }); +const p = await b.newPage(); +await p.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1'); +await p.setViewport({ width: +w, height: +h, deviceScaleFactor: 2, isMobile: true, hasTouch: true }); +await p.goto((process.env.BASE || 'http://localhost:8799') + url, { waitUntil: 'networkidle2' }); +await new Promise(r => setTimeout(r, 600)); +console.log(JSON.stringify(await p.evaluate(expr), null, 1)); +await b.close(); diff --git a/drafts/mobile/tools/sheet.py b/drafts/mobile/tools/sheet.py new file mode 100644 index 0000000..8892d3d --- /dev/null +++ b/drafts/mobile/tools/sheet.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +# Tile several screenshots side by side as one small JPEG for viewing. +# usage: sheet.py out.jpg cellwidth in1.jpg in2.jpg ... +import sys +from PIL import Image +out, cw, *ins = sys.argv[1:] +cw = int(cw) +ims = [] +for p in ins: + im = Image.open(p).convert('RGB') + h = round(im.height * cw / im.width) + ims.append(im.resize((cw, h), Image.LANCZOS)) +H = max(i.height for i in ims) +sheet = Image.new('RGB', (cw * len(ims) + 8 * (len(ims) - 1), H), (128, 128, 128)) +for n, im in enumerate(ims): + sheet.paste(im, (n * (cw + 8), 0)) +sheet.save(out, 'JPEG', quality=60) +print(out, sheet.size) diff --git a/drafts/mobile/tools/shot.mjs b/drafts/mobile/tools/shot.mjs new file mode 100644 index 0000000..1ed52dc --- /dev/null +++ b/drafts/mobile/tools/shot.mjs @@ -0,0 +1,22 @@ +// usage: node shot.mjs [js-to-run-before] [wait-ms] [--full] [--theme=dark] +import { createRequire } from 'node:module'; +import { DEVICES } from '../../../scripts/mobile-check.mjs'; +const require = createRequire(import.meta.url.replace('drafts/mobile/tools/shot.mjs', 'scripts/x.mjs')); +const puppeteer = require('puppeteer-core'); +const args = process.argv.slice(2); +const flags = args.filter((a) => a.startsWith('--')); +const [base, url, dev, out, js, wait] = args.filter((a) => !a.startsWith('--')); +const UA = { iphone: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1', android: 'Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36', ipad: 'Mozilla/5.0 (iPad; CPU OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1' }; +const d = DEVICES[dev]; +const b = await puppeteer.launch({ executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', headless: 'new', args: ['--hide-scrollbars'] }); +const p = await b.newPage(); +await p.setUserAgent(UA[d.ua]); +await p.setViewport({ width: d.w, height: d.h, deviceScaleFactor: flags.includes('--hi') ? d.dpr : 1.5, isMobile: true, hasTouch: true, isLandscape: !!d.landscape }); +const th = flags.find((f) => f.startsWith('--theme=')); +if (th) await p.evaluateOnNewDocument((t) => { try { localStorage.setItem('kw-theme', t); } catch {} }, th.split('=')[1]); +await p.goto(base + url, { waitUntil: 'networkidle2', timeout: 180000 }); +await new Promise((r) => setTimeout(r, 500)); +if (js) { const r = await p.evaluate(js); if (r !== undefined) console.log(JSON.stringify(r)); } +await new Promise((r) => setTimeout(r, +(wait || 700))); +await p.screenshot({ path: out, type: 'jpeg', quality: 60, fullPage: flags.includes('--full') }); +await b.close(); diff --git a/package-lock.json b/package-lock.json index c05efca..b091ade 100755 --- a/package-lock.json +++ b/package-lock.json @@ -15,6 +15,7 @@ "@resvg/resvg-js": "^2.6.2", "axe-core": "^4.14.0", "gifenc": "^1.0.3", + "puppeteer-core": "^25.14.0", "satori": "^0.62.0", "turndown": "7.2.4", "turndown-plugin-gfm": "1.0.2" @@ -1370,6 +1371,35 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@puppeteer/browsers": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.5.tgz", + "integrity": "sha512-UoCo3Pynbm37aLEEoydSiG+t24ui7sLD40+07CKxzxNy4PpSowJMkvlLIiV67XjP1lMVynhQVnuwlTABqBH8LQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "modern-tar": "^0.8.5", + "yargs": "^18.0.0" + }, + "bin": { + "browsers": "lib/main-cli.js" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "proxy-agent": ">=8.0.1", + "yauzl": "^2.10.0 || ^3.4.0" + }, + "peerDependenciesMeta": { + "proxy-agent": { + "optional": true + }, + "yauzl": { + "optional": true + } + } + }, "node_modules/@resvg/resvg-js": { "version": "2.6.2", "resolved": "https://registry.npmjs.org/@resvg/resvg-js/-/resvg-js-2.6.2.tgz", @@ -2055,6 +2085,32 @@ "am-i-vibing": "dist/cli.mjs" } }, + "node_modules/ansi-regex": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/anymatch": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", @@ -2278,6 +2334,23 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/chromium-bidi": { + "version": "157.0.8090-0", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-157.0.8090-0.tgz", + "integrity": "sha512-KJw7IQgqXwxpJgJlEIPg5mr2ZoqA+jkTRtc5EABI7sUJ3bu3cpI7NuEBoj4Gn1AsF78CaT9So5WQWspK3/wYag==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "mitt": "^3.0.1", + "zod": "^4.6.5" + }, + "engines": { + "node": ">=20.19.0 <22.0.0 || >=22.12.0" + }, + "peerDependencies": { + "devtools-protocol": "*" + } + }, "node_modules/ci-info": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", @@ -2293,6 +2366,39 @@ "node": ">=8" } }, + "node_modules/cliui": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", + "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cliui/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/clsx": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", @@ -2537,6 +2643,13 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/devtools-protocol": { + "version": "0.0.1696802", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1696802.tgz", + "integrity": "sha512-FO5/SENfvc2K8wRnWQflKcwuoTH4dBkXCWTQ9ebIWtuX8JM5+ZvCotaEmkfh21pO7TvIKGTM3hG4xFiq9WTwmg==", + "dev": true, + "license": "BSD-3-Clause" + }, "node_modules/diff": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/diff/-/diff-9.0.0.tgz", @@ -2622,6 +2735,13 @@ "node": ">=4" } }, + "node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, + "license": "MIT" + }, "node_modules/emoji-regex-xs": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/emoji-regex-xs/-/emoji-regex-xs-2.0.1.tgz", @@ -2638,6 +2758,16 @@ "integrity": "sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA==", "license": "MIT" }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", @@ -2755,6 +2885,29 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-tsconfig": { "version": "5.0.0-beta.6", "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-5.0.0-beta.6.tgz", @@ -3325,6 +3478,23 @@ ], "license": "MIT" }, + "node_modules/mitt": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", + "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", + "dev": true, + "license": "MIT" + }, + "node_modules/modern-tar": { + "version": "0.8.6", + "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.6.tgz", + "integrity": "sha512-LYSks0tNVqbtez/9OB0YFP6qLRSqkdAxJWOQpVaR67lNTbj2zNLyYpowkRMia5lXLCZKzxwoxkxH2MbbBR2aEg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/mrmime": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", @@ -3602,6 +3772,24 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/puppeteer-core": { + "version": "25.14.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.14.0.tgz", + "integrity": "sha512-LQitnes3tBeVbdZ7V/4iwJPLZGgkl9uBVK0W7YYMh68j/3Y9eNuvj4yl+Fdo7zN0SuajOMrhd7aPj3DifK8k6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@puppeteer/browsers": "3.2.5", + "chromium-bidi": "157.0.8090-0", + "devtools-protocol": "0.0.1696802", + "typed-query-selector": "^2.12.3", + "webdriver-bidi-protocol": "1.0.1", + "ws": "^8.22.0" + }, + "engines": { + "node": ">=22.12.0" + } + }, "node_modules/radix3": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/radix3/-/radix3-1.1.2.tgz", @@ -3902,6 +4090,23 @@ "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", "license": "MIT" }, + "node_modules/string-width": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/string.prototype.codepointat": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/string.prototype.codepointat/-/string.prototype.codepointat-0.2.1.tgz", @@ -3923,6 +4128,22 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, "node_modules/svgo": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/svgo/-/svgo-4.1.0.tgz", @@ -4042,6 +4263,13 @@ "dev": true, "license": "MIT" }, + "node_modules/typed-query-selector": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz", + "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==", + "dev": true, + "license": "MIT" + }, "node_modules/ufo": { "version": "1.6.4", "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", @@ -4417,12 +4645,87 @@ } } }, + "node_modules/webdriver-bidi-protocol": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-1.0.1.tgz", + "integrity": "sha512-WXWs/aXF2a6Al1Z2/V/7Gp2oPZOAAmHjJOTmv4KCXRJ122IMj3tSSMc6a4q3K4QOmhQbse/Ahr+oTVJOU2dUiw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/xxhash-wasm": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz", "integrity": "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==", "license": "MIT" }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, "node_modules/yaml": { "version": "2.9.1", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", @@ -4438,6 +4741,24 @@ "url": "https://github.com/sponsors/eemeli" } }, + "node_modules/yargs": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz", + "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^8.2.1", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, "node_modules/yargs-parser": { "version": "22.0.0", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", diff --git a/package.json b/package.json index 7661172..17288cf 100755 --- a/package.json +++ b/package.json @@ -7,7 +7,8 @@ "preview": "astro preview", "extract": "node scripts/extract-content.mjs", "test": "node --test tests/*.test.mjs", - "verify": "node scripts/verify-build.mjs" + "verify": "node scripts/verify-build.mjs", + "mobile-check": "node scripts/mobile-check.mjs" }, "dependencies": { "@astrojs/sitemap": "^3.7.4", @@ -19,6 +20,7 @@ "@resvg/resvg-js": "^2.6.2", "axe-core": "^4.14.0", "gifenc": "^1.0.3", + "puppeteer-core": "^25.14.0", "satori": "^0.62.0", "turndown": "7.2.4", "turndown-plugin-gfm": "1.0.2" diff --git a/scripts/mobile-check.mjs b/scripts/mobile-check.mjs new file mode 100644 index 0000000..3b3ee83 --- /dev/null +++ b/scripts/mobile-check.mjs @@ -0,0 +1,348 @@ +#!/usr/bin/env node +// Mobile regression check — developer tool, not part of the site build. +// +// Loads each page under TRUE device emulation (CDP Emulation.setDeviceMetricsOverride +// through puppeteer-core, system Chrome, no browser download) and fails when: +// 1. the page overflows horizontally (measured with the html/body overflow-x:hidden +// safety net temporarily removed, so hidden overflow is not mistaken for none); +// 2. an interactive element is smaller than 44x44 CSS px (inline links in running +// text are listed as warnings, not failures); +// 3. axe-core reports a violation (light, dark and warm themes); +// 4. text smaller than 12px is rendered (warning only); +// 5. the fixed dock bar covers the last content at the bottom of the page. +// +// npm run mobile-check -- --pages /,/the-81 (see docs/mobile-check.md) +// node scripts/mobile-check.mjs --base http://localhost:8799 --pages /,/the-81 --devices iphone-se,iphone-14 +// +// Needs: `npm install --no-save puppeteer-core`, the site served (wrangler pages dev dist --port 8799 +// --kv CLAIMS), and Google Chrome at /Applications/Google Chrome.app (or CHROME_PATH). + +import fs from 'node:fs'; +import path from 'node:path'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; + +const require = createRequire(import.meta.url); + +export const DEVICES = { + 'iphone-se-1': { w: 320, h: 568, dpr: 2, ua: 'iphone', label: 'iPhone SE (1st gen) 320x568' }, + 'iphone-se': { w: 375, h: 667, dpr: 2, ua: 'iphone', label: 'iPhone SE 375x667' }, + 'android-s': { w: 360, h: 800, dpr: 3, ua: 'android', label: 'Small Android 360x800' }, + 'iphone-14': { w: 390, h: 844, dpr: 3, ua: 'iphone', label: 'iPhone 14 390x844' }, + 'phone-large': { w: 430, h: 932, dpr: 3, ua: 'iphone', label: 'Large phone 430x932' }, + 'landscape': { w: 844, h: 390, dpr: 3, ua: 'iphone', label: 'Landscape 844x390', landscape: true }, + 'tablet': { w: 768, h: 1024, dpr: 2, ua: 'ipad', label: 'Tablet 768x1024' }, +}; +const UA = { + iphone: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1', + android: 'Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36', + ipad: 'Mozilla/5.0 (iPad; CPU OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1', +}; +// Standard run: the five phone widths the audit cares about, plus landscape and tablet. +const DEFAULT_DEVICES = ['iphone-se-1', 'android-s', 'iphone-se', 'iphone-14', 'phone-large', 'landscape', 'tablet']; + +export const PAGES = [ + '/', '/the-81', '/voices/01', '/voices/42', '/voices/81', + '/read', '/read/01', '/read/x', '/read/01/full', + '/method', '/definition', '/stories', '/stories/knight-capital-2012', + '/stories/anthropic-agentic-misalignment-simulation', + '/contribute', '/order', '/rules', '/colophon', '/agents', '/this-page-does-not-exist', +]; + +function parseArgs(argv) { + const o = { base: 'http://localhost:8799', pages: null, devices: null, themes: ['light', 'dark', 'warm'], + axe: true, axeAll: false, shots: null, json: null, noFail: false, sliceH: 1400, verbose: false, scrollDock: true }; + for (let i = 2; i < argv.length; i++) { + const a = argv[i]; + const v = () => argv[++i]; + if (a === '--base') o.base = v(); + else if (a === '--pages') o.pages = v().split(','); + else if (a === '--devices') o.devices = v().split(','); + else if (a === '--themes') o.themes = v().split(','); + else if (a === '--no-axe') o.axe = false; + else if (a === '--axe-all') o.axeAll = true; + else if (a === '--shots') o.shots = v(); + else if (a === '--json') o.json = v(); + else if (a === '--no-fail') o.noFail = true; + else if (a === '--slice') o.sliceH = Number(v()); + else if (a === '--verbose' || a === '-v') o.verbose = true; + else if (a === '--help' || a === '-h') { console.log(fs.readFileSync(new URL(import.meta.url), 'utf8').split('\n').slice(1, 22).join('\n')); process.exit(0); } + else { console.error('unknown arg ' + a); process.exit(2); } + } + return o; +} + +// ---- in-page measurements ------------------------------------------------ +// Everything below runs inside the page; it must stay self-contained. +function measureInPage(minTap) { + const vw = document.documentElement.clientWidth; + const out = { vw, scrollW: 0, offenders: [], clipped: [], scrollers: [], smallInputs: [], small: [], tiny: [], sticky: [], dock: null, viewportMeta: document.querySelector('meta[name=viewport]')?.content || '' }; + const html = document.documentElement; + out.scrollW = Math.max(html.scrollWidth, document.body.scrollWidth); + const sel = (el) => { + let s = el.tagName.toLowerCase(); + if (el.id) s += '#' + el.id; + const c = (el.getAttribute('class') || '').trim().split(/\s+/).filter(Boolean).slice(0, 2); + if (c.length) s += '.' + c.join('.'); + return s; + }; + const visible = (el, r, cs) => r.width > 0 && r.height > 0 && cs.visibility !== 'hidden' && cs.display !== 'none' && cs.opacity !== '0'; + const clipAncestor = (el) => { + for (let p = el.parentElement; p && p !== document.body && p !== html; p = p.parentElement) { + const cs = getComputedStyle(p); + if (/(auto|scroll|hidden|clip)/.test(cs.overflowX)) return { p, cs }; + } + return null; + }; + const all = document.body.querySelectorAll('*'); + for (const el of all) { + const cs = getComputedStyle(el); + const r = el.getBoundingClientRect(); + if (!visible(el, r, cs)) continue; + if (el.closest('svg') && el.tagName.toLowerCase() !== 'svg') continue; + // 1. horizontal overflow of the viewport + if (r.right < -1000) continue; // honeypot fields parked far off-screen on purpose + if (r.right > vw + 0.5 || r.left < -0.5) { + const ca = clipAncestor(el); + if (!ca) out.offenders.push({ el: sel(el), left: Math.round(r.left), right: Math.round(r.right), w: Math.round(r.width), text: (el.textContent || '').trim().slice(0, 40) }); + else if (/hidden|clip/.test(ca.cs.overflowX) && r.width > 2 && ca.p.clientWidth > 2) out.clipped.push({ el: sel(el), by: sel(ca.p), left: Math.round(r.left), right: Math.round(r.right), text: (el.textContent || '').trim().slice(0, 40) }); + } + // content cut off by overflow:hidden on the element itself + if (/hidden|clip/.test(cs.overflowX) && el.scrollWidth > el.clientWidth + 1 && el.clientWidth > 2 && !['svg', 'canvas'].includes(el.tagName.toLowerCase())) { + out.clipped.push({ el: sel(el), by: 'self', scrollW: el.scrollWidth, clientW: el.clientWidth, text: (el.textContent || '').trim().slice(0, 40) }); + } + // horizontal scrollers that hide content behind a swipe + if (/(auto|scroll)/.test(cs.overflowX) && el.scrollWidth > el.clientWidth + 1 && el.clientWidth > 0 && !/marquee/.test(el.className)) { + out.scrollers.push({ el: sel(el), scrollW: el.scrollWidth, clientW: el.clientWidth, text: (el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 40) }); + } + // 16px minimum on text fields, or iOS Safari zooms the page on focus + const tag0 = el.tagName.toLowerCase(); + if ((tag0 === 'input' && !/^(checkbox|radio|hidden|submit|button|range|file)$/.test(el.type)) || tag0 === 'textarea' || tag0 === 'select') { + if (parseFloat(cs.fontSize) < 16) out.smallInputs.push({ el: sel(el), px: parseFloat(cs.fontSize) }); + } + // 2. tap targets + const tag = el.tagName.toLowerCase(); + const isCtl = (tag === 'a' && el.hasAttribute('href')) || tag === 'button' || tag === 'select' || tag === 'textarea' || tag === 'summary' || + (tag === 'input' && el.type !== 'hidden') || el.getAttribute('role') === 'button' || el.getAttribute('role') === 'tab' || + (el.hasAttribute('tabindex') && el.tabIndex >= 0 && tag !== 'main' && !el.closest('svg')); + if (isCtl && !el.closest('[inert]')) { + // a label-wrapped checkbox/radio: measure the label + let m = el; + if (tag === 'input' && (el.type === 'checkbox' || el.type === 'radio')) { const l = el.closest('label') || (el.id && document.querySelector('label[for="' + el.id + '"]')); if (l) m = l; } + const mr = m.getBoundingClientRect(); + const onscreenX = mr.right > 0 && mr.left < vw; + const skip = el.classList.contains('kw-skip') || !onscreenX; + if (!skip && (mr.width < minTap - 0.5 || mr.height < minTap - 0.5)) { + const inline = cs.display === 'inline' && !!el.closest('p, li, dd, blockquote, figcaption, td'); + out.small.push({ el: sel(el), w: Math.round(mr.width), h: Math.round(mr.height), inline, text: (el.textContent || el.getAttribute('aria-label') || el.getAttribute('title') || '').trim().replace(/\s+/g, ' ').slice(0, 30) }); + } + } + // 4. tiny text + const hasText = [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim().length > 1); + if (hasText) { + const fs = parseFloat(cs.fontSize); + if (fs < 12) out.tiny.push({ el: sel(el), px: Math.round(fs * 10) / 10, text: el.textContent.trim().slice(0, 30) }); + } + if (cs.position === 'sticky' || cs.position === 'fixed') { + out.sticky.push({ el: sel(el), pos: cs.position, top: cs.top, bottom: cs.bottom, h: Math.round(r.height), z: cs.zIndex }); + } + } + return out; +} + +async function measurePage(page, minTap) { + return page.evaluate(measureInPage, minTap); +} + +// Overflow check with the html/body safety net lifted. +async function overflowCheck(page) { + return page.evaluate(() => { + const st = document.createElement('style'); + st.id = '__mc_overflow'; + st.textContent = 'html,body{overflow-x:visible!important}'; + document.head.appendChild(st); + const html = document.documentElement; + const r = { vw: html.clientWidth, scrollW: Math.max(html.scrollWidth, document.body.scrollWidth), innerW: window.innerWidth, vvW: window.visualViewport?.width }; + st.remove(); + return r; + }); +} + +async function dockCheck(page) { + // Scroll to the bottom, then see whether the fixed dock sits on top of real content. + return page.evaluate(async () => { + window.scrollTo(0, document.documentElement.scrollHeight); + await new Promise((r) => setTimeout(r, 400)); + const dock = document.getElementById('kw-dock'); + if (!dock) return null; + const dr = dock.getBoundingClientRect(); + const cs = getComputedStyle(dock); + const shown = dock.classList.contains('kw-visible') || cs.transform === 'none'; + const hits = []; + document.querySelectorAll('footer *, main > *:last-child *').forEach((el) => { + if (dock.contains(el)) return; + const r = el.getBoundingClientRect(); + if (r.width === 0 || r.height === 0) return; + const t = (el.childNodes.length && [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim())); + if (t && r.bottom > dr.top + 1 && r.top < dr.bottom - 1 && dr.height > 0 && dr.top < innerHeight) hits.push({ el: el.tagName.toLowerCase() + '.' + (el.className || '').toString().split(' ')[0], text: el.textContent.trim().slice(0, 30) }); + }); + const targets = [...dock.querySelectorAll('a, button')].filter((e) => e.getBoundingClientRect().width > 0).map((e) => { const r = e.getBoundingClientRect(); return { el: e.id || e.tagName.toLowerCase(), w: Math.round(r.width), h: Math.round(r.height) }; }); + // Does the last real content end above the dock? (footer text must be fully visible) + const foot = document.querySelector('footer'); + const lastBottom = foot ? Math.max(...[...foot.querySelectorAll('*')].map((e) => e.getBoundingClientRect().bottom)) : 0; + const padBottom = parseFloat(getComputedStyle(dock).paddingBottom); + window.scrollTo(0, 0); + return { shown, targets, lastBottom: Math.round(lastBottom), padBottom, top: Math.round(dr.top), h: Math.round(dr.height), bottom: Math.round(dr.bottom), vh: innerHeight, hits: hits.slice(0, 5) }; + }); +} + +async function runAxe(page, axeSource) { + await page.evaluate(axeSource); + return page.evaluate(async () => { + const r = await window.axe.run(document, { resultTypes: ['violations'] }); + return r.violations.map((v) => ({ id: v.id, impact: v.impact, n: v.nodes.length, sample: v.nodes[0]?.target?.join(' ').slice(0, 80), summary: (v.nodes[0]?.failureSummary || '').split('\n').slice(1, 3).join(' ').slice(0, 160) })); + }); +} + +async function setTheme(page, theme) { + await page.evaluate((t) => { + // The theme change animates colours over 0.7s: measure contrast after the change, not during it. + if (!document.getElementById('__mc_notrans')) { + const st = document.createElement('style'); + st.id = '__mc_notrans'; + st.textContent = '*,*::before,*::after{transition:none!important}'; + document.head.appendChild(st); + } + if (t === 'light') document.documentElement.removeAttribute('data-theme'); + else document.documentElement.setAttribute('data-theme', t); + }, theme); + await new Promise((r) => setTimeout(r, 120)); +} + +async function gotoPage(page, base, url) { + await page.goto(base + url, { waitUntil: 'networkidle2', timeout: 120000 }); + await new Promise((r) => setTimeout(r, 500)); +} + +async function ensureReader(page, base) { + // Reader sign-up with a throw-away test address; wrangler dev only (local KV). + // The first request after `wrangler pages dev` starts compiles the functions: allow it time, retry once. + for (let attempt = 0; attempt < 2; attempt++) { + try { await page.goto(base + '/read/01/', { waitUntil: 'domcontentloaded', timeout: 90000 }); break; } catch (e) { if (attempt) throw e; } + } + return page.evaluate(async () => { + const r = await fetch('/api/reader', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'mobile-check@example.test', updates: false, chapter: '01' }), credentials: 'same-origin' }); + return r.status; + }); +} + +export async function main(argv = process.argv) { + const opt = parseArgs(argv); + let puppeteer; + try { puppeteer = require('puppeteer-core'); } catch { console.error('puppeteer-core missing: npm install --no-save puppeteer-core'); process.exit(2); } + const chromePath = process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; + if (!fs.existsSync(chromePath)) { console.error('Chrome not found at ' + chromePath + ' (set CHROME_PATH)'); process.exit(2); } + const axeSource = fs.readFileSync(require.resolve('axe-core/axe.min.js'), 'utf8'); + const pages = opt.pages || PAGES; + const devices = opt.devices || DEFAULT_DEVICES; + const browser = await puppeteer.launch({ executablePath: chromePath, headless: 'new', args: ['--no-first-run', '--hide-scrollbars'] }); + const results = []; + let fails = 0, warns = 0; + try { + const readerPage = await browser.newPage(); + let status = 0; + try { status = await ensureReader(readerPage, opt.base); } catch (e) { console.error('(reader sign-up failed: ' + e.message.split('\n')[0] + ')'); } + if (status !== 200) console.error(`(reader sign-up returned ${status}; /read/NN/full will show the gate)`); + const anonCtx = await browser.createBrowserContext(); + const anonPage = await anonCtx.newPage(); + // Console errors (a CSP refusal shows up here) fail the run. + const consoleErrors = new Map(); + for (const pg of [readerPage, anonPage]) { + consoleErrors.set(pg, []); + pg.on('console', (m) => { if (m.type() === 'error' && !/Failed to load resource/.test(m.text())) consoleErrors.get(pg).push(m.text().slice(0, 160)); }); + pg.on('pageerror', (e) => consoleErrors.get(pg).push('pageerror: ' + e.message.slice(0, 160))); + } + for (const dev of devices) { + const d = DEVICES[dev]; + if (!d) { console.error('unknown device ' + dev); continue; } + for (const pg of [readerPage, anonPage]) { + await pg.setUserAgent(UA[d.ua]); + await pg.setViewport({ width: d.w, height: d.h, deviceScaleFactor: d.dpr, isMobile: true, hasTouch: true, isLandscape: !!d.landscape }); + } + for (const url of pages) { + const page = /\/full\/?$/.test(url) ? readerPage : anonPage; // gate pages must be seen signed out + const rec = { device: dev, w: d.w, url, fails: [], warns: [] }; + try { + consoleErrors.get(page).length = 0; + await gotoPage(page, opt.base, url); + const ov = await overflowCheck(page); + rec.vw = ov.vw; rec.scrollW = ov.scrollW; + if (ov.scrollW > ov.vw + 1) rec.fails.push(`overflow-x: page is ${ov.scrollW}px wide in a ${ov.vw}px viewport`); + const m = await measurePage(page, 44); + rec.offenders = m.offenders; rec.clipped = m.clipped; + if (m.offenders.length) rec.fails.push(`${m.offenders.length} element(s) pass the right/left edge: ` + m.offenders.slice(0, 4).map((o) => `${o.el}[${o.left}..${o.right}] "${o.text}"`).join('; ')); + // Group by the clipping box: a marquee or a carousel clips hundreds of children on purpose. + const clipBy = {}; + for (const c of m.clipped) { const k = c.by === 'self' ? c.el : c.by; (clipBy[k] ||= { n: 0, text: c.text }).n++; } + rec.clippedBy = clipBy; + const clipKeys = Object.keys(clipBy); + if (clipKeys.length) rec.warns.push(`content clipped by overflow:hidden in ${clipKeys.length} box(es): ` + clipKeys.slice(0, 6).map((k) => `${k} (${clipBy[k].n}) "${clipBy[k].text}"`).join('; ')); + const hard = m.small.filter((s) => !s.inline); + rec.small = m.small; + if (hard.length) rec.fails.push(`${hard.length} tap target(s) under 44px: ` + hard.slice(0, 30).map((s) => `${s.el} ${s.w}x${s.h} "${s.text}"`).join('; ')); + const inl = m.small.filter((s) => s.inline); + if (inl.length) rec.warns.push(`${inl.length} inline link(s) under 44px tall (exempt by WCAG, listed for information)`); + if (m.tiny.length) rec.warns.push(`${m.tiny.length} text node(s) under 12px: ` + [...new Set(m.tiny.map((t) => t.el + ' ' + t.px + 'px'))].slice(0, 5).join('; ')); + rec.tiny = m.tiny; + rec.scrollers = m.scrollers; + if (m.scrollers.length) rec.warns.push(`${m.scrollers.length} horizontal scroller(s) hiding content: ` + m.scrollers.slice(0, 4).map((x) => `${x.el} ${x.clientW}→${x.scrollW}`).join('; ')); + if (m.smallInputs.length) rec.fails.push(`${m.smallInputs.length} text field(s) under 16px (iOS zooms on focus): ` + m.smallInputs.slice(0, 4).map((x) => `${x.el} ${x.px}px`).join('; ')); + if (!/viewport-fit=cover/.test(m.viewportMeta)) rec.warns.push('viewport meta lacks viewport-fit=cover (safe-area insets stay 0 on notched iPhones)'); + rec.sticky = m.sticky; + if (opt.scrollDock) { + const dk = await dockCheck(page); + rec.dock = dk; + if (dk && dk.hits.length) rec.fails.push('dock bar covers content at the bottom: ' + dk.hits.map((h) => h.el + ' "' + h.text + '"').join('; ')); + if (dk) for (const t of dk.targets) if (t.w < 44 || t.h < 44) rec.fails.push(`dock control ${t.el} is ${t.w}x${t.h} (under 44px)`); + } + if (consoleErrors.get(page).length) rec.fails.push('console errors: ' + consoleErrors.get(page).slice(0, 3).join(' | ')); + if (opt.axe) { + const themes = (opt.axeAll || dev === 'iphone-se') ? opt.themes : ['light']; + rec.axe = {}; + for (const t of themes) { + await setTheme(page, t); + const v = await runAxe(page, axeSource); + rec.axe[t] = v; + if (v.length) rec.fails.push(`axe (${t}): ` + v.map((x) => `${x.id}×${x.n} ${x.sample}`).join('; ')); + } + await setTheme(page, 'light'); + } + if (opt.shots) { + fs.mkdirSync(opt.shots, { recursive: true }); + const name = `${url === '/' ? 'home' : url.replace(/^\//, '').replace(/\//g, '_')}-${dev}`; + await page.evaluate(() => window.scrollTo(0, 0)); + const h = await page.evaluate(() => Math.min(document.documentElement.scrollHeight, 12000)); + for (let y = 0, i = 1; y < h; y += opt.sliceH, i++) { + await page.screenshot({ path: path.join(opt.shots, `${name}-${String(i).padStart(2, '0')}.jpg`), type: 'jpeg', quality: 55, captureBeyondViewport: true, clip: { x: 0, y, width: d.w, height: Math.min(opt.sliceH, h - y) } }); + } + } + } catch (e) { + rec.fails.push('error: ' + e.message.split('\n')[0]); + } + fails += rec.fails.length; warns += rec.warns.length; + results.push(rec); + const tag = rec.fails.length ? 'FAIL' : rec.warns.length ? 'warn' : ' ok '; + console.log(`${tag} ${String(d.w).padStart(3)} ${url}`); + if (opt.verbose || rec.fails.length) for (const f of rec.fails) console.log(' ✗ ' + f); + if (opt.verbose) for (const w of rec.warns) console.log(' ! ' + w); + } + } + } finally { + await browser.close(); + } + if (opt.json) fs.writeFileSync(opt.json, JSON.stringify(results, null, 1)); + console.log(`\n${results.length} page/device runs · ${fails} failure(s) · ${warns} warning(s)`); + if (fails && !opt.noFail) process.exit(1); +} + +if (import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) main();