Skip to content
Merged
41 changes: 41 additions & 0 deletions e2e/domain-filter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,47 @@ test.describe('Domain Filter - Mobile Swipe', () => {
timeout: 10000,
});
});

test('can swipe to the end-of-feed error panel and retry from it', async ({ page }) => {
test.setTimeout(60000);

// Page 0 (5 stories) loads; page 1 fails until the test lets it through.
let failNextPage = true;
await page.route(`${ALGOLIA_API}/search_by_date*`, async (route) => {
const pageNum = new URL(route.request().url()).searchParams.get('page');
if (failNextPage && pageNum === '1') {
await route.fulfill({ status: 503, json: { message: 'Service unavailable' } });
} else {
await route.fallback();
}
});

await page.goto('/#/from/example.com');
const container = page.getByTestId('swipe-container');
await waitForSwipeReady(page, 5);

// Auto-retry exhausts its backoff (2s+4s+8s) before the panel turns into an error.
const errorPanel = container.locator('[data-testid="swipe-panel"]', { hasText: 'Failed to load item' });
await expect(errorPanel).toHaveCount(1, { timeout: 30000 });

// Panels are hidden until activated, so Try Again only shows if a swipe
// can land on the panel after the last story.
const width = await container.evaluate((el) => el.getBoundingClientRect().width);
await smoothScrollAndAwaitSettled(container, width * 5);
await waitForScrollAtIndex(page, 5);
const retryButton = errorPanel.getByRole('button', { name: /try again/i });
await expect(retryButton).toBeVisible();

failNextPage = false;
await retryButton.click();

// The next page's first story takes the error panel's place.
await expectActiveSwipePanelText(page, 'Advanced CSS Grid Techniques for Modern Layouts', {
minPanels: 7,
timeout: 10000,
});
await expect(page).toHaveURL(/\/item\/77700/, { timeout: 5000 });
});
});

test.describe('Domain Filter - Algolia Error Handling', () => {
Expand Down
15 changes: 13 additions & 2 deletions e2e/fixtures/api-mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,17 @@ function buildItemsMap(): Record<number, object> {
function resolveFirebasePath(
path: string,
items: Record<number, object>,
opts?: { userResolver?: (username: string) => object | null },
opts?: {
userResolver?: (username: string) => object | null;
lists?: Record<string, number[]>;
},
): unknown {
// Strip leading slash — the SDK sends `/v0/...` but our constants use `v0/...`
const p = path.replace(/^\//, '');

const listOverride = opts?.lists?.[p];
if (listOverride) return listOverride;

if (p === 'v0/topstories') return mockTopItemIds;
if (p === 'v0/beststories') return mockBestItemIds;
if (p === 'v0/newstories') return mockNewItemIds;
Expand Down Expand Up @@ -242,6 +248,8 @@ export function createFirebaseWsHandler(opts?: {
delayMs?: number;
itemOverrides?: Record<number, object | null>;
errorItemIds?: number[];
/** Story lists to serve instead of the defaults, keyed by path (`v0/topstories`). */
lists?: Record<string, number[]>;
}) {
const items = { ...buildItemsMap(), ...(opts?.itemOverrides ?? {}) };

Expand Down Expand Up @@ -286,7 +294,10 @@ export function createFirebaseWsHandler(opts?: {
return;
}

const data = resolveFirebasePath(body.p, items, { userResolver: opts?.userResolver });
const data = resolveFirebasePath(body.p, items, {
userResolver: opts?.userResolver,
lists: opts?.lists,
});
const response = JSON.stringify({
t: 'd',
d: { r: reqId, b: { s: 'ok', d: data } },
Expand Down
92 changes: 90 additions & 2 deletions e2e/mobile-swipe.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { test, expect } from '@playwright/test';
import { setupApiMocks } from './fixtures/api-mocks';
import { test, expect, type Page } from '@playwright/test';
import {
setupApiMocks,
createFirebaseWsHandler,
FIREBASE_WS_PATTERN,
} from './fixtures/api-mocks';
import { ALGOLIA_API } from './fixtures/mock-data';
import {
expectActiveSwipePanelText,
getActiveSwipePanel,
Expand Down Expand Up @@ -772,3 +777,86 @@ test.describe('Mobile Direct Item Access', () => {
), { timeout: 5000 }).toBe(1);
});
});

test.describe('Mobile Swipe Viewer - Back past the cached page', () => {
test.use({
viewport: { width: 375, height: 667 },
hasTouch: true,
});

// A full first page. The feed cache keeps only this page, so the viewer that
// mounts on Back can't find the Algolia stories that load after it.
const topIds = Array.from({ length: 20 }, (_, i) => 30001 + i);

test.beforeEach(async ({ page }) => {
await setupApiMocks(page);
await page.routeWebSocket(
FIREBASE_WS_PATTERN,
createFirebaseWsHandler({ lists: { 'v0/topstories': topIds } }),
);
await page.addInitScript(() => {
localStorage.clear();
sessionStorage.clear();
});
});

/** Swipes to index 21, the second story of the page loaded after the first. */
async function swipePastFirstPage(page: Page) {
await page.goto('/#/');
const container = page.getByTestId('swipe-container');
await waitForSwipeReady(page, 20);
const panelWidth = await container.evaluate((el) => el.getBoundingClientRect().width);

// The next page (yesterday's front page, sorted by points: 55552, 55551,
// 55553) loads once you're within 5 stories of the end; the swipe helper
// only targets panels that already exist.
await smoothScrollAndAwaitSettled(container, panelWidth * 16);
await waitForSwipeReady(page, 23);
await smoothScrollAndAwaitSettled(container, panelWidth * 21);
await waitForScrollAtIndex(page, 21);
await expect(page).toHaveURL(/\/item\/55551/, { timeout: 5000 });
}

/** Goes Back with day pages blocked, so stories past the cached page can only
* come from what the viewer kept when it unmounted. */
async function goBackToStory21(page: Page) {
await page.route(`${ALGOLIA_API}/search*`, async (route) => {
const tags = new URL(route.request().url()).searchParams.get('tags');
if (tags === 'story') {
await route.abort();
} else {
await route.fallback();
}
});

await page.goBack();
await expect(page).toHaveURL(/\/item\/55551/, { timeout: 5000 });
await waitForSwipeReady(page, 23);
await waitForScrollAtIndex(page, 21);
await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', '55551');
await expect(page.getByTestId('swipe-container').locator('[data-testid="swipe-panel"]').nth(20))
.toHaveAttribute('data-item-id', '55552');
}

test('returns to the same story and its neighbors after visiting the author', async ({ page }) => {
test.setTimeout(60_000);
await swipePastFirstPage(page);

await getActiveSwipePanel(page).locator('a[href^="#/user/"]').first().click();
await expect(page).toHaveURL(/\/user\//, { timeout: 5000 });

await goBackToStory21(page);
});

test('returns to the same story after switching to Best', async ({ page }) => {
test.setTimeout(60_000);
await swipePastFirstPage(page);

await page.getByRole('link', { name: 'best', exact: true }).click({ force: true });
// Best's own viewer mounts on its first story and saves a position too.
await expect(page).toHaveURL(/\/item\/33001/, { timeout: 5000 });
await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', '33001');

await goBackToStory21(page);
});
});
20 changes: 20 additions & 0 deletions e2e/theme-toggle.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,26 @@ test.describe('Theme - System mode', () => {
await expect(html).not.toHaveClass(/dark/);
});

test('follows the OS dark preference without an error when site storage is blocked', async ({ page }) => {
await page.emulateMedia({ colorScheme: 'dark' });
await setupApiMocks(page);
await page.addInitScript(() => {
const deny = () => {
throw new DOMException('Access is denied for this document.', 'SecurityError');
};
Object.defineProperty(window, 'localStorage', { configurable: true, get: deny });
Object.defineProperty(window, 'sessionStorage', { configurable: true, get: deny });
});
const errors: string[] = [];
page.on('pageerror', (error) => errors.push(error.message));

await page.goto('/#/');

await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible();
await expect(page.locator('html')).toHaveClass(/dark/);
expect(errors).toEqual([]);
});

// Issue 2: while following the system, flipping the OS theme flips the app.
test('system mode follows the OS theme when it changes after load', async ({ page }) => {
await page.emulateMedia({ colorScheme: 'light' });
Expand Down
6 changes: 5 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,11 @@
// Mirrors ThemeProvider: 'light'/'dark' are explicit pins; 'system' (and
// any missing value) follows the OS color scheme.
(function() {
var mode = localStorage.getItem('setting:theme');
// Reading storage throws when the browser blocks site data; follow the OS then.
var mode = null;
try {
mode = localStorage.getItem('setting:theme');
} catch (e) {}
var prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
var isDark = mode === 'dark' || (mode !== 'light' && prefersDark);
if (isDark) {
Expand Down
9 changes: 9 additions & 0 deletions src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,15 @@ describe('MobileItemDetailWrapper — viewer recovery (stateless reload)', () =>
expect(screen.queryByTestId('user-viewer')).toBeNull();
});

it('recovers the viewer whose snapshot is on this story when another viewer saved later', () => {
seedSnapshot({ from: 'best' }, 123);
seedSnapshot({ from: 'top' }, 456);

renderWrapper(123);

expect(screen.getByTestId('feed-viewer')).toHaveAttribute('data-type', 'best');
});

it('falls back to the resolver when the snapshot id does not match the route', () => {
seedSnapshot({ from: 'best' }, 999); // snapshot is for a different story

Expand Down
6 changes: 3 additions & 3 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,9 @@ export function MobileItemDetailWrapper() {
const { id } = useParams();
const canSwipe = useCanSwipe();
const location = useLocation();
// Snapshot read once (sticky for the wrapper's life); used only by Branch 4b to
// recover the viewer on a stateless reload.
const [recovered] = useState(() => readSwipePosition());
// Newest snapshot taken on this story, read once (sticky for the wrapper's life);
// used only by Branch 4b to recover the viewer on a stateless reload.
const [recovered] = useState(() => readSwipePosition({ storyId: Number(id) }));

if (canSwipe) {
const state = location.state as LocationState | null;
Expand Down
40 changes: 40 additions & 0 deletions src/api/hn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,18 @@ describe('hn API utilities', () => {
expect(result2.stories.length).toBe(5);
expect(result2.hasMore).toBe(false);
});

it('keeps Show HN projects whose titles mention hiring', async () => {
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) =>
Number(id) === 99998
? { ...mockShowItems[99998], title: 'Show HN: A "Who is hiring" thread search' }
: mockShowItems[Number(id)] ?? null
);

const result = await fetchShowStories(0);

expect(result.stories.map(s => s.id)).toEqual([99999, 99998, 99997]);
});
});

describe('fetchAskStories', () => {
Expand Down Expand Up @@ -599,6 +611,21 @@ describe('hn API utilities', () => {
expect(result2.stories.length).toBe(5);
expect(result2.hasMore).toBe(false);
});

it('filters out the monthly whoishiring threads', async () => {
vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue([88888, 88910, 88911, 88887]);
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => {
const hiring: Record<number, FirebaseItem> = {
88910: { id: 88910, title: 'Ask HN: Who is hiring? (October 2026)', text: 'Post jobs', by: 'whoishiring', score: 300, time: Math.floor(Date.now() / 1000), descendants: 400, type: 'story' },
88911: { id: 88911, title: 'Ask HN: Who wants to be hired? (October 2026)', text: 'Post resumes', by: 'whoishiring', score: 120, time: Math.floor(Date.now() / 1000), descendants: 200, type: 'story' },
};
return hiring[Number(id)] ?? mockAskItems[Number(id)] ?? null;
});

const result = await fetchAskStories(0);

expect(result.stories.map(s => s.id)).toEqual([88888, 88887]);
});
});

describe('fetchNewStories', () => {
Expand Down Expand Up @@ -803,6 +830,19 @@ describe('hn API utilities', () => {
expect(result.stories).toEqual([]);
expect(result.hasMore).toBe(false);
});

it('filters out the monthly whoishiring threads', async () => {
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => {
const base = { id: Number(id), by: 'testuser', score: 50, time: Math.floor(Date.now() / 1000) - 7200, descendants: 5, type: 'story' as const };
if (Number(id) === 12346) return { ...base, title: 'Ask HN: Who is hiring? (October 2026)', by: 'whoishiring' };
if (Number(id) === 12348) return { ...base, title: 'Ask HN: Who wants to be hired? (October 2026)', by: 'whoishiring' };
return { ...base, title: `Item ${id}` };
});

const result = await fetchBestStories(0, 30);

expect(result.stories.map(s => s.id)).toEqual([12345, 12347, 12349]);
});
});

describe('fetchFirebaseItem', () => {
Expand Down
Loading
Loading