From 4d6b1a6e267c679a64f65bd64fc33a1adcd71701 Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Mon, 5 Oct 2026 15:39:25 +0200
Subject: [PATCH 2/6] fix: load every comment on threads with more than 1,000
Algolia search returns at most 1,000 hits, so the comment fetch stopped
there: a 2,530-comment thread showed 1,000. When the first page shows
the cap, the comments now also come from the /items endpoint, which
returns the whole tree in one request. It misses a few comments that
search has (47 on that thread), so its comments are added to the search
results rather than replacing them. If it fails, the search results are
used as before.
The loop also stops at the last page search reports instead of asking
for one more empty page.
---
src/api/hn.test.ts | 76 ++++++++++++++++++++++++++++++++++++++++++++++
src/api/hn.ts | 33 +++++++++++++++++++-
2 files changed, 108 insertions(+), 1 deletion(-)
diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts
index 8c47a6e..820595e 100644
--- a/src/api/hn.test.ts
+++ b/src/api/hn.test.ts
@@ -1088,5 +1088,81 @@ describe('hn API utilities', () => {
mockFetch.mockRestore();
});
+
+ describe('a thread bigger than search returns', () => {
+ const itemId = 9100;
+ const firebaseItem: FirebaseItem = {
+ id: itemId, title: 'Big thread', by: 'author', score: 900, time: 1700000000,
+ descendants: 1500, kids: [101, 102, 103, 104], type: 'story',
+ };
+ const searchHits = [
+ { objectID: '101', author: 'alice', comment_text: 'From search', created_at_i: 1700000100, parent_id: itemId },
+ // Missing from the item tree below, as some comments are.
+ { objectID: '102', author: 'bob', comment_text: 'Only in search', created_at_i: 1700000200, parent_id: itemId },
+ ];
+ const tree = {
+ id: itemId, type: 'story', author: 'author', text: null, created_at_i: 1700000000,
+ parent_id: null, story_id: itemId,
+ children: [
+ {
+ id: 101, author: 'alice', text: 'From the tree', created_at_i: 1700000100, parent_id: itemId,
+ children: [{ id: 201, author: 'carol', text: 'Reply', created_at_i: 1700000300, parent_id: 101, children: [] }],
+ },
+ {
+ id: 103, author: null, text: null, created_at_i: 1700000400, parent_id: itemId,
+ children: [{ id: 202, author: 'dave', text: 'Reply to a deleted comment', created_at_i: 1700000500, parent_id: 103, children: [] }],
+ },
+ { id: 104, author: 'erin', text: 'Past the limit', created_at_i: 1700000600, parent_id: itemId, children: [] },
+ ],
+ };
+
+ const urlOf = (input: RequestInfo | URL) =>
+ typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+
+ function mockAlgolia(search: { nbHits: number; nbPages: number }, { treeStatus = 200 } = {}) {
+ return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
+ if (urlOf(input).includes(`/items/${itemId}`)) {
+ return treeStatus === 200 ? Response.json(tree) : new Response(null, { status: treeStatus });
+ }
+ return Response.json({ hits: searchHits, page: 0, hitsPerPage: 200, ...search });
+ });
+ }
+
+ beforeEach(() => {
+ vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => (Number(id) === itemId ? firebaseItem : null));
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('adds the comments past the limit from the item tree', async () => {
+ // nbPages is capped at 1,000 hits / 200 per page, so it no longer covers nbHits.
+ mockAlgolia({ nbHits: 1500, nbPages: 5 });
+
+ const comments = await fetchCommentsForItem(itemId);
+
+ expect(comments.map(c => c.id)).toEqual([101, 102, 104]);
+ expect(comments[0].text).toBe('From search');
+ expect(comments[0].children.map(c => c.id)).toEqual([201]);
+ });
+
+ it('keeps the search results when the item tree fails', async () => {
+ mockAlgolia({ nbHits: 1500, nbPages: 5 }, { treeStatus: 500 });
+
+ const comments = await fetchCommentsForItem(itemId);
+
+ expect(comments.map(c => c.id)).toEqual([101, 102]);
+ });
+
+ it('skips the item tree when search has every comment', async () => {
+ const mockFetch = mockAlgolia({ nbHits: 2, nbPages: 1 });
+
+ await fetchCommentsForItem(itemId);
+
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ expect(urlOf(mockFetch.mock.calls[0][0])).toContain('/search?');
+ });
+ });
});
});
diff --git a/src/api/hn.ts b/src/api/hn.ts
index f48a653..6d4dd9a 100644
--- a/src/api/hn.ts
+++ b/src/api/hn.ts
@@ -360,6 +360,7 @@ async function fetchAllCommentsAlgolia(itemId: number, signal?: AbortSignal): Pr
const allComments: AlgoliaComment[] = [];
let page = 0;
const hitsPerPage = 200; // Algolia max
+ let isCapped = false;
while (true) {
if (signal?.aborted) return allComments;
@@ -372,8 +373,10 @@ async function fetchAllCommentsAlgolia(itemId: number, signal?: AbortSignal): Pr
const data = await response.json() as AlgoliaSearchResponse
;
allComments.push(...data.hits);
+ // Search returns at most 1,000 hits and caps nbPages to match.
+ if (page === 0) isCapped = data.nbHits > data.nbPages * hitsPerPage;
- if (data.hits.length < hitsPerPage || allComments.length >= data.nbHits) {
+ if (data.hits.length < hitsPerPage || allComments.length >= data.nbHits || page >= data.nbPages - 1) {
break;
}
page++;
@@ -381,10 +384,38 @@ async function fetchAllCommentsAlgolia(itemId: number, signal?: AbortSignal): Pr
// Safety limit to prevent infinite loops
if (page > 10) break;
}
+
+ // The item endpoint has the rest of a bigger thread. It also misses a few
+ // comments that search has, so it adds to search's results.
+ if (isCapped && !signal?.aborted) {
+ const tree = await fetchAlgoliaItem(itemId, signal).catch(() => null);
+ const seen = new Set(allComments.map(c => c.objectID));
+ for (const comment of flattenAlgoliaItemChildren(tree?.children ?? [])) {
+ if (!seen.has(comment.objectID)) allComments.push(comment);
+ }
+ }
return allComments;
}
+function flattenAlgoliaItemChildren(children: AlgoliaItemChild[], into: AlgoliaComment[] = []): AlgoliaComment[] {
+ for (const child of children) {
+ // Deleted comments have no author; their replies are left as orphans,
+ // which buildCommentTree drops just as it does for search results.
+ if (child.author) {
+ into.push({
+ objectID: String(child.id),
+ author: child.author,
+ comment_text: child.text ?? '',
+ created_at_i: child.created_at_i,
+ parent_id: child.parent_id,
+ });
+ }
+ flattenAlgoliaItemChildren(child.children ?? [], into);
+ }
+ return into;
+}
+
// `kidsOrder` (from Firebase kids arrays) maintains HN's ranking order; falls
// back to creation time when not available.
function buildCommentTree(comments: AlgoliaComment[], itemId: number, kidsOrder = new Map()): Comment[] {
From 6aaa1d28843834a4d53322a7e98061f12268b7d7 Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Mon, 5 Oct 2026 15:41:53 +0200
Subject: [PATCH 3/6] fix: refresh a story's title, points and comment count
with its comments
useItemWithComments revalidates a stale cached item by fetching its
comments, and that fetch reads the item from Firebase too, but only its
text was used. The cached title, points and comment count stayed up to
24 hours old and were written back as fresh, so the next visit kept
them too. This shows on a reload, a bookmark, Back to a story, or a
story opened before the feed's prefetch reached it.
They now come from the fetched item. The type stays the local one,
because Firebase calls Ask/Show posts 'story', and a fetched item
without a title (a deleted story) changes nothing but the body, as
before.
The e2e Firebase mock now has its own copy of each story that only the
Algolia mocks listed, with the same title and counts. It used to answer
them with a generic "Item ", which the swipe panel now shows once
the comments load.
---
e2e/fixtures/api-mocks.ts | 45 ++++++++++++++++++++-----
src/hooks/useItemWithComments.test.tsx | 46 ++++++++++++++++++++++++--
src/hooks/useItemWithComments.ts | 26 ++++++++++++---
3 files changed, 101 insertions(+), 16 deletions(-)
diff --git a/e2e/fixtures/api-mocks.ts b/e2e/fixtures/api-mocks.ts
index 77f4e71..d42cf25 100644
--- a/e2e/fixtures/api-mocks.ts
+++ b/e2e/fixtures/api-mocks.ts
@@ -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 {
+ 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,
@@ -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
diff --git a/src/hooks/useItemWithComments.test.tsx b/src/hooks/useItemWithComments.test.tsx
index e227209..d5b33d7 100644
--- a/src/hooks/useItemWithComments.test.tsx
+++ b/src/hooks/useItemWithComments.test.tsx
@@ -121,9 +121,9 @@ describe('useItemWithComments', () => {
await waitFor(() => {
expect(result.current.commentsLoading).toBe(false);
});
- // Only the body is filled in: the feed's own fields (type, points) stay.
- expect(result.current.item).toEqual({ ...askItem, text: body });
- expect(getCachedItem(12345)?.item).toEqual({ ...askItem, text: body });
+ // Firebase calls Ask HN posts `story`, so the type stays the feed's.
+ expect(result.current.item).toEqual({ ...askItem, text: body, points: 999 });
+ expect(getCachedItem(12345)?.item).toEqual({ ...askItem, text: body, points: 999 });
});
});
@@ -492,6 +492,46 @@ describe('useItemWithComments', () => {
expect(result.current.item).toBeTruthy();
});
+ function seedStaleCache() {
+ localStorage.setItem(`${ITEM_CACHE_KEY_PREFIX}12345`, JSON.stringify({
+ item: testItem,
+ comments: testComments,
+ timestamp: Date.now() - 60 * 60 * 1000,
+ orderedDepth: 3,
+ }));
+ }
+
+ it('updates the title, points and comment count from the revalidation', async () => {
+ vi.spyOn(hnSdk, 'readItem').mockResolvedValue({
+ ...mockFirebaseStory, title: 'Renamed by a moderator', score: 450, descendants: 120,
+ });
+ seedStaleCache();
+
+ const { result } = renderHook(() => useItemWithComments(12345));
+ expect(result.current.item).toEqual(testItem);
+
+ const fresh = { ...testItem, title: 'Renamed by a moderator', points: 450, commentCount: 120 };
+ await waitFor(() => {
+ expect(result.current.item).toEqual(fresh);
+ });
+ expect(getCachedItem(12345)?.item).toEqual(fresh);
+ });
+
+ it('keeps the cached title when the story has since been deleted', async () => {
+ vi.spyOn(hnSdk, 'readItem').mockResolvedValue({
+ id: 12345, deleted: true, time: mockFirebaseStory.time, type: 'story',
+ });
+ seedStaleCache();
+
+ const { result } = renderHook(() => useItemWithComments(12345));
+
+ await waitFor(() => {
+ expect(getCachedItem(12345)?.isFresh).toBe(true);
+ });
+ expect(result.current.item).toEqual(testItem);
+ expect(getCachedItem(12345)?.item).toEqual(testItem);
+ });
+
it('fetches when cache has no comments', async () => {
const CACHE_KEY = `${ITEM_CACHE_KEY_PREFIX}12345`;
const partialData = {
diff --git a/src/hooks/useItemWithComments.ts b/src/hooks/useItemWithComments.ts
index 5845e71..686eb65 100644
--- a/src/hooks/useItemWithComments.ts
+++ b/src/hooks/useItemWithComments.ts
@@ -36,6 +36,24 @@ function withText(item: Item | null | undefined, source: Item | null | undefined
return { ...item, text: source.text };
}
+// The comments fetch reads the item too, so it has newer points, comment count
+// and title than a cached or restored copy. The rest stays: Firebase calls
+// Ask/Show posts `story`, and a deleted story comes back without a title.
+function withFetchedFields(item: Item | null | undefined, fetched: Item): Item | null {
+ if (!item || item.type === 'comment' || item.type === 'job' || fetched.type !== 'story' ||
+ fetched.id !== item.id || !fetched.title) {
+ return withText(item, fetched);
+ }
+ return {
+ ...item,
+ title: fetched.title,
+ url: fetched.url ?? item.url,
+ text: fetched.text ?? item.text,
+ points: fetched.points,
+ commentCount: fetched.commentCount,
+ };
+}
+
export function useItemWithComments(itemId: number | string, { initialItem = null, skipOrderingCompletion = false, isPriority = true, deferComments = false }: UseItemWithCommentsOptions = {}): UseItemWithCommentsResult {
const initialCache = getCachedItem(itemId);
@@ -176,12 +194,12 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
try {
const { item: fetchedItem, comments: commentsData } = await fetchItemWithComments(itemId, controller.signal);
if (!controller.signal.aborted) {
- setItem(current => withText(current, fetchedItem));
+ setItem(current => withFetchedFields(current, fetchedItem));
setComments(commentsData);
setCommentsLoading(false);
setCommentsError(null);
- const fullItem = withText(itemData, fetchedItem);
+ const fullItem = withFetchedFields(itemData, fetchedItem);
if (fullItem) {
setCachedItem(itemId, fullItem, commentsData, 3);
}
@@ -277,11 +295,11 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
void fetchItemWithComments(itemId, controller.signal)
.then(({ item: fetchedItem, comments: commentsData }) => {
if (controller.signal.aborted) return;
- setItem(current => withText(current, fetchedItem));
+ setItem(current => withFetchedFields(current, fetchedItem));
setComments(commentsData);
setCommentsLoading(false);
setCommentsError(null);
- const fullItem = withText(item, fetchedItem);
+ const fullItem = withFetchedFields(item, fetchedItem);
if (fullItem) setCachedItem(itemId, fullItem, commentsData, 3);
})
.catch(err => {
From c04bba5316fa6a539f070b599126821de9b8277e Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Mon, 5 Oct 2026 15:47:56 +0200
Subject: [PATCH 4/6] fix: keep the story on screen when a feed refresh lands
after a swipe
A feed opened from its cache refreshes in the background, and the
refresh replaced every story. The swipe viewer starts it at mount, but
on a slow connection it lands after the first swipes: the panel's index
stayed the same while the story under it changed, with no input from
the reader.
useInfiniteStories now takes the ids the reader has reached
(keepOnRevalidate), and a refresh keeps those stories, followed by the
fresh ones that aren't already there. The swipe viewer reports them on
each change, from the first story through the one on screen, so the
story on screen stays even at index 0. The feed cache still gets the
fresh page as fetched. Desktop passes nothing, so its refresh still
replaces the whole list.
The feed counts as fresh once the page arrives, rather than once it adds
a story: with stories kept, every fetched one can already be there, and
the swipe viewer calls loadMore for as long as the feed is marked as
cached. The list is rebuilt from the kept stories at that point too,
even with nothing new on the page. The desktop list caches everything
it loaded, and the cached stories past the kept ones are no longer in
seenIds, so the next page would show them a second time.
The e2e swipe helper now waits up to 2 s for a swipe to finish before
sending it again, up from 500 ms. On Mobile Safari under load some
swipes finished later than that, and the retry then moved the reader a
panel further than asked; the new refresh test failed about one run in
ten because of it.
---
e2e/fixtures/swipe-helpers.ts | 6 +-
e2e/mobile-swipe.spec.ts | 145 +++++++++++++++++++++++++++
src/components/SwipeStoryViewer.tsx | 15 ++-
src/hooks/useInfiniteStories.test.ts | 71 ++++++++++++-
src/hooks/useInfiniteStories.ts | 88 ++++++++++------
5 files changed, 286 insertions(+), 39 deletions(-)
diff --git a/e2e/fixtures/swipe-helpers.ts b/e2e/fixtures/swipe-helpers.ts
index 5f94610..95a04bb 100644
--- a/e2e/fixtures/swipe-helpers.ts
+++ b/e2e/fixtures/swipe-helpers.ts
@@ -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).
diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts
index 34cd3e5..3b78b1c 100644
--- a/e2e/mobile-swipe.spec.ts
+++ b/e2e/mobile-swipe.spec.ts
@@ -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.
diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx
index c369c77..eab1de5 100644
--- a/src/components/SwipeStoryViewer.tsx
+++ b/src/components/SwipeStoryViewer.tsx
@@ -34,6 +34,8 @@ interface SwipeStoryViewerCoreProps {
* with zero stories and no initialItemId. Feeds omit this to preserve the
* existing fall-through behavior (they are never truly empty). */
emptyTitle?: string;
+ /** Called with the ids of the stories from the first through the one on screen. */
+ onReachedStoriesChange?: (storyIds: number[]) => void;
}
/**
@@ -57,6 +59,7 @@ export function SwipeStoryViewerCore({
backState,
titleFallback,
emptyTitle,
+ onReachedStoriesChange,
}: SwipeStoryViewerCoreProps) {
const navigate = useNavigate();
const location = useLocation();
@@ -506,6 +509,10 @@ export function SwipeStoryViewerCore({
// Each panel IS the story detail on mobile — track how long the active story
// is looked at and hide it for a window scaled to that dwell time.
useViewDwell(currentStory?.id);
+
+ useLayoutEffect(() => {
+ onReachedStoriesChange?.(mergedStories.slice(0, currentIndex + 1).map(story => story.id));
+ }, [mergedStories, currentIndex, onReachedStoriesChange]);
// Load more stories when approaching the end (don't auto-retry on error — user taps Retry)
useEffect(() => {
@@ -718,13 +725,14 @@ interface SwipeStoryViewerProps {
/** Feed-backed swipe viewer wrapping SwipeStoryViewerCore. */
export function SwipeStoryViewer({ type, initialItemId }: SwipeStoryViewerProps) {
- const { stories, loading, error, hasMore, loadMore, isFromCache, isFromSession } = useInfiniteStories(type);
+ const { stories, loading, error, hasMore, loadMore, isFromCache, isFromSession, keepOnRevalidate } = useInfiniteStories(type);
// Prefetch other sections in background for instant tab switching
usePrefetchSections(type);
- // Trigger revalidation eagerly — same as StoryList — so the replace
- // happens at index 0, not mid-session after the user has swiped deep.
+ // Trigger revalidation eagerly — same as StoryList — so it lands before the
+ // reader has swiped far: the stories they've reached, the one on screen
+ // included, stay, and the rest are replaced.
useEffect(() => {
if (isFromSession) return;
if (isFromCache && !loading && !error) {
@@ -744,6 +752,7 @@ export function SwipeStoryViewer({ type, initialItemId }: SwipeStoryViewerProps)
initialItemId={initialItemId}
backState={backState}
titleFallback={FEED_TYPE_TITLES[type]}
+ onReachedStoriesChange={keepOnRevalidate}
/>
);
}
diff --git a/src/hooks/useInfiniteStories.test.ts b/src/hooks/useInfiniteStories.test.ts
index f0a8d4c..e2923cb 100644
--- a/src/hooks/useInfiniteStories.test.ts
+++ b/src/hooks/useInfiniteStories.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { useInfiniteStories } from './useInfiniteStories';
-import { setCachedFeed, clearFeedCache } from '../utils/feedCache';
+import { setCachedFeed, getCachedFeed, clearFeedCache } from '../utils/feedCache';
import { clearListSessionState } from '../utils/itemCache';
import { createStoryItem } from '../test/factories';
import { server } from '../mocks/server';
@@ -150,4 +150,73 @@ describe('useInfiniteStories', () => {
expect(new Set(ids).size).toBe(ids.length);
expect(ids).toHaveLength(50);
});
+
+ describe('revalidation', () => {
+ function seedStaleFeed(type: FeedType) {
+ // A cached order the live ranking (1, 2, 3, …) has moved on from.
+ setCachedFeed(type, [5, 29, 3].map(id => createStoryItem({ id, title: `Cached Story ${id}` })));
+ }
+
+ it.each(['top', 'best', 'ask'])('keeps the %s stories passed to keepOnRevalidate ahead of the fresh ones', async (type) => {
+ seedStaleFeed(type);
+ const { result } = renderHook(() => useInfiniteStories(type));
+
+ act(() => result.current.keepOnRevalidate([5, 29]));
+ await act(() => result.current.loadMore());
+
+ const fresh = getCachedFeed(type)!.stories.map(s => s.id);
+ expect(fresh).toContain(5);
+ expect(result.current.stories.map(s => s.id)).toEqual([5, 29, ...fresh.filter(id => id !== 5 && id !== 29)]);
+ expect(result.current.stories[0].title).toBe('Cached Story 5');
+ });
+
+ it('keeps only the stories passed, not the ones ahead of them in the feed', async () => {
+ // A linked story the viewer moved to the front: the reader has seen it
+ // and none of the cached stories before it.
+ seedStaleFeed('top');
+ const { result } = renderHook(() => useInfiniteStories('top'));
+
+ act(() => result.current.keepOnRevalidate([3]));
+ await act(() => result.current.loadMore());
+
+ const fresh = getCachedFeed('top')!.stories.map(s => s.id);
+ expect(result.current.stories.map(s => s.id)).toEqual([3, ...fresh.filter(id => id !== 3)]);
+ });
+
+ it.each(['top', 'best', 'ask'])('counts the %s feed as fresh when every fetched story was kept', async (type) => {
+ // The swipe viewer calls loadMore for as long as isFromCache is set.
+ setCachedFeed(type, rankedIds.map(id => createStoryItem({ id })));
+ const { result } = renderHook(() => useInfiniteStories(type));
+
+ act(() => result.current.keepOnRevalidate(rankedIds));
+ await act(() => result.current.loadMore());
+
+ expect(result.current.isFromCache).toBe(false);
+ expect(result.current.stories.map(s => s.id)).toEqual(rankedIds);
+ });
+
+ it.each(['top', 'best', 'ask'])('drops the cached %s stories past the kept ones when every fetched story was kept', async (type) => {
+ // A cache longer than one page, as the desktop list writes, and a reader
+ // past the whole fetched page.
+ setCachedFeed(type, rankedIds.map(id => createStoryItem({ id })));
+ const { result } = renderHook(() => useInfiniteStories(type));
+
+ act(() => result.current.keepOnRevalidate(rankedIds.slice(0, 40)));
+ await act(() => result.current.loadMore());
+ expect(result.current.stories.map(s => s.id)).toEqual(rankedIds.slice(0, 40));
+
+ await act(() => result.current.loadMore());
+ const ids = result.current.stories.map(s => s.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ it('replaces every story when none were kept', async () => {
+ seedStaleFeed('top');
+ const { result } = renderHook(() => useInfiniteStories('top'));
+
+ await act(() => result.current.loadMore());
+
+ expect(result.current.stories.map(s => s.id)).toEqual(getCachedFeed('top')!.stories.map(s => s.id));
+ });
+ });
});
diff --git a/src/hooks/useInfiniteStories.ts b/src/hooks/useInfiniteStories.ts
index 59a9a7c..ecc8372 100644
--- a/src/hooks/useInfiniteStories.ts
+++ b/src/hooks/useInfiniteStories.ts
@@ -5,7 +5,7 @@
* Stale responses discarded via a monotonic version counter.
* Deduplication across pages via a `seenIds` set.
*/
-import { useState, useCallback, useRef } from 'react';
+import { useState, useCallback, useRef, useLayoutEffect } from 'react';
import { fetchTopStories, fetchFrontPageForDay, fetchBestStories, fetchNewStories, fetchShowStories, fetchAskStories, fetchAskStoriesForDay, fetchShowStoriesForDay } from '../api/hn';
import { getCachedFeed, setCachedFeed } from '../utils/feedCache';
import { getListSessionState, saveListSessionState, clearListSessionState } from '../utils/itemCache';
@@ -92,6 +92,12 @@ export function useInfiniteStories(type: FeedType = 'top') {
// commit both still see the old `loading === false`.
const inFlightRef = useRef(false);
const hasStaleCacheRef = useRef(initialState.isFromCache);
+ const storiesRef = useRef(stories);
+ const keptIdsRef = useRef>(new Set());
+
+ useLayoutEffect(() => {
+ storiesRef.current = stories;
+ }, [stories]);
// For ask/show: tracks whether we've exhausted Firebase and moved to Algolia
const phaseRef = useRef<'firebase' | 'algolia'>(
(() => {
@@ -112,9 +118,22 @@ export function useInfiniteStories(type: FeedType = 'top') {
// Capture current version to check if response is stale
const currentVersion = versionRef.current;
+ // Revalidation REPLACES the stale stories, except the ones passed to
+ // keepOnRevalidate. seenIds restarts from those, so nothing fresh gets
+ // dropped.
+ const startRevalidation = () => {
+ const kept = storiesRef.current.filter(story => keptIdsRef.current.has(story.id));
+ seenIdsRef.current = new Set(kept.map(story => story.id));
+ return kept;
+ };
+
try {
if (type === 'top') {
let newStories: StoryItem[] = [];
+ // Set once a refresh's page arrives, which then rebuilds the list even
+ // with nothing new on it: the cached stories past the kept ones are no
+ // longer in seenIds, so the next page would repeat them.
+ let kept: StoryItem[] | null = null;
const isRevalidating = hasStaleCacheRef.current && positionRef.current === 0;
if (positionRef.current === 0) {
@@ -122,9 +141,8 @@ export function useInfiniteStories(type: FeedType = 'top') {
if (versionRef.current !== currentVersion) return;
- // Revalidation REPLACES all stories — clear seenIds so nothing gets dropped.
- if (isRevalidating) {
- seenIdsRef.current.clear();
+ if (isRevalidating && frontPage.length > 0) {
+ kept = startRevalidation();
}
newStories = frontPage.filter(story => {
@@ -135,8 +153,10 @@ export function useInfiniteStories(type: FeedType = 'top') {
return true;
});
- if (newStories.length > 0) {
- setCachedFeed(type, newStories);
+ // Fresh once the page arrives, even if every story on it was kept:
+ // the swipe viewer calls loadMore for as long as isFromCache is set.
+ if (frontPage.length > 0) {
+ setCachedFeed(type, frontPage);
setIsFromCache(false);
hasStaleCacheRef.current = false;
}
@@ -169,12 +189,10 @@ export function useInfiniteStories(type: FeedType = 'top') {
if (newStories.length === 0 && positionRef.current >= 365) {
setHasMore(false);
+ } else if (kept) {
+ setStories([...kept, ...newStories]);
} else if (newStories.length > 0) {
- if (isRevalidating) {
- setStories(newStories);
- } else {
- setStories(prev => [...prev, ...newStories]);
- }
+ setStories(prev => [...prev, ...newStories]);
}
} else if (type === 'best' || type === 'newest') {
// Offset-based pagination via Firebase /beststories or /newstories.
@@ -184,9 +202,8 @@ export function useInfiniteStories(type: FeedType = 'top') {
if (versionRef.current !== currentVersion) return;
- if (isRevalidatingBest) {
- seenIdsRef.current.clear();
- }
+ // As in the top branch.
+ const kept = isRevalidatingBest && result.stories.length > 0 ? startRevalidation() : null;
const uniqueStories = result.stories.filter(story => {
if (seenIdsRef.current.has(story.id)) {
@@ -196,8 +213,9 @@ export function useInfiniteStories(type: FeedType = 'top') {
return true;
});
- if (positionRef.current === 0 && uniqueStories.length > 0) {
- setCachedFeed(type, uniqueStories);
+ // By the fetched page, as in the top branch.
+ if (positionRef.current === 0 && result.stories.length > 0) {
+ setCachedFeed(type, result.stories);
setIsFromCache(false);
hasStaleCacheRef.current = false;
}
@@ -205,12 +223,10 @@ export function useInfiniteStories(type: FeedType = 'top') {
positionRef.current = result.nextOffset;
setHasMore(result.hasMore);
- if (uniqueStories.length > 0) {
- if (isRevalidatingBest) {
- setStories(uniqueStories);
- } else {
- setStories(prev => [...prev, ...uniqueStories]);
- }
+ if (kept) {
+ setStories([...kept, ...uniqueStories]);
+ } else if (uniqueStories.length > 0) {
+ setStories(prev => [...prev, ...uniqueStories]);
}
} else if (type === 'show' || type === 'ask') {
const isRevalidating = hasStaleCacheRef.current && positionRef.current === 0;
@@ -221,9 +237,8 @@ export function useInfiniteStories(type: FeedType = 'top') {
if (versionRef.current !== currentVersion) return;
- if (isRevalidating) {
- seenIdsRef.current.clear();
- }
+ // As in the top branch.
+ const kept = isRevalidating && result.stories.length > 0 ? startRevalidation() : null;
const uniqueStories = result.stories.filter(story => {
if (seenIdsRef.current.has(story.id)) {
@@ -233,8 +248,9 @@ export function useInfiniteStories(type: FeedType = 'top') {
return true;
});
- if (positionRef.current === 0 && uniqueStories.length > 0) {
- setCachedFeed(type, uniqueStories);
+ // By the fetched page, as in the top branch.
+ if (positionRef.current === 0 && result.stories.length > 0) {
+ setCachedFeed(type, result.stories);
setIsFromCache(false);
hasStaleCacheRef.current = false;
}
@@ -248,12 +264,10 @@ export function useInfiniteStories(type: FeedType = 'top') {
// Do NOT call setHasMore(false) — Algolia has more content
}
- if (uniqueStories.length > 0) {
- if (isRevalidating) {
- setStories(uniqueStories);
- } else {
- setStories(prev => [...prev, ...uniqueStories]);
- }
+ if (kept) {
+ setStories([...kept, ...uniqueStories]);
+ } else if (uniqueStories.length > 0) {
+ setStories(prev => [...prev, ...uniqueStories]);
}
} else {
// Algolia phase: fetch day-by-day
@@ -326,6 +340,13 @@ export function useInfiniteStories(type: FeedType = 'top') {
clearListSessionState(type);
}, [type]);
+ // The swipe viewer passes the stories from the first through the one on
+ // screen: a revalidation that lands after a swipe would otherwise put a
+ // different story under the reader.
+ const keepOnRevalidate = useCallback((storyIds: readonly number[]) => {
+ keptIdsRef.current = new Set(storyIds);
+ }, []);
+
// Save session state for instant back navigation
const saveSessionState = useCallback((scrollY = window.scrollY) => {
if (stories.length === 0) return;
@@ -356,5 +377,6 @@ export function useInfiniteStories(type: FeedType = 'top') {
isFromSession,
initialScrollY,
saveSessionState,
+ keepOnRevalidate,
} as const;
}
From 2ac6624ccc838ab6ae4c59c4882c0bac1eb522c3 Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Mon, 5 Oct 2026 15:51:22 +0200
Subject: [PATCH 5/6] fix: list more than 1,000 stories for a domain or user
The domain and user lists page through Algolia's search_by_date, which
returns at most 1,000 hits and caps nbPages to match. Their 'has more'
check ended at that last page, so /from/github.com and the submissions
of anyone with more than 1,000 stories stopped with no sign that more
existed.
Past the last page, the next request now starts over at page 0 with
created_at_i at or before the oldest hit so far. Results are newest
first, so that picks up where the list stopped; the boundary story
comes back once and the existing dedup drops it.
---
src/hooks/useDomainInfiniteStories.test.ts | 28 +++++++++++++++++++
src/hooks/useDomainInfiniteStories.ts | 17 +++++++-----
src/hooks/useUserInfiniteStories.test.ts | 28 +++++++++++++++++++
src/hooks/useUserInfiniteStories.ts | 18 +++++++------
src/utils/algoliaPaging.ts | 31 ++++++++++++++++++++++
5 files changed, 107 insertions(+), 15 deletions(-)
create mode 100644 src/utils/algoliaPaging.ts
diff --git a/src/hooks/useDomainInfiniteStories.test.ts b/src/hooks/useDomainInfiniteStories.test.ts
index d43ec55..e6edc6c 100644
--- a/src/hooks/useDomainInfiniteStories.test.ts
+++ b/src/hooks/useDomainInfiniteStories.test.ts
@@ -688,6 +688,34 @@ describe('useDomainInfiniteStories', () => {
});
});
+ describe('more stories than search returns', () => {
+ it('loads past the last page from the oldest hit so far', async () => {
+ const hit = (id: number, createdAt: number) => ({ ...body('example.com', [id]).hits[0], created_at_i: createdAt });
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
+ const filter = new URL(fetchInputToUrl(input)).searchParams.get('numericFilters');
+ // Search stops at 1,000 hits and caps nbPages to match, so its last
+ // page doesn't reach nbHits.
+ return Promise.resolve(Response.json(filter === null
+ ? { hits: [hit(1, 300), hit(2, 200)], nbHits: 1500, nbPages: 1, page: 0, hitsPerPage: 50 }
+ : { hits: [hit(2, 200), hit(3, 100)], nbHits: 2, nbPages: 1, page: 0, hitsPerPage: 50 }));
+ });
+
+ const { result } = renderHook(() => useDomainInfiniteStories('example.com'));
+ await waitFor(() => expect(result.current.stories.map((s) => s.id)).toEqual([1, 2]));
+ expect(result.current.hasMore).toBe(true);
+
+ await act(async () => {
+ await result.current.loadMore();
+ });
+
+ const nextUrl = new URL(fetchInputToUrl(fetchSpy.mock.calls[1]?.[0]));
+ expect(nextUrl.searchParams.get('numericFilters')).toBe('created_at_i<=200');
+ expect(nextUrl.searchParams.get('page')).toBe('0');
+ expect(result.current.stories.map((s) => s.id)).toEqual([1, 2, 3]);
+ expect(result.current.hasMore).toBe(false);
+ });
+ });
+
describe('reset', () => {
it('clears state, removes the cache entry, and triggers a fresh fetch', async () => {
// Two distinct payloads so we can prove the second fetch actually ran
diff --git a/src/hooks/useDomainInfiniteStories.ts b/src/hooks/useDomainInfiniteStories.ts
index f01dc4f..30693c6 100644
--- a/src/hooks/useDomainInfiniteStories.ts
+++ b/src/hooks/useDomainInfiniteStories.ts
@@ -1,6 +1,7 @@
import { useState, useCallback, useRef, useEffect, useLayoutEffect } from 'react';
import { ALGOLIA_API } from '../config/api';
import { normalizeAlgoliaHit } from '../api/hn';
+import { algoliaPageParams, nextAlgoliaPage, type AlgoliaPageCursor } from '../utils/algoliaPaging';
import type { StoryItem, AlgoliaSearchResponse } from '../types';
const HITS_PER_PAGE = 50;
@@ -20,6 +21,7 @@ const MAX_EMPTY_PAGES_COLD_START = 3;
interface DomainCacheEntry {
stories: StoryItem[];
page: number;
+ before?: number;
hasMore: boolean;
seenIds: Set;
}
@@ -72,7 +74,7 @@ export function useDomainInfiniteStories(rawDomain: string) {
const [hasMore, setHasMore] = useState(initialCached?.hasMore ?? true);
const [prevDomain, setPrevDomain] = useState(domain);
- const nextPageRef = useRef(initialCached?.page ?? 0);
+ const nextPageRef = useRef({ page: initialCached?.page ?? 0, before: initialCached?.before });
const seenIdsRef = useRef>(new Set(initialCached?.seenIds ?? []));
const versionRef = useRef(0);
const inFlightRef = useRef(false);
@@ -105,7 +107,7 @@ export function useDomainInfiniteStories(rawDomain: string) {
// it. useEffect would leave a gap where resolved fetches slip through.
useLayoutEffect(() => {
const cached = domain ? domainCache.get(domain) : undefined;
- nextPageRef.current = cached?.page ?? 0;
+ nextPageRef.current = { page: cached?.page ?? 0, before: cached?.before };
seenIdsRef.current = new Set(cached?.seenIds ?? []);
storiesRef.current = cached?.stories ?? [];
versionRef.current += 1;
@@ -128,7 +130,7 @@ export function useDomainInfiniteStories(rawDomain: string) {
// Cold start pages on until a story lands: see MAX_EMPTY_PAGES_COLD_START.
do {
const pageToFetch = nextPageRef.current;
- const url = `${ALGOLIA_API}/search_by_date?tags=story&query=${encodeURIComponent(domain)}&restrictSearchableAttributes=url&hitsPerPage=${HITS_PER_PAGE}&page=${pageToFetch}`;
+ const url = `${ALGOLIA_API}/search_by_date?tags=story&query=${encodeURIComponent(domain)}&restrictSearchableAttributes=url&hitsPerPage=${HITS_PER_PAGE}${algoliaPageParams(pageToFetch)}`;
const response = await fetch(url);
if (!response.ok) {
@@ -189,7 +191,8 @@ export function useDomainInfiniteStories(rawDomain: string) {
return true;
});
- nextPageRef.current = data.page + 1;
+ const nextPage = nextAlgoliaPage(data, HITS_PER_PAGE, pageToFetch);
+ nextPageRef.current = nextPage ?? { ...pageToFetch, page: data.page + 1 };
// Cold-start cap. Snapshot before the storiesRef update below so the
// check reflects "had we shown anything before this fetch?", not "are
@@ -200,7 +203,7 @@ export function useDomainInfiniteStories(rawDomain: string) {
} else {
emptyPageStreakRef.current = 0;
}
- const algoliaHasMore = data.page < data.nbPages - 1;
+ const algoliaHasMore = nextPage !== null;
const capReached = emptyPageStreakRef.current >= MAX_EMPTY_PAGES_COLD_START;
newHasMore = algoliaHasMore && !capReached;
} while (uniqueStories.length === 0 && storiesRef.current.length === 0 && newHasMore);
@@ -214,7 +217,7 @@ export function useDomainInfiniteStories(rawDomain: string) {
storiesRef.current = updated;
domainCache.set(domain, {
stories: updated,
- page: nextPageRef.current,
+ ...nextPageRef.current,
hasMore: newHasMore,
seenIds: new Set(seenIdsRef.current),
});
@@ -251,7 +254,7 @@ export function useDomainInfiniteStories(rawDomain: string) {
setLoading(!!domain);
setError(null);
setHasMore(true);
- nextPageRef.current = 0;
+ nextPageRef.current = { page: 0 };
seenIdsRef.current = new Set();
storiesRef.current = [];
emptyPageStreakRef.current = 0;
diff --git a/src/hooks/useUserInfiniteStories.test.ts b/src/hooks/useUserInfiniteStories.test.ts
index 6eb8bee..9d5239e 100644
--- a/src/hooks/useUserInfiniteStories.test.ts
+++ b/src/hooks/useUserInfiniteStories.test.ts
@@ -244,6 +244,34 @@ describe('useUserInfiniteStories', () => {
});
});
+ describe('more submissions than search returns', () => {
+ it('loads past the last page from the oldest story so far', async () => {
+ const hit = (id: number, createdAt: number) => ({ ...body([id]).hits[0], created_at_i: createdAt });
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
+ const filter = new URL(fetchInputToUrl(input)).searchParams.get('numericFilters');
+ // Search stops at 1,000 hits and caps nbPages to match, so its last
+ // page doesn't reach nbHits.
+ return Promise.resolve(Response.json(filter === null
+ ? { hits: [hit(1, 300), hit(2, 200)], nbHits: 1500, nbPages: 1, page: 0, hitsPerPage: 50 }
+ : { hits: [hit(2, 200), hit(3, 100)], nbHits: 2, nbPages: 1, page: 0, hitsPerPage: 50 }));
+ });
+
+ const { result } = renderHook(() => useUserInfiniteStories('pg'));
+ await waitFor(() => expect(result.current.stories.map((s) => s.id)).toEqual([1, 2]));
+ expect(result.current.hasMore).toBe(true);
+
+ await act(async () => {
+ await result.current.loadMore();
+ });
+
+ const nextUrl = new URL(fetchInputToUrl(fetchSpy.mock.calls[1]?.[0]));
+ expect(nextUrl.searchParams.get('numericFilters')).toBe('created_at_i<=200');
+ expect(nextUrl.searchParams.get('page')).toBe('0');
+ expect(result.current.stories.map((s) => s.id)).toEqual([1, 2, 3]);
+ expect(result.current.hasMore).toBe(false);
+ });
+ });
+
describe('username change', () => {
it('discards stale state and re-fetches when username changes', async () => {
vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
diff --git a/src/hooks/useUserInfiniteStories.ts b/src/hooks/useUserInfiniteStories.ts
index 853c108..7ab7ffd 100644
--- a/src/hooks/useUserInfiniteStories.ts
+++ b/src/hooks/useUserInfiniteStories.ts
@@ -1,6 +1,7 @@
import { useState, useCallback, useRef, useEffect, useLayoutEffect } from 'react';
import { ALGOLIA_API } from '../config/api';
import { normalizeAlgoliaHit } from '../api/hn';
+import { algoliaPageParams, nextAlgoliaPage, type AlgoliaPageCursor } from '../utils/algoliaPaging';
import type { StoryItem, AlgoliaSearchResponse } from '../types';
const HITS_PER_PAGE = 50;
@@ -8,6 +9,7 @@ const HITS_PER_PAGE = 50;
interface UserCacheEntry {
stories: StoryItem[];
page: number;
+ before?: number;
hasMore: boolean;
seenIds: Set;
}
@@ -45,7 +47,7 @@ export function useUserInfiniteStories(username: string) {
const [hasMore, setHasMore] = useState(initialCached?.hasMore ?? true);
const [prevUsername, setPrevUsername] = useState(username);
- const nextPageRef = useRef(initialCached?.page ?? 0);
+ const nextPageRef = useRef({ page: initialCached?.page ?? 0, before: initialCached?.before });
const seenIdsRef = useRef>(new Set(initialCached?.seenIds ?? []));
const versionRef = useRef(0);
const inFlightRef = useRef(false);
@@ -69,7 +71,7 @@ export function useUserInfiniteStories(username: string) {
// before a stale in-flight fetch can check it.
useLayoutEffect(() => {
const cached = username ? userStoriesCache.get(username) : undefined;
- nextPageRef.current = cached?.page ?? 0;
+ nextPageRef.current = { page: cached?.page ?? 0, before: cached?.before };
seenIdsRef.current = new Set(cached?.seenIds ?? []);
storiesRef.current = cached?.stories ?? [];
versionRef.current += 1;
@@ -90,7 +92,7 @@ export function useUserInfiniteStories(username: string) {
// tags=story,author_X is an AND filter: only stories AND authored by X.
// search_by_date returns chronological newest-first, matching HN's
// /submitted ordering.
- const url = `${ALGOLIA_API}/search_by_date?tags=story,author_${encodeURIComponent(username)}&hitsPerPage=${HITS_PER_PAGE}&page=${pageToFetch}`;
+ const url = `${ALGOLIA_API}/search_by_date?tags=story,author_${encodeURIComponent(username)}&hitsPerPage=${HITS_PER_PAGE}${algoliaPageParams(pageToFetch)}`;
const response = await fetch(url);
if (!response.ok) {
@@ -113,10 +115,10 @@ export function useUserInfiniteStories(username: string) {
return true;
});
- const newPage = data.page + 1;
- nextPageRef.current = newPage;
+ const nextPage = nextAlgoliaPage(data, HITS_PER_PAGE, pageToFetch);
+ nextPageRef.current = nextPage ?? { ...pageToFetch, page: data.page + 1 };
- const newHasMore = data.page < data.nbPages - 1;
+ const newHasMore = nextPage !== null;
setHasMore(newHasMore);
// Compute outside updater to keep setStories pure (StrictMode-safe).
@@ -124,7 +126,7 @@ export function useUserInfiniteStories(username: string) {
storiesRef.current = updated;
userStoriesCache.set(username, {
stories: updated,
- page: newPage,
+ ...nextPageRef.current,
hasMore: newHasMore,
seenIds: new Set(seenIdsRef.current),
});
@@ -157,7 +159,7 @@ export function useUserInfiniteStories(username: string) {
setLoading(!!username);
setError(null);
setHasMore(true);
- nextPageRef.current = 0;
+ nextPageRef.current = { page: 0 };
seenIdsRef.current = new Set();
storiesRef.current = [];
if (username) userStoriesCache.delete(username);
diff --git a/src/utils/algoliaPaging.ts b/src/utils/algoliaPaging.ts
new file mode 100644
index 0000000..99c1511
--- /dev/null
+++ b/src/utils/algoliaPaging.ts
@@ -0,0 +1,31 @@
+import type { AlgoliaSearchResponse } from '../types';
+
+/** Where the next `search_by_date` request starts. */
+export interface AlgoliaPageCursor {
+ page: number;
+ /** Only hits created at or before this time (unix seconds). */
+ before?: number;
+}
+
+export function algoliaPageParams({ page, before }: AlgoliaPageCursor): string {
+ const filter = before === undefined ? '' : `&numericFilters=${encodeURIComponent(`created_at_i<=${before}`)}`;
+ return `&page=${page}${filter}`;
+}
+
+// Search returns at most 1,000 hits and caps nbPages to match. Results are
+// newest first, so past the last page the next request starts over at page 0
+// from the oldest hit so far. That hit comes back once; callers already dedup.
+export function nextAlgoliaPage(
+ data: AlgoliaSearchResponse,
+ hitsPerPage: number,
+ cursor: AlgoliaPageCursor,
+): AlgoliaPageCursor | null {
+ if (data.page < data.nbPages - 1) return { ...cursor, page: data.page + 1 };
+
+ const oldest = data.hits[data.hits.length - 1]?.created_at_i;
+ const isCapped = data.nbHits > data.nbPages * hitsPerPage;
+ if (isCapped && oldest !== undefined && oldest !== cursor.before) {
+ return { page: 0, before: oldest };
+ }
+ return null;
+}
From a5994edecca08f61790f7f2312dae85fd6e7eff3 Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Mon, 5 Oct 2026 15:54:14 +0200
Subject: [PATCH 6/6] fix: keep swipe mode off the 404 and not-found pages on a
phone
index.html adds the swipe-mode class before React loads, for routes that
will mount a swipe viewer. Its regex ended in an optional group with no
end anchor, so it matched every '#/' route. Only UserProfile cleared the
class again, so a phone that opened a 404, /item/abc, or an empty /from/
or /submitted/ directly kept the swipe viewer's body styles
(overflow: clip, no scrollbar) on a page that has no viewer.
The regex now lists the routes App.tsx gives a viewer: the feeds, a
numeric /item/, and a non-empty /from/ or /submitted/.
---
e2e/mobile-breakpoint.spec.ts | 24 ++++++++++++++++++++++++
e2e/user-profile.spec.ts | 16 ++++++----------
index.html | 6 ++++--
src/pages/UserProfile.test.tsx | 7 +++----
src/pages/UserProfile.tsx | 9 ++++-----
5 files changed, 41 insertions(+), 21 deletions(-)
diff --git a/e2e/mobile-breakpoint.spec.ts b/e2e/mobile-breakpoint.spec.ts
index 00767be..195ab1e 100644
--- a/e2e/mobile-breakpoint.spec.ts
+++ b/e2e/mobile-breakpoint.spec.ts
@@ -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', () => {
diff --git a/e2e/user-profile.spec.ts b/e2e/user-profile.spec.ts
index 479348c..c612425 100644
--- a/e2e/user-profile.spec.ts
+++ b/e2e/user-profile.spec.ts
@@ -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
- // and 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();
diff --git a/index.html b/index.html
index 1169fe8..d39e1c7 100644
--- a/index.html
+++ b/index.html
@@ -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');
diff --git a/src/pages/UserProfile.test.tsx b/src/pages/UserProfile.test.tsx
index 12a7e3f..01d34b6 100644
--- a/src/pages/UserProfile.test.tsx
+++ b/src/pages/UserProfile.test.tsx
@@ -173,10 +173,9 @@ describe('UserProfile', () => {
describe('mobile swipe-mode bug', () => {
// The bootstrap script in index.html applies `swipe-mode` to /
- // for all `#/...` routes on mobile so the swipe viewers don't double-paint
- // a scrollable page first. UserProfile is vertically scrollable, so it
- // must imperatively turn that class off on mount or direct loads end up
- // with `body { overflow: clip }` and the page can't scroll.
+ // on mobile so the swipe viewers don't double-paint a scrollable page
+ // first. UserProfile is vertically scrollable, so it turns that class off
+ // on mount, or a page left with `body { overflow: clip }` can't scroll.
it('removes the swipe-mode class from and on mount', async () => {
document.documentElement.classList.add('swipe-mode');
document.body.classList.add('swipe-mode');
diff --git a/src/pages/UserProfile.tsx b/src/pages/UserProfile.tsx
index c815100..c994e8e 100644
--- a/src/pages/UserProfile.tsx
+++ b/src/pages/UserProfile.tsx
@@ -36,11 +36,10 @@ export function UserProfile() {
const { disableSwipeMode } = useScrollContainer();
// index.html optimistically applies `swipe-mode` to /
- // for any `#/...` route on mobile so swipe viewers don't double-
- // paint a scrollable page first. This page IS vertically scrollable,
- // so we undo that on mount or `overflow: clip` sticks on direct
- // load (`https://.../#/user/pg`). Desktop is a no-op via the
- // provider's noop fallback.
+ // on mobile, before React, so swipe viewers don't double-paint a
+ // scrollable page first. This page IS vertically scrollable, so we
+ // make sure it's off on mount, or `overflow: clip` would stick.
+ // Desktop is a no-op via the provider's noop fallback.
//
// useLayoutEffect (not useEffect): the class removal MUST run before
// first paint to avoid a one-frame window where mid-flick gestures