Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions e2e/header-overflow.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,40 @@ test.describe('Header overflow — More dropdown', () => {
});
});

// The packer fills the row in canonical order, so the one slot a 320px bar
// has went to Best whichever feed you opened — the active pill was reachable
// only by opening the menu it had been packed into. Header pins the active
// item now; this is that fix meeting a real ResizeObserver.
test.describe('Header overflow — the active feed keeps its pill', () => {
test.use({ viewport: { width: 320, height: 568 } });

test.beforeEach(async ({ page }) => {
await setupApiMocks(page);
});

// Label, not route key: New lives at /newest and renders as "new".
for (const { route, label } of [
{ route: '/show', label: 'show' },
{ route: '/ask', label: 'ask' },
{ route: '/newest', label: 'new' },
]) {
test(`${label} is in the bar, not the menu`, async ({ page }) => {
await page.goto(`/#${route}`);

// The trigger only renders once the packer has measured, so waiting on
// it also proves the row overflowed — without that, a bar wide enough
// for every tab would pass this test without exercising anything.
await expect(page.getByRole('button', { name: 'More tabs' })).toBeVisible();

const pill = page
.getByRole('navigation', { name: 'Sections' })
.getByRole('link', { name: label });
await expect(pill).toBeVisible();
await expect(pill).toHaveAttribute('aria-current', 'page');
});
}
});

test.describe('Theme toggle — accessible label', () => {
test.beforeEach(async ({ page }) => {
await setupApiMocks(page);
Expand Down
45 changes: 41 additions & 4 deletions src/components/Header.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,16 @@ interface MockPackedNavKeys {
hidden: string[];
showOverflow: boolean;
}
interface MockPackableItem {
key: string;
pinned?: boolean;
}
// `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 } => ({
(): { state: MockPackedNavKeys; lastItems: MockPackableItem[] } => ({
state: { visible: [], hidden: [], showOverflow: false },
lastItems: [],
}),
);

Expand All @@ -35,10 +42,11 @@ vi.mock('../hooks/usePackedNav', () => ({
// actual input items and returns the matching object. The default
// empty-state branch returns the full input untouched (= everything
// visible, no overflow) so unrelated tests keep finding all nav links.
usePackedNav: <T extends { key: string }>(
usePackedNav: <T extends MockPackableItem>(
_ref: unknown,
items: T[],
): { visible: T[]; hidden: T[]; showOverflow: boolean } => {
mockPackedNav.lastItems = items;
if (mockPackedNav.state.visible.length === 0 && !mockPackedNav.state.showOverflow) {
return { visible: items, hidden: [], showOverflow: false };
}
Expand Down Expand Up @@ -358,8 +366,8 @@ describe('Header', () => {

describe('nav DOM order', () => {
// Locks the canonical packing rule: when an active contextual pill
// exists, it lives at index 0 of the <nav> children (so usePackedNav,
// which always keeps items[0] visible, preserves it as the row narrows).
// exists, it lives at index 0 of the <nav> children (a narrow row keeps
// it because it is the active item, not because of its index).
// The 4 feed tabs follow in fixed Best → Show → Ask → New order — we
// never reorder feeds based on which one is active, since that would
// cause jarring reflow as users move between them.
Expand Down Expand Up @@ -422,6 +430,35 @@ describe('Header', () => {
});
});

describe('packing priority', () => {
// The counterpart to the fixed order above: order stays canonical, so the
// active tab can only survive a narrow row by being pinned. Asserted on
// the packer's input because the packer itself is mocked here — see
// usePackedNav.test.ts for what pinning does, and e2e/header-overflow
// for the two meeting in a real viewport.
const pinnedKeys = () =>
mockPackedNav.lastItems.filter((i) => i.pinned).map((i) => i.key);

it.each([
['/best', 'best'],
['/show', 'show'],
['/ask', 'ask'],
['/newest', 'newest'],
['/submitted/pg', 'user'],
['/from/example.com', 'from'],
])('pins the active item on %s', (route, expected) => {
render(<Header />, { initialEntries: [route] });

expect(pinnedKeys()).toEqual([expected]);
});

it('pins nothing on a route with no active tab', () => {
render(<Header />, { initialEntries: ['/'] });

expect(pinnedKeys()).toEqual([]);
});
});

describe('More dropdown (overflow menu)', () => {
// The packing hook is mocked at the module level above. These tests
// configure it to simulate a viewport too narrow to fit all nav items,
Expand Down
13 changes: 8 additions & 5 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
import { useScrollDirection } from '../hooks/useScrollDirection';
import { useScrollContainer } from '../hooks/useScrollContainer';
import { useIsMobile } from '../hooks/useIsMobile';
import { usePackedNav } from '../hooks/usePackedNav';
import { usePackedNav, type PackableItem } from '../hooks/usePackedNav';
import { clearListSessionState } from '../utils/itemCache';
import { prefersReducedMotion } from '../utils/prefersReducedMotion';
import {
Expand Down Expand Up @@ -89,10 +89,10 @@ const OVERFLOW_BUDGET = SEPARATOR_SLOT + MORE_PILL_WIDTH;
// when computing whether the next item still fits.
const NAV_GAP = 4;

// Per-render packable nav-item shape — `usePackedNav` is generic over the
// minimum `{ width }` shape, so we attach the full NavItemSpec on the same
// object and read it straight off the result without a key-based lookup.
type PackableNavItem = NavItemSpec & { width: number };
// Per-render packable nav-item shape — `usePackedNav` is generic over its
// minimum shape, so we attach the full NavItemSpec on the same object and
// read it straight off the result without a key-based lookup.
type PackableNavItem = NavItemSpec & PackableItem;

// An explicit `behavior: 'smooth'` overrides CSS `scroll-behavior`, so the
// global reduced-motion rule in index.css can't neutralize it — gate it here.
Expand All @@ -115,11 +115,14 @@ export function Header() {
);

// Attach width estimates. ICON_EXTRA only at md+ (icons hidden on mobile).
// Pinning the active tab keeps it in the bar on a narrow row: canonical
// order would otherwise spend the only slot on Best whatever feed you open.
const packableItems: PackableNavItem[] = useMemo(
() =>
navItems.map((it) => ({
...it,
width: PILL_WIDTH_NO_ICON[it.key] + (isMobile ? 0 : ICON_EXTRA),
pinned: it.isActive,
})),
[navItems, isMobile],
);
Expand Down
61 changes: 61 additions & 0 deletions src/hooks/usePackedNav.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,67 @@ describe('usePackedNav', () => {
expect(keys(result.current.hidden)).toEqual(['b', 'c', 'd']);
});

// Header's four feed tabs at their mobile widths — the row this hook was
// written for, reused below so the numbers mean something.
const FEEDS: TestItem[] = [
{ key: 'best', width: 56 },
{ key: 'show', width: 60 },
{ key: 'ask', width: 50 },
{ key: 'newest', width: 52 },
];
const pin = (key: string) =>
FEEDS.map((it) => (it.key === key ? { ...it, pinned: true } : it));

it('spends the only slot on the pinned item, not the first one', () => {
// A 320px phone: nav ≈ 200 wide, budget = 200 - 105 = 95, so exactly one
// tab fits. Unpinned that is always best — which is the whole bug: open
// Ask from the More menu and the bar still reads Best.
const { result } = renderHook(() =>
usePackedNav(makeFakeRef(200), pin('ask'), { overflowWidth: 105, gap: 4 }),
);

expect(keys(result.current.visible)).toEqual(['ask']);
expect(keys(result.current.hidden)).toEqual(['best', 'show', 'newest']);
expect(result.current.showOverflow).toBe(true);
});

it('keeps the row in the caller order around a pinned item', () => {
// Total is 230, so 220 still overflows. Budget = 115: newest (52) is
// claimed, best (56) then fits at 112 and show would overshoot at 176.
// Pinning must not promote newest to the front — feeds never reorder
// as you move between them.
const { result } = renderHook(() =>
usePackedNav(makeFakeRef(220), pin('newest'), { overflowWidth: 105, gap: 4 }),
);

expect(keys(result.current.visible)).toEqual(['best', 'newest']);
expect(keys(result.current.hidden)).toEqual(['show', 'ask']);
});

it('drops a pinned item that cannot fit the budget alone', () => {
// Budget = 100 - 50 = 50. The pin asks for 200 — honouring it would
// overflow the row, which is worse than losing the active pill.
const items: TestItem[] = [
{ key: 'tiny', width: 20 },
{ key: 'huge', width: 200, pinned: true },
];
const { result } = renderHook(() =>
usePackedNav(makeFakeRef(100), items, { overflowWidth: 50, gap: 4 }),
);

expect(keys(result.current.visible)).toEqual(['tiny']);
expect(keys(result.current.hidden)).toEqual(['huge']);
});

it('ignores the pin when everything fits', () => {
const { result } = renderHook(() =>
usePackedNav(makeFakeRef(400), pin('ask'), { overflowWidth: 105, gap: 4 }),
);

expect(keys(result.current.visible)).toEqual(['best', 'show', 'ask', 'newest']);
expect(result.current.showOverflow).toBe(false);
});

it('repacks when items array changes (e.g. active context changes)', () => {
// Start with comments-led ordering at a width that fits all 4.
const { result, rerender } = renderHook(
Expand Down
48 changes: 32 additions & 16 deletions src/hooks/usePackedNav.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ import { useLayoutEffect, useMemo, useState, type RefObject } from 'react';
/** Item with an estimated rendered width (px). */
export interface PackableItem {
width: number;
/**
* Claims a slot before the left-to-right pass; only the first such item
* does. The active tab sets this — a row that overflows the pill for the
* page you are on reads as the wrong page.
*/
pinned?: boolean;
}

export interface PackedNav<T extends PackableItem> {
Expand All @@ -25,7 +31,8 @@ const UNMEASURED = Number.POSITIVE_INFINITY;

/**
* Greedy left-to-right nav packing. Hides trailing items into overflow
* when the container shrinks. Generic over `T extends PackableItem`.
* when the container shrinks, keeping a `pinned` item regardless of where
* it sits. Generic over `T extends PackableItem`.
*
* On first render / jsdom, container width = Infinity (all items visible).
*/
Expand Down Expand Up @@ -99,27 +106,36 @@ export function usePackedNav<T extends PackableItem>(

// Overflow case — reserve space for the trigger and pack greedily.
const budget = containerWidth - options.overflowWidth;
const visible: T[] = [];
const taken = new Set<number>();
let used = 0;

// Claimed ahead of the pass, so the last slot in a narrow row goes to
// the pinned item rather than to whatever sorts first. Skipped when it
// cannot fit alone — nothing is worth overflowing the row.
const pinned = items.findIndex((it) => it.pinned);
if (pinned !== -1 && items[pinned].width <= budget) {
taken.add(pinned);
used = items[pinned].width;
}

for (let i = 0; i < items.length; i++) {
const next = used + (i > 0 ? options.gap : 0) + items[i].width;
if (next <= budget) {
visible.push(items[i]);
used = next;
} else {
// Stop on first non-fitting item. We don't try later items even
// if they're smaller — a "best Show then skip Ask then take More"
// pattern would shuffle items unpredictably as the viewport
// changes. Strict left-to-right greedy keeps order stable.
break;
}
if (taken.has(i)) continue;
const next = used + (taken.size > 0 ? options.gap : 0) + items[i].width;
// Stop on first non-fitting item. We don't try later items even
// if they're smaller — a "best Show then skip Ask then take More"
// pattern would shuffle items unpredictably as the viewport
// changes. Strict left-to-right greedy keeps order stable.
if (next > budget) break;
taken.add(i);
used = next;
}

// Filtered rather than sliced: the pinned item can sit past the run
// that fits, and both lists must stay in the caller's order.
return {
visible,
hidden: items.slice(visible.length),
showOverflow: true,
visible: items.filter((_, i) => taken.has(i)),
hidden: items.filter((_, i) => !taken.has(i)),
showOverflow: taken.size < items.length,
};
}, [items, containerWidth, options.gap, options.overflowWidth]);
}