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
45 changes: 36 additions & 9 deletions e2e/fixtures/api-mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,46 @@ function attachFrameBuffering(ws: WebSocketRoute, handler: (raw: string) => void
});
}

// Page 0 of the domain search: the original item + 4 clones (5 total for scrollability).
const mockDomainPage0Hits = [
mockDomainItem,
...Array.from({ length: 4 }, (_, i) => ({
...mockDomainItem,
objectID: String(77770 + i),
title: `Domain Article ${i + 2}`,
})),
];

// Firebase's copy of a story only the Algolia mocks list. The app takes a
// story's title and counts from Firebase once its comments load, so the two
// have to agree.
function firebaseStoryFromHit(hit: typeof mockDomainItem) {
return {
id: Number(hit.objectID),
title: hit.title,
url: hit.url,
by: hit.author,
score: hit.points,
time: hit.created_at_i,
descendants: hit.num_comments,
type: 'story',
};
}

/**
* Build the item lookup table used by the WebSocket mock.
*/
function buildItemsMap(): Record<number, object> {
const algoliaOnlyStories = [
...mockDomainPage0Hits.slice(1),
mockDomainPaginationItem1,
mockDomainPaginationItem2,
mockPaginationItem1,
mockPaginationItem2,
mockPaginationItem3,
];
return {
...Object.fromEntries(algoliaOnlyStories.map(hit => [Number(hit.objectID), firebaseStoryFromHit(hit)])),
12345: mockItem1,
12346: mockItem2,
12347: mockItem3,
Expand Down Expand Up @@ -460,15 +495,7 @@ export async function setupApiMocks(page: Page) {
}
} else if (query) {
if (pageNum === 0) {
// Page 0: original item + 4 generated clones (5 total for scrollability)
hits = [
mockDomainItem,
...Array.from({ length: 4 }, (_, i) => ({
...mockDomainItem,
objectID: String(77770 + i),
title: `Domain Article ${i + 2}`,
})),
];
hits = mockDomainPage0Hits;
nbPages = 2;
} else {
// Page 1: pagination items with unique titles for assertion
Expand Down
6 changes: 4 additions & 2 deletions e2e/fixtures/swipe-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,14 +179,16 @@ export async function smoothScrollAndAwaitSettled(container: Locator, targetLeft
dispatchTouch('touchend', [], [makeTouch(endX)]);
}, { forward: isForward, width: panelWidth });

// Wait for the animation to complete (panel gets .active)
// Wait for the animation to complete (panel gets .active). Long enough
// for WebKit under load: a gesture that lands late after a retry has
// been sent moves the reader a panel further than asked.
try {
await page.waitForFunction((idx) => {
const c = document.querySelector('[data-testid="swipe-container"]');
if (!c) return false;
const panel = c.children[idx] as HTMLElement;
return panel?.classList.contains('active');
}, stepTarget, { timeout: 500 });
}, stepTarget, { timeout: 2000 });
success = true;
} catch {
// Gesture was likely rejected (e.g. programmatic scroll guard still active).
Expand Down
24 changes: 24 additions & 0 deletions e2e/mobile-breakpoint.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,30 @@ test.describe('The first paint, before React', () => {
await page.evaluate(() => document.documentElement.classList.contains('swipe-mode')),
).toBe(true);
});

for (const route of ['/#/best', '/#/item/12345', '/#/from/github.com/rust-lang', '/#/submitted/pg']) {
test(`bets on it for ${route}`, async ({ page }) => {
await page.route('**/*.js', r => r.abort());
await page.goto(route, { waitUntil: 'domcontentloaded' });

expect(
await page.evaluate(() => document.documentElement.classList.contains('swipe-mode')),
).toBe(true);
});
}

// None of these mount a viewer, and the 404 and not-found pages never
// clear the class, so a wrong bet would stay.
for (const route of ['/#/user/pg', '/#/no-such-page', '/#/item/abc', '/#/from/']) {
test(`does not for ${route}`, async ({ page }) => {
await page.route('**/*.js', r => r.abort());
await page.goto(route, { waitUntil: 'domcontentloaded' });

expect(
await page.evaluate(() => document.documentElement.classList.contains('swipe-mode')),
).toBe(false);
});
}
});

test.describe('with a finger, on a viewport only rem calls narrow', () => {
Expand Down
164 changes: 164 additions & 0 deletions e2e/mobile-swipe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,151 @@ test.describe('Mobile Swipe Viewer', () => {
expect(ids.filter((id) => mockTopItemIds.includes(id))).toEqual([]);
});

test('a feed refresh that lands after a swipe keeps the story on screen', async ({ page }) => {
// An hour-old cached Top feed in the reverse of the live order, and Firebase
// reads that take 1.5s, so the refresh lands after the swipe.
await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ delayMs: 1500 }));
await page.addInitScript((ids) => {
const stories = [...ids].reverse().map((id) => ({
id, type: 'story', title: `Cached story ${id}`, url: `https://example.com/${id}`,
points: 1, author: 'someone', createdAt: Date.now() - 3_600_000, commentCount: 0,
}));
localStorage.setItem('feed:top', JSON.stringify({ stories, timestamp: Date.now() - 3_600_000 }));
}, mockTopItemIds);

await page.goto('/#/');
await waitForSwipeReady(page, 2);
const container = page.getByTestId('swipe-container');
const panelWidth = await container.evaluate((el) => el.getBoundingClientRect().width);
await smoothScrollAndAwaitSettled(container, panelWidth);
await waitForScrollAtIndex(page, 1);
const [first, second] = [...mockTopItemIds].reverse();
await expect(page).toHaveURL(new RegExp(`/item/${second}`), { timeout: 5000 });

const panelIds = () => page.locator('[data-item-id]').evaluateAll(
(els) => els.map((el) => Number(el.getAttribute('data-item-id'))),
);
// The refresh has landed once the live ranking's first story is ahead of its third.
await expect.poll(async () => {
const ids = await panelIds();
return ids.indexOf(mockTopItemIds[0]) < ids.indexOf(mockTopItemIds[2]);
}, { timeout: 15000 }).toBe(true);

await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', String(second));
await expect(page).toHaveURL(new RegExp(`/item/${second}`));
expect((await panelIds()).slice(0, 2)).toEqual([first, second]);
});

test('a link to the last story of a cached feed refreshes it without paging back through older days', async ({ page }) => {
// The cached feed already holds the live stories, so the refresh brings no
// new ones, and the link opens the last of them.
await page.addInitScript((ids) => {
const stories = ids.map((id) => ({
id, type: 'story', title: `Cached story ${id}`, url: `https://example.com/${id}`,
points: 1, author: 'someone', createdAt: Date.now() - 3_600_000, commentCount: 0,
}));
localStorage.setItem('feed:top', JSON.stringify({ stories, timestamp: Date.now() - 3_600_000 }));
}, mockTopItemIds);
// Day pages that never run out, as the live API's don't.
let dayRequests = 0;
await page.route(`${ALGOLIA_API}/search*`, async (route) => {
if (!route.request().url().includes('numericFilters')) return route.fallback();
dayRequests += 1;
const base = 900_000 + dayRequests * 10;
await route.fulfill({
json: {
hits: [0, 1, 2].map((i) => ({
objectID: String(base + i), title: `Older story ${base + i}`, url: 'https://example.com/older',
author: 'someone', points: 1, num_comments: 0, created_at_i: Math.floor(Date.now() / 1000) - 86_400 * dayRequests,
_tags: ['story'],
})),
nbHits: 3, page: 0, nbPages: 1, hitsPerPage: 30,
},
});
});

const last = mockTopItemIds[mockTopItemIds.length - 1];
await page.goto(`/#/item/${last}`);
await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', String(last));

// The refresh rewrites the cache once it lands.
const startedAt = Date.now();
await expect.poll(
() => page.evaluate(() => (JSON.parse(localStorage.getItem('feed:top') ?? '{}') as { timestamp?: number }).timestamp ?? 0),
{ timeout: 10_000 },
).toBeGreaterThan(startedAt - 60_000);
await page.waitForTimeout(1000);
expect(dayRequests).toBeLessThan(5);
});

test('a refresh with no new stories drops the cached ones past the reader, so the next page does not repeat them', async ({ page }) => {
// A cache longer than one page, as the desktop list writes: the live front
// page, then the older stories that yesterday's page holds.
const older = Array.from({ length: 9 }, (_, i) => 900_001 + i);
const yesterday = Math.floor(Date.now() / 1000) - 86_400;
await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({
delayMs: 1500,
itemOverrides: Object.fromEntries(older.map((id) => [id, {
id, title: `Older story ${id}`, url: 'https://example.com/older', by: 'someone', score: 1,
time: yesterday, descendants: 0, type: 'story',
}])),
}));
let dayRequests = 0;
await page.route(`${ALGOLIA_API}/search*`, async (route) => {
if (!route.request().url().includes('numericFilters')) return route.fallback();
dayRequests += 1;
const ids = dayRequests === 1 ? older : [0, 1, 2].map((i) => 700_000 + dayRequests * 10 + i);
await route.fulfill({
json: {
hits: ids.map((id) => ({
objectID: String(id), title: `Older story ${id}`, url: 'https://example.com/older',
author: 'someone', points: 1, num_comments: 0, created_at_i: yesterday - 86_400 * (dayRequests - 1),
_tags: ['story'],
})),
nbHits: ids.length, page: 0, nbPages: 1, hitsPerPage: 30,
},
});
});
await page.addInitScript(({ live, older }) => {
const stories = [...live, ...older].map((id) => ({
id, type: 'story', title: `Cached story ${id}`, url: `https://example.com/${id}`,
points: 1, author: 'someone', createdAt: Date.now() - 3_600_000, commentCount: 0,
}));
localStorage.setItem('feed:top', JSON.stringify({ stories, timestamp: Date.now() - 3_600_000 }));
// A reload keeps the history entry's state, so the viewer reopens the
// story where it was in the feed: past the whole front page.
history.replaceState({ usr: { from: 'top' }, key: 'reload', idx: 0 }, '');
}, { live: mockTopItemIds, older });

const reading = older[2];
await page.goto(`/#/item/${reading}`);
await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', String(reading));

const startedAt = Date.now();
await expect.poll(
() => page.evaluate(() => (JSON.parse(localStorage.getItem('feed:top') ?? '{}') as { timestamp?: number }).timestamp ?? 0),
{ timeout: 10_000 },
).toBeGreaterThan(startedAt - 60_000);
await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', String(reading));

// Two swipes on, the next page loads.
await expect(page.locator(`[data-item-id="${older[4]}"]`).first()).toBeAttached();
const container = page.getByTestId('swipe-container');
const panelWidth = await container.evaluate((el) => el.getBoundingClientRect().width);
const index = mockTopItemIds.length + 2;
await smoothScrollAndAwaitSettled(container, panelWidth * (index + 1));
await waitForScrollAtIndex(page, index + 1);
await smoothScrollAndAwaitSettled(container, panelWidth * (index + 2));
await waitForScrollAtIndex(page, index + 2);
await expect.poll(() => dayRequests).toBeGreaterThan(0);
await page.waitForTimeout(1000);

const ids = await page.locator('[data-item-id]').evaluateAll(
(els) => els.map((el) => Number(el.getAttribute('data-item-id'))),
);
expect(ids.filter((id, i) => ids.indexOf(id) !== i)).toEqual([]);
});

test('swipe uses replace — back navigates to previous section, not previous item', async ({ page }) => {
// Swipe-driven URL changes use replaceState (not pushState), so back
// exits the swipe viewer rather than stepping through items.
Expand Down Expand Up @@ -470,6 +615,25 @@ test.describe('Mobile Direct Item Access', () => {
await expect(page.getByText(/curious what side projects everyone is working on/i)).toBeVisible();
});

test('keeps a linked story that is not in the feed after swiping away and back', async ({ page }) => {
// 88888 is an Ask HN story, so the Top feed shows it in front of its own stories.
await page.goto('/#/item/88888');
await expectActiveSwipePanelText(page, 'Ask HN: What are you working on?');

const container = page.getByTestId('swipe-container');
await waitForSwipeReady(page, 6);
const panelWidth = await container.evaluate((el) => el.getBoundingClientRect().width);

await smoothScrollAndAwaitSettled(container, panelWidth);
await waitForScrollAtIndex(page, 1);
await expect(page).toHaveURL(/\/item\/12345/, { timeout: 5000 });

await smoothScrollAndAwaitSettled(container, 0);
await waitForScrollAtIndex(page, 0);
await expect(page).toHaveURL(/\/item\/88888/, { timeout: 5000 });
await expectActiveSwipePanelText(page, 'Ask HN: What are you working on?');
});

test('clears error state when navigating back and forward from not-found item', async ({ page }) => {
// Regression test: navigating to a non-existent item sets anchorItemId,
// injectedError, and fetchedItemIdRef. Browser back/forward must properly
Expand Down
16 changes: 6 additions & 10 deletions e2e/user-profile.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,12 @@ test.describe('User Profile - Mobile', () => {
});

test('clears swipe-mode after mount on direct /user/:id load', async ({ page }) => {
// index.html's bootstrap script optimistically adds `swipe-mode` to <html>
// and <body> for ANY `#/...` route on mobile (the regex
// `^#\/(show|ask|best|newest|item\/)?` is not end-anchored and the group is
// optional, so `#/user/pg` matches via the empty-group fallback). That
// class sets `overflow: clip` on the body, which would wedge the
// vertically scrollable profile if nothing cleared it. UserProfile's
// mount effect imperatively calls `disableSwipeMode()` to unwedge it —
// this assertion runs AFTER the heading is visible (i.e. after React has
// hydrated and the effect has fired) so the assertion pins the
// post-mount state.
// `swipe-mode` sets `overflow: clip` on the body, which would wedge the
// vertically scrollable profile. index.html's bootstrap script no longer
// adds it for `#/user/...`, and UserProfile's mount effect calls
// `disableSwipeMode()` in case anything else does — this assertion runs
// AFTER the heading is visible (i.e. after React has hydrated and the
// effect has fired) so the assertion pins the post-mount state.
await page.goto('/#/user/pg');

await expect(page.getByRole('heading', { level: 1, name: 'pg' })).toBeVisible();
Expand Down
6 changes: 4 additions & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,10 @@
(function() {
var canSwipe = !window.matchMedia('(min-width: 48rem)').matches
&& window.matchMedia('(pointer: coarse) and (hover: none)').matches;
var hash = window.location.hash || '#/';
var isSwipeRoute = /^#\/(show|ask|best|newest|item\/)?/.test(hash);
var path = (window.location.hash || '#/').slice(1).split('?')[0];
// Only the routes App.tsx gives a swipe viewer: the class otherwise
// stays on pages that never clear it (404, "Item not found").
var isSwipeRoute = /^\/(?:(?:show|ask|best|newest)\/?|item\/\d+\/?|from\/.+|submitted\/[^\/]+\/?)?$/i.test(path);
if (canSwipe && isSwipeRoute) {
document.documentElement.classList.add('swipe-mode');
document.body.classList.add('swipe-mode');
Expand Down
Loading
Loading