diff --git a/e2e/fixtures/layout-helpers.ts b/e2e/fixtures/layout-helpers.ts index e91d87e..e17f07e 100644 --- a/e2e/fixtures/layout-helpers.ts +++ b/e2e/fixtures/layout-helpers.ts @@ -7,6 +7,49 @@ interface CenteredBetweenChromeOptions { bottomSelector?: string; } +/** + * Approximate a raised default font size by moving the root font size that every + * `rem` resolves against. Only an approximation: `rem` in a media query resolves + * against the browser's *initial* size, which no stylesheet can reach, so the + * breakpoints stay put. layout-tokens.spec.ts covers that half over CDP. + */ +export async function enlargeRootFont(page: Page, px: number) { + await page.addInitScript((size) => { + const apply = () => { + const style = document.createElement('style'); + style.textContent = `html{font-size:${size}px}`; + document.head.appendChild(style); + }; + if (document.head) apply(); + else document.addEventListener('DOMContentLoaded', apply); + }, px); +} + +/** + * Emulate the browser's own default font size — the setting itself, so `rem` + * media queries move with it, which {@link enlargeRootFont} cannot reach. + * Chromium only; skip the calling test elsewhere. + */ +export async function emulateBrowserFontSize(page: Page, px: number) { + const cdp = await page.context().newCDPSession(page); + await cdp.send('Page.setFontSizes', { fontSizes: { standard: px, fixed: px } }); +} + +/** + * Emulate Android's text scaling, which is neither of the above: it inflates + * glyphs and leaves every `rem` length — padding, gaps, icons — where it was. + * Applied after load on purpose, so a nav that only re-packs when its own box + * changes size fails this; the text growing inside it has to be enough. + */ +export async function scaleNavTextOnly(page: Page, factor: number) { + await page.evaluate((size) => { + const style = document.createElement('style'); + // `text-sm` is 14px at a 16px root. + style.textContent = `header nav a, header nav span, header nav button { font-size: ${size}px !important; }`; + document.head.appendChild(style); + }, 14 * factor); +} + /** * Force the app into its offline-bar state after the route has already loaded. * This lets geometry assertions include the fixed bottom chrome without making diff --git a/e2e/header-overflow.spec.ts b/e2e/header-overflow.spec.ts index 68aeb84..ab6a06d 100644 --- a/e2e/header-overflow.spec.ts +++ b/e2e/header-overflow.spec.ts @@ -1,5 +1,44 @@ import { test, expect, type Page } from '@playwright/test'; import { setupApiMocks } from './fixtures/api-mocks'; +import { + emulateBrowserFontSize, + enlargeRootFont, + scaleNavTextOnly, +} from './fixtures/layout-helpers'; + +/** + * Where the packed row sits against the nav that holds it. `escaped` is how far + * it breaks out leftward, which is the direction `justify-end` sends an overrun + * — across the logo. Read off the real rects: those report layout, so the CSS + * clip cannot hide a packing regression from these tests. + */ +const navBounds = (page: Page) => + page.evaluate(() => { + const nav = document.querySelector('header nav')!; + const navLeft = nav.getBoundingClientRect().left; + const leftmost = Math.min( + ...[...nav.children].map((c) => c.getBoundingClientRect().left), + ); + return { + escaped: navLeft - leftmost, + leftmost, + logoRight: document.querySelector('header a[href="#/"]')!.getBoundingClientRect().right, + }; + }); + +/** The pill for the page you are on, which is the one that must never be lost. */ +const activePill = (page: Page) => + page.getByRole('navigation', { name: 'Sections' }).locator('[aria-current="page"]'); + +/** + * The hidden element the packer scales its glyph estimates against. Read + * through `evaluate` rather than a locator: it is `visibility: hidden`, which + * no amount of waiting will ever make visible. + */ +const probeWidth = (page: Page) => + page.evaluate( + () => document.querySelector('header nav span.absolute')!.getBoundingClientRect().width, + ); // End-to-end coverage for the responsive header's "More" overflow dropdown. // @@ -163,6 +202,195 @@ test.describe('Header overflow — the active feed keeps its pill', () => { } }); +// `comments` is the widest pill at 91.5px, and the trigger used to reserve +// 105px of a 320px phone's 200px nav for its separator and its label — so the +// pill the reader was actually looking at lost the row by a single pixel. +test.describe('Header overflow — the widest pill still fits a phone', () => { + test.use({ viewport: { width: 320, height: 568 } }); + + test('the comments pill is in the bar, not the menu', async ({ page }) => { + await setupApiMocks(page); + // 1002 is a comment, so the header's contextual cascade picks `comments`. + await page.goto('/#/item/1002'); + + // Same reasoning as the feed guards above: the trigger's presence is what + // proves the row overflowed and the pill won a contested slot. + await expect(page.getByRole('button', { name: 'More tabs' })).toBeVisible(); + + const active = page + .getByRole('navigation', { name: 'Sections' }) + .locator('[aria-current="page"]'); + await expect(active).toHaveText('comments'); + }); +}); + +// Two shapes where the row outgrew the nav rather than the menu. Because the +// nav is `justify-end`, the excess spills leftward across the logo: at 412px +// and 150% the leading pill sat 78px outside the nav, and below ~200px the +// trigger's own label did the same. Measured on the real rects, which report +// layout, so the CSS clip cannot mask a packing regression here. +test.describe('Header overflow — the row stays inside the nav', () => { + for (const shape of [ + { label: '412px at a 150% font', width: 412, height: 800, rootPx: 24 }, + { label: '164px at the default font', width: 164, height: 809, rootPx: null }, + ]) { + test(`no pill escapes the nav at ${shape.label}`, async ({ page }) => { + if (shape.rootPx) await enlargeRootFont(page, shape.rootPx); + await page.setViewportSize({ width: shape.width, height: shape.height }); + await setupApiMocks(page); + await page.goto('/#/best'); + + // Polled because the first frame legitimately renders every item: the + // packer has no width until it has measured one. A pixel of slack for + // subpixel layout — the regressions here were 78px and 32px. + await expect + .poll(async () => (await navBounds(page)).escaped, { + message: 'the packed row must settle inside the nav', + }) + .toBeLessThanOrEqual(1); + + const { leftmost, logoRight } = await navBounds(page); + expect(leftmost).toBeGreaterThan(logoRight); + + // Both shapes overflow, so the trigger proves the packer engaged at all + // — without it a bar wide enough for every tab would pass unexercised. + await expect(page.getByRole('button', { name: 'More tabs' })).toBeVisible(); + }); + } +}); + +// Android scales text without moving a single `rem` length, so the nav keeps +// its width, no observer of the nav fires, and the packer's estimates go +// quietly stale. On a comment view at 320px that spilled the row 10px over the +// logo at 1.3× and 27px at 1.5× — and being right-aligned, the pill it clipped +// was the active one. The hidden probe in the nav is what notices. +test.describe('Header overflow — text that grows on its own', () => { + test.use({ viewport: { width: 320, height: 568 } }); + + for (const factor of [1.3, 1.5]) { + test(`the active pill survives ${factor}× text, inside the nav`, async ({ page }) => { + await setupApiMocks(page); + // 1002 is a comment: the widest pill, and the thinnest slack. + await page.goto('/#/item/1002'); + await expect(activePill(page)).toHaveText('comments'); + + await scaleNavTextOnly(page, factor); + + await expect + .poll(async () => (await navBounds(page)).escaped, { + message: 'the row must re-pack when only the text inside it grows', + }) + .toBeLessThanOrEqual(1); + + // Containment alone would also be satisfied by dropping every pill. + await expect(activePill(page)).toHaveText('comments'); + }); + } +}); + +// The other half of the same question, and the one the injected root font in +// `enlargeRootFont` cannot ask: a real font setting also moves the `rem` media +// queries, so the layout around the nav changes shape at the same time. +test.describe("Header overflow — the browser's own font setting", () => { + test.use({ viewport: { width: 412, height: 800 } }); + + test('a 24px default keeps the active pill in a contained row', async ({ + page, + browserName, + }) => { + test.skip(browserName !== 'chromium', 'only Chromium can emulate the setting'); + await emulateBrowserFontSize(page, 24); + await setupApiMocks(page); + await page.goto('/#/item/1002'); + + // The premise everything above rests on: no stylesheet of ours pins the + // root font size. One `html { font-size: 16px }` would overrule the reader + // outright — the packer would read 16 and be right, and every `rem` in the + // app would quietly stop scaling. Nothing else in the suite would notice. + expect( + await page.evaluate(() => getComputedStyle(document.documentElement).fontSize), + ).toBe('24px'); + + await expect + .poll(async () => (await navBounds(page)).escaped, { + message: 'the packed row must settle inside the nav', + }) + .toBeLessThanOrEqual(1); + + await expect(activePill(page)).toHaveText('comments'); + await expect(page.getByRole('button', { name: 'More tabs' })).toBeVisible(); + }); +}); + +// The probe stands in for a pill's label, and is a reading of the reader's +// text size only for as long as it renders like one: the same typography, and +// a width that owes nothing to the box around it. The second is why it is +// positioned out of flow — at 164px the nav is 44px, narrower than the word +// itself, and a probe that took its container's width instead would report a +// reader who had shrunk their text, which is the direction that overfills a +// row rather than the safe one. +test.describe('Header overflow — the probe reads like a pill', () => { + test('it measures the active pill, less that pill’s padding', async ({ page }) => { + await setupApiMocks(page); + await page.setViewportSize({ width: 320, height: 568 }); + await page.goto('/#/item/1002'); + await expect(activePill(page)).toHaveText('comments'); + + const { probe, glyphs } = await page.evaluate(() => { + const nav = document.querySelector('header nav')!; + const pill = nav.querySelector('[aria-current="page"]')!; + return { + probe: nav.querySelector('span.absolute')!.getBoundingClientRect().width, + // `px-2.5` a side; what is left is the label itself. + glyphs: pill.getBoundingClientRect().width - 20, + }; + }); + + // A relation, not a number: what the probe measures is a platform's font, + // and TEXT_PROBE_BASELINE is one platform's reading of it. This machine + // renders `comments` at 71.5px and CI's Linux stack at 67.7px, both + // correct — the scale between them is the whole point of measuring. + expect(probe).toBeCloseTo(glyphs, 1); + }); + + test('it measures its own word, not the narrower nav around it', async ({ page }) => { + await setupApiMocks(page); + await page.setViewportSize({ width: 900, height: 800 }); + await page.goto('/#/best'); + await expect(activePill(page)).toHaveText('best'); + const roomy = await probeWidth(page); + + await page.setViewportSize({ width: 164, height: 809 }); + await expect(page.getByRole('button', { name: 'More tabs' })).toBeVisible(); + + // 44px of nav against a word wider than that: an in-flow probe would be + // squeezed to its container and read as a reader who shrank their text. + expect(roomy).toBeGreaterThan(44); + expect(await probeWidth(page)).toBeCloseTo(roomy, 1); + }); +}); + +test.describe('Header overflow — the trigger stays a target', () => { + test.use({ viewport: { width: 320, height: 568 } }); + + test('the bare chevron is as tall as the pills beside it', async ({ page }) => { + await setupApiMocks(page); + await page.goto('/#/item/1002'); + + const trigger = page.getByRole('button', { name: 'More tabs' }); + await expect(trigger).toBeVisible(); + const box = (await trigger.boundingBox())!; + + // Dropping the label drops the line box with it, leaving a 14px icon to + // set the height: 22px, under the 24×24 WCAG 2.5.8 (AA) asks for. + expect(box.height).toBeGreaterThanOrEqual(24); + expect(box.width).toBeGreaterThanOrEqual(24); + + const pill = (await activePill(page).boundingBox())!; + expect(box.height).toBeCloseTo(pill.height, 0); + }); +}); + test.describe('Theme toggle — accessible label', () => { test.beforeEach(async ({ page }) => { await setupApiMocks(page); diff --git a/e2e/layout-tokens.spec.ts b/e2e/layout-tokens.spec.ts index a38b6e3..790b04b 100644 --- a/e2e/layout-tokens.spec.ts +++ b/e2e/layout-tokens.spec.ts @@ -1,6 +1,10 @@ import { test, expect, type Page } from '@playwright/test'; import { setupApiMocks, stubNotFoundUser } from './fixtures/api-mocks'; -import { expectChromeTokenToMatch, setOfflineAndWaitForBar } from './fixtures/layout-helpers'; +import { + enlargeRootFont, + expectChromeTokenToMatch, + setOfflineAndWaitForBar, +} from './fixtures/layout-helpers'; // `--header-height` and `--network-bar-height` duplicate, by hand, heights that // Tailwind utilities produce on the components. Nothing in the build connects @@ -20,24 +24,6 @@ const BREAKPOINTS = [ { label: 'xl', width: 1400, height: 900 }, ]; -/** - * Approximate a raised default font size by moving the root font size that every - * `rem` resolves against. Only an approximation: `rem` in a media query resolves - * against the browser's *initial* size, which no stylesheet can reach, so the - * breakpoints stay put. The Chromium CDP test below covers that half. - */ -async function enlargeRootFont(page: Page, px: number) { - await page.addInitScript((size) => { - const apply = () => { - const style = document.createElement('style'); - style.textContent = `html{font-size:${size}px}`; - document.head.appendChild(style); - }; - if (document.head) apply(); - else document.addEventListener('DOMContentLoaded', apply); - }, px); -} - /** * The theme toggle IS the control row that sets the header's height, so its paint * is the readiness signal. Fonts too: a face swap re-measures the whole bar. diff --git a/e2e/touch-feel.spec.ts b/e2e/touch-feel.spec.ts index 716e54c..7211fba 100644 --- a/e2e/touch-feel.spec.ts +++ b/e2e/touch-feel.spec.ts @@ -37,6 +37,12 @@ test.describe('Overscroll containment', () => { // be scoped to that class — asserting the class is gone proves it isn't. await page.goto('/#/user/pg'); + // The class comes off as the profile mounts, so wait for the profile + // itself: on a loaded runner that mount is the slow part, and a poll over + // the class alone spends its whole budget waiting for a render it cannot + // see. That cost a CI run 10.4s here against 2.4s on a quiet machine. + await expect(page.getByRole('heading', { level: 1, name: 'pg' })).toBeVisible(); + await expect .poll(() => page.evaluate(() => ({ diff --git a/src/components/Header.test.tsx b/src/components/Header.test.tsx index e8a2ca5..23f6457 100644 --- a/src/components/Header.test.tsx +++ b/src/components/Header.test.tsx @@ -30,12 +30,22 @@ interface MockPackableItem { // `lastItems` records what Header hands the packer, so the pinning contract // can be asserted without the real measurement the mock stands in for. const mockPackedNav = vi.hoisted( - (): { state: MockPackedNavKeys; lastItems: MockPackableItem[] } => ({ + (): { + state: MockPackedNavKeys; + lastItems: MockPackableItem[]; + lastOverflowWidth: number; + } => ({ state: { visible: [], hidden: [], showOverflow: false }, lastItems: [], + lastOverflowWidth: -1, }), ); +// Mobile is a render-time branch here, not a media query, so the chrome the +// packer is charged for and the chrome that renders can be asserted together. +const mockIsMobile = vi.hoisted((): { value: boolean } => ({ value: false })); +vi.mock('../hooks/useIsMobile', () => ({ useIsMobile: () => mockIsMobile.value })); + vi.mock('../hooks/usePackedNav', () => ({ // The hook is now generic — it returns full item slices, not key // strings — so the mock looks up each configured key against the @@ -45,8 +55,10 @@ vi.mock('../hooks/usePackedNav', () => ({ usePackedNav: ( _ref: unknown, items: T[], + options: { overflowWidth: number }, ): { visible: T[]; hidden: T[]; showOverflow: boolean } => { mockPackedNav.lastItems = items; + mockPackedNav.lastOverflowWidth = options.overflowWidth; if (mockPackedNav.state.visible.length === 0 && !mockPackedNav.state.showOverflow) { return { visible: items, hidden: [], showOverflow: false }; } @@ -452,10 +464,86 @@ describe('Header', () => { expect(pinnedKeys()).toEqual([expected]); }); - it('pins nothing on a route with no active tab', () => { - render(
, { initialEntries: ['/'] }); + it('pins nothing on a route with no active tab', () => { + render(
, { initialEntries: ['/'] }); + + expect(pinnedKeys()).toEqual([]); + }); + }); + + // Pinning only helps if the pinned pill can afford a slot, and on a phone + // the trigger's own chrome was eating one. Both halves are asserted here + // because they have to move together: charge for a label that no longer + // renders and the row loses a pill for nothing. + describe('mobile chrome', () => { + afterEach(() => { + mockIsMobile.value = false; + mockPackedNav.state = { visible: [], hidden: [], showOverflow: false }; + }); + + it('leaves the widest pill room on a 320px phone', () => { + // Measured, not derived from the constants under test: 320px of + // viewport leaves the nav 200px once the logo, the theme toggle and + // the header padding have taken theirs, and `comments` renders 91.5px + // there — the pill the old 105px reservation hid by a single pixel. + const NAV_AT_320 = 200; + const WIDEST_PILL = 96; + mockIsMobile.value = true; + + render(
, { initialEntries: ['/best'] }); + + expect(NAV_AT_320 - mockPackedNav.lastOverflowWidth).toBeGreaterThanOrEqual(WIDEST_PILL); + }); - expect(pinnedKeys()).toEqual([]); + it('still buys the separator and the label where there is room', () => { + render(
, { initialEntries: ['/best'] }); + const desktop = mockPackedNav.lastOverflowWidth; + mockIsMobile.value = true; + + render(
, { initialEntries: ['/best'] }); + + expect(mockPackedNav.lastOverflowWidth).toBeLessThan(desktop); + }); + + it('renders the trigger as a bare chevron, and no separator beside it', () => { + mockIsMobile.value = true; + mockPackedNav.state = { + visible: ['best'], + hidden: ['show', 'ask', 'newest'], + showOverflow: true, + }; + + render(
, { initialEntries: ['/best'] }); + + // The name survives the label: it comes from `aria-label`. + const trigger = screen.getByRole('button', { name: 'More tabs' }); + expect(within(trigger).queryByText('more')).toBeNull(); + // Same hairline query as the overflow tests above. + const nav = screen.getByRole('navigation', { name: 'Sections' }); + expect(nav.querySelector('span.w-px')).toBeNull(); + }); + }); + + describe('text probe', () => { + it('carries the same typography as the pills it stands in for', () => { + // Its width is only a reading of the reader's text size while it is set + // in the pills' own font — restyle them and this is the test that says + // so, before the packer starts measuring the wrong thing in silence. + render(
, { initialEntries: ['/best'] }); + + const nav = screen.getByRole('navigation', { name: 'Sections' }); + const probe = nav.querySelector('span.absolute'); + const pill = within(nav).getByRole('link', { name: 'best' }); + + expect(probe).not.toBeNull(); + expect(probe!.getAttribute('aria-hidden')).toBe('true'); + for (const cls of ['text-sm', 'font-medium', 'capitalize']) { + expect(pill.className).toContain(cls); + expect(probe!.className).toContain(cls); + } + // The word is in `content`, so no second `comments` lands in the DOM. + expect(probe!.textContent).toBe(''); + expect(probe!.className).toContain("before:content-['comments']"); }); }); @@ -626,9 +714,9 @@ describe('Header', () => { }); const nav = screen.getByRole('navigation', { name: 'Sections' }); - // Query only the hairline separator, not the chevron SVG - // inside the "More" button (which also carries aria-hidden). - const separator = nav.querySelector('span[aria-hidden="true"]'); + // The hairline by its own width, not by `aria-hidden`: the chevron and + // the text probe are hidden from the tree too, and only this is 1px. + const separator = nav.querySelector('span.w-px'); expect(separator).toBeNull(); }); }); diff --git a/src/components/Header.tsx b/src/components/Header.tsx index 76a8b7e..6efa565 100644 --- a/src/components/Header.tsx +++ b/src/components/Header.tsx @@ -69,9 +69,23 @@ const PILL_WIDTH_NO_ICON: Record = { user: 56, from: 56, }; +// 14px icon + its `gap-1.5`, reserved when md+ draws one — which is not +// exactly when `isMobile` says so: that asks 767px in px where `md:` asks +// 48rem. Off a 16px root the two disagree for a band, and both halves of it +// measured safe — above, the icon is reserved and hidden, which only +// over-reserves; below, it renders unreserved, and the band's tightest row +// still had ~200px spare against the ~66px it wanted. const ICON_EXTRA = 20; -// Width budget for the overflow trigger including its leading separator. +// `px-2.5` on both sides. The rest of a pill is its label, and the two are +// split apart because a reader can enlarge one without the other — see +// `PackableItem.textWidth`. Every estimate above carries a little slack over +// what it measures, and keeping the box exact puts all of that slack in the +// label, which is the half that actually varies between fonts. +const PILL_BOX_WIDTH = 20; + +// Width budget for the md+ overflow trigger including its leading separator; +// mobile drops both and pays MOBILE_OVERFLOW_BUDGET below. // Breakdown: // - 4px gap-1 (parent flex) between last visible item and the separator // - 6px mx-1.5 left of the 1px separator line @@ -83,12 +97,33 @@ const ICON_EXTRA = 20; const SEPARATOR_SLOT = 21; const MORE_PILL_WIDTH = 84; const OVERFLOW_BUDGET = SEPARATOR_SLOT + MORE_PILL_WIDTH; +// What is left of the trigger once its box is out: 20px padding, 8px `gap-2` +// and the 14px chevron. Only this part follows the reader's text size. +const MORE_LABEL_WIDTH = MORE_PILL_WIDTH - 42; // Parent flex gap-1 (4px) — must stay in sync with the `gap-1` className // on the