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/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-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/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts index a42f880..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. @@ -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 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/App.test.tsx b/src/App.test.tsx index 3ab4549..960afd9 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -1,8 +1,9 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { screen, fireEvent } from '@testing-library/react'; -import { Routes, Route, Link } from 'react-router'; +import { Routes, Route, Link, useNavigate } from 'react-router'; import { render } from './test/test-utils'; import { MobileItemDetailWrapper, MobileStoryListWrapper } from './App'; +import { fetchItemOnly } from './api/hn'; import { saveSwipePosition } from './utils/swipePosition'; import { createStoryItem } from './test/factories'; import type { LocationState, StoryItem } from './types'; @@ -17,9 +18,18 @@ vi.mock('./components/SwipeStoryViewer', async () => { const { useState } = await import('react'); return { SwipeStoryViewer: function SwipeStoryViewer({ type, initialItemId }: { type: string; initialItemId?: string }) { - // Frozen at mount: a reused instance keeps the feed it was mounted for. + // Frozen at mount: a reused instance keeps the feed and item it was mounted for. const [mountedType] = useState(type); - return
; + const [mountedItem] = useState(initialItemId ?? ''); + return ( +
+ ); }, }; }); @@ -140,6 +150,41 @@ describe('MobileItemDetailWrapper — viewer recovery (stateless reload)', () => }); }); +describe('MobileItemDetailWrapper — direct link', () => { + beforeEach(() => { + sessionStorage.clear(); + }); + + function SwipeToNextStory() { + const navigate = useNavigate(); + // What the swipe viewer does when the first swipe lands on the next story. + return ( + + ); + } + + it('keeps the story viewer when the first swipe adds `from: top` to the URL state', async () => { + vi.mocked(fetchItemOnly).mockResolvedValueOnce(createStoryItem({ id: 88888 })); + render( + + } /> + , + { initialEntries: ['/item/88888'] }, + ); + expect(await screen.findByTestId('feed-viewer')).toHaveAttribute('data-item', '88888'); + + fireEvent.click(screen.getByRole('button', { name: 'swipe' })); + + // A new instance would start over from 12345 and lose 88888, the story + // the link opened, which isn't in the Top feed. + const viewer = screen.getByTestId('feed-viewer'); + expect(viewer).toHaveAttribute('data-item', '12345'); + expect(viewer).toHaveAttribute('data-mounted-item', '88888'); + }); +}); + describe('MobileItemDetailWrapper — ids that are not numbers', () => { it.each(['abc', '1.5', '-1'])('shows "Item not found" for /item/%s instead of a feed', (id) => { renderWrapper(id, { from: 'top' }); diff --git a/src/App.tsx b/src/App.tsx index 10dd696..78ada1a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -19,7 +19,7 @@ import { SwipeCommentViewer } from './components/SwipeCommentViewer'; import { NetworkStatusProvider } from './context/NetworkStatusContext'; import { fetchItemOnly } from './api/hn'; import { readSwipePosition } from './utils/swipePosition'; -import type { FeedType, LocationState } from './types'; +import type { FeedType, LocationState, SwipePosition } from './types'; // Exported for focused unit testing. export function MobileStoryListWrapper({ type }: { type: FeedType }) { @@ -103,41 +103,58 @@ export function MobileItemDetailWrapper() { // HN ids are numeric. The swipe viewer can't fetch anything else, and its // NaN id never matches the failed fetch, so it would show the Top feed. - if (!id || !/^\d+$/.test(id)) { + const isNumericId = id !== undefined && /^\d+$/.test(id); + const viewer = canSwipe && isNumericId + ? pickSwipeViewer(location.state as LocationState | null, recovered, id) + : null; + const isResolvedStory = useResolveDirectLink(id, canSwipe && isNumericId && !viewer); + + if (!isNumericId) { return ; } - + if (canSwipe) { - const state = location.state as LocationState | null; + if (viewer) return viewer; - // Branch 1: Known comment → SwipeCommentViewer immediately. - // Comments take priority over user/domain/from to match the header pill - // priority (comments > user > from). - if (state?.isComment) { - return ; - } + // Branch 5: Direct URL (no state) → resolve type first. The story viewer + // must be the element Branch 4 renders for `{ from: 'top' }`: the first + // swipe writes that state, and a different element there would remount + // the viewer and drop the story this link opened. + if (isResolvedStory) return renderSwipeViewer({ from: 'top' }, id); + return ; + } + + return ; +} - // Branches 2–4: viewer context from location.state (zero-latency path). - if (state) { - const viewer = renderSwipeViewer(state, id); - if (viewer) return viewer; - } +function pickSwipeViewer( + state: LocationState | null, + recovered: SwipePosition | null, + id: string, +): ReactNode { + // Branch 1: Known comment → SwipeCommentViewer immediately. + // Comments take priority over user/domain/from to match the header pill + // priority (comments > user > from). + if (state?.isComment) { + return ; + } - // Branch 4b: stateless reload — recover the viewer from the snapshot so - // non-`top` feeds (best/show/ask/domain/user) restore too. Snapshots come only - // from story viewers, so we skip the resolver's comment-vs-story fetch. Also - // fires for a fresh same-tab nav to a still-snapshotted id+viewer (intended: - // resume where you left off), not just back/reload. - if (recovered?.storyId === Number(id)) { - const viewer = renderSwipeViewer(recovered.viewer, id); - if (viewer) return viewer; - } + // Branches 2–4: viewer context from location.state (zero-latency path). + if (state) { + const viewer = renderSwipeViewer(state, id); + if (viewer) return viewer; + } - // Branch 5: Direct URL (no state) → resolve type first - return ; + // Branch 4b: stateless reload — recover the viewer from the snapshot so + // non-`top` feeds (best/show/ask/domain/user) restore too. Snapshots come only + // from story viewers, so we skip the resolver's comment-vs-story fetch. Also + // fires for a fresh same-tab nav to a still-snapshotted id+viewer (intended: + // resume where you left off), not just back/reload. + if (recovered?.storyId === Number(id)) { + return renderSwipeViewer(recovered.viewer, id); } - - return ; + + return null; } function ItemNotFound() { @@ -149,25 +166,15 @@ function ItemNotFound() { ); } -// Resolves item type for a direct URL hit on mobile (no `location.state`), -// then mounts the matching viewer. -function MobileItemResolver({ id }: { id: string }) { - const [itemType, setItemType] = useState<'story' | null>(null); +// Resolves item type for a direct URL hit on mobile (no `location.state`): +// a comment re-routes to Branch 1, and anything else reports `true` so the +// wrapper mounts the story viewer. +function useResolveDirectLink(id: string | undefined, enabled: boolean): boolean { + const [storyId, setStoryId] = useState(null); const navigate = useNavigate(); - const { enableSwipeMode, disableSwipeMode } = useScrollContainer(); - - // The skeleton below is the viewer's own panel, and it pads for the fixed - // chrome itself — so React has to know this is swipe mode before paint, or - // `
` reserves the header a second time and the skeleton starts 56px - // low, then jumps when the viewer takes over. Before paint, and paired with - // a release, for the same reasons useSwipeScroll's own call is. - useLayoutEffect(() => { - enableSwipeMode(); - return disableSwipeMode; - }, [enableSwipeMode, disableSwipeMode]); useEffect(() => { - if (!id) return; + if (!enabled || !id) return; const controller = new AbortController(); void fetchItemOnly(id, controller.signal) @@ -177,21 +184,33 @@ function MobileItemResolver({ id }: { id: string }) { // Navigate with state so MobileItemDetailWrapper Branch 1 picks it up void navigate(`/item/${id}`, { replace: true, state: { isComment: true } }); } else { - setItemType('story'); + setStoryId(id); } }) .catch(() => { if (controller.signal.aborted) return; // Default to story viewer on error (it has its own error handling) - setItemType('story'); + setStoryId(id); }); return () => controller.abort(); - }, [id, navigate]); + }, [id, enabled, navigate]); - if (itemType === 'story') { - return ; - } + return storyId !== null && storyId === id; +} + +function MobileItemResolverSkeleton() { + const { enableSwipeMode, disableSwipeMode } = useScrollContainer(); + + // The skeleton below is the viewer's own panel, and it pads for the fixed + // chrome itself — so React has to know this is swipe mode before paint, or + // `
` reserves the header a second time and the skeleton starts 56px + // low, then jumps when the viewer takes over. Before paint, and paired with + // a release, for the same reasons useSwipeScroll's own call is. + useLayoutEffect(() => { + enableSwipeMode(); + return disableSwipeMode; + }, [enableSwipeMode, disableSwipeMode]); return (
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[] { 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/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/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; } 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 => { 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/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 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; +}