diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts index 3e932f1..a42f880 100644 --- a/e2e/mobile-swipe.spec.ts +++ b/e2e/mobile-swipe.spec.ts @@ -4,7 +4,7 @@ import { createFirebaseWsHandler, FIREBASE_WS_PATTERN, } from './fixtures/api-mocks'; -import { ALGOLIA_API } from './fixtures/mock-data'; +import { ALGOLIA_API, mockTopItemIds } from './fixtures/mock-data'; import { expectActiveSwipePanelText, getActiveSwipePanel, @@ -393,6 +393,25 @@ test.describe('Mobile Swipe Viewer', () => { await expect(page).toHaveURL(/\/item\/12345/, { timeout: 5000 }); }); + test('switching feeds while the first one is still loading shows only the new feed', async ({ page }) => { + // Every Firebase read takes 1.5s, so Top's first page is still loading at the click. + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ delayMs: 1500 })); + await page.goto('/#/'); + await expect(page.getByTestId('swipe-container')).toBeVisible(); + await expect(page.locator('[data-item-id]')).toHaveCount(0); + + await page.getByRole('link', { name: 'best', exact: true }).click({ force: true }); + + await expect(page).toHaveURL(/\/item\/33001/, { timeout: 15000 }); + await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', '33001'); + await waitForSwipeReady(page, 3); + const ids = await page.locator('[data-item-id]').evaluateAll( + (els) => els.map((el) => Number(el.getAttribute('data-item-id'))), + ); + expect(ids).toEqual(expect.arrayContaining([33001, 33002, 33003])); + expect(ids.filter((id) => mockTopItemIds.includes(id))).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. @@ -477,6 +496,14 @@ test.describe('Mobile Direct Item Access', () => { await expect(page.getByText(/not found/i)).toBeVisible(); }); + test('shows not found for an item id that is not a number', async ({ page }) => { + await page.goto('/#/item/abc'); + + await expect(page.getByRole('heading', { name: 'Item not found' })).toBeVisible(); + await expect(page).toHaveTitle(/Item not found.*HackerTok/); + await expect(page.locator('[data-item-id]')).toHaveCount(0); + }); + test('restores swipe position when navigating back from not-found item', async ({ page }) => { // Regression: swiping away from index 0, then navigating to a non-existent item, // then pressing back should restore the scroll position (not reset to index 0). @@ -663,6 +690,28 @@ test.describe('Mobile Direct Item Access', () => { await expect(page.getByText(/curious what side projects everyone is working on/i)).toBeVisible(); }); + test('keeps the Ask HN body after visiting the author and going Back, and after a reload', async ({ page }) => { + // The saved swipe position stores stories without their body, and the + // restored copy is what the panel renders. + await page.goto('/#/ask'); + await expect(page).toHaveURL(/\/item\/88888/); + const body = () => getActiveSwipePanel(page).getByText(/curious what side projects everyone is working on/i); + await expect(body()).toBeVisible(); + + await getActiveSwipePanel(page).locator('a[href^="#/user/"]').first().click(); + await expect(page).toHaveURL(/\/user\//, { timeout: 5000 }); + + await page.goBack(); + await expect(page).toHaveURL(/\/item\/88888/, { timeout: 5000 }); + await expectActiveSwipePanelText(page, 'Ask HN: What are you working on?'); + await expect(body()).toBeVisible(); + + await page.reload(); + await expect(page).toHaveURL(/\/item\/88888/, { timeout: 5000 }); + await expectActiveSwipePanelText(page, 'Ask HN: What are you working on?'); + await expect(body()).toBeVisible(); + }); + test('navigating directly to a comment shows comment in swipe viewer', async ({ page }) => { await page.goto('/#/item/1001'); diff --git a/e2e/story-browsing.spec.ts b/e2e/story-browsing.spec.ts index e59c673..08c8dd0 100644 --- a/e2e/story-browsing.spec.ts +++ b/e2e/story-browsing.spec.ts @@ -154,6 +154,44 @@ test.describe('Item Browsing - Desktop Scroll Restoration', () => { }); }); +test.describe('Item Browsing - Desktop Back between feeds', () => { + test.use({ viewport: { width: 1280, height: 720 } }); + + test.beforeEach(async ({ page }) => { + await setupApiMocks(page); + }); + + test('does not repeat stories after going Back to a feed you opened a story from', async ({ page }, testInfo) => { + if (testInfo.project.name.startsWith('Mobile')) { + test.skip(); + return; + } + const cards = page.locator('[data-testid="story-card"]'); + + await page.goto('/#/best'); + await expect(cards).toHaveCount(3); + + // Opening a story saves Best's session. + await page.locator('[data-story-id="33001"]').getByRole('link', { name: /comments/i }).click(); + await expect(page).toHaveURL(/\/item\/33001/); + await page.goBack(); + await expect(cards).toHaveCount(3); + + await page.getByRole('link', { name: 'show', exact: true }).click(); + await expect(page).toHaveURL(/\/show$/); + await expect(page.locator('[data-story-id="99999"]')).toBeVisible(); + + // The list stays mounted, so Back to Best resets it rather than remounting. + await page.goBack(); + await expect(page).toHaveURL(/\/best$/); + // reset() drops the session and re-arms hasMore, so the end marker only + // returns once the load after it finishes. + await expect.poll(() => page.evaluate(() => sessionStorage.getItem('feed:session:best'))).toBeNull(); + await expect(page.getByText("You've reached the end")).toBeVisible(); + await expect(cards).toHaveCount(3); + }); +}); + /** * Error handling tests use fixtureTest which provides errorMockedPage. * This fixture sets up routes on browserContext BEFORE page creation, diff --git a/src/App.test.tsx b/src/App.test.tsx index 8d9a3ab..3ab4549 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -1,8 +1,8 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { screen } from '@testing-library/react'; -import { Routes, Route } from 'react-router'; +import { screen, fireEvent } from '@testing-library/react'; +import { Routes, Route, Link } from 'react-router'; import { render } from './test/test-utils'; -import { MobileItemDetailWrapper } from './App'; +import { MobileItemDetailWrapper, MobileStoryListWrapper } from './App'; import { saveSwipePosition } from './utils/swipePosition'; import { createStoryItem } from './test/factories'; import type { LocationState, StoryItem } from './types'; @@ -13,11 +13,16 @@ vi.mock('./hooks/useCanSwipe', () => ({ useCanSwipe: () => true })); // Stub the heavy swipe viewers so we can assert *which* viewer the wrapper // mounts (and with what props) without their data hooks / async state. -vi.mock('./components/SwipeStoryViewer', () => ({ - SwipeStoryViewer: ({ type, initialItemId }: { type: string; initialItemId?: string }) => ( -
- ), -})); +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. + const [mountedType] = useState(type); + return
; + }, + }; +}); vi.mock('./components/SwipeDomainStoryViewer', () => ({ SwipeDomainStoryViewer: ({ domain, initialItemId }: { domain: string; initialItemId?: string }) => (
@@ -37,7 +42,7 @@ vi.mock('./api/hn', async (importOriginal) => ({ fetchItemOnly: vi.fn(() => new Promise(() => { /* never resolves */ })), })); -function renderWrapper(id: number, state?: LocationState) { +function renderWrapper(id: number | string, state?: LocationState) { return render( } /> @@ -134,3 +139,35 @@ describe('MobileItemDetailWrapper — viewer recovery (stateless reload)', () => expect(screen.queryByTestId('user-viewer')).toBeNull(); }); }); + +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' }); + + expect(screen.getByRole('heading', { name: 'Item not found' })).toBeInTheDocument(); + expect(screen.queryByTestId('feed-viewer')).toBeNull(); + expect(screen.queryByTestId('swipe-container')).toBeNull(); + expect(document.title).toMatch(/^Item not found/); + }); +}); + +describe('MobileStoryListWrapper', () => { + it('mounts a new viewer when you switch feeds before the URL moves to a story', () => { + render( + <> + + } /> + } /> + + best + , + ); + expect(screen.getByTestId('feed-viewer')).toHaveAttribute('data-mounted-type', 'top'); + + fireEvent.click(screen.getByRole('link', { name: 'best' })); + + const viewer = screen.getByTestId('feed-viewer'); + expect(viewer).toHaveAttribute('data-type', 'best'); + expect(viewer).toHaveAttribute('data-mounted-type', 'best'); + }); +}); diff --git a/src/App.tsx b/src/App.tsx index 71a57d5..10dd696 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -21,11 +21,16 @@ import { fetchItemOnly } from './api/hn'; import { readSwipePosition } from './utils/swipePosition'; import type { FeedType, LocationState } from './types'; -function MobileStoryListWrapper({ type }: { type: FeedType }) { +// Exported for focused unit testing. +export function MobileStoryListWrapper({ type }: { type: FeedType }) { const canSwipe = useCanSwipe(); if (canSwipe) { - return ; + // key={type}: every feed route renders this wrapper, so a tab switch made + // before the viewer moves the URL to /item/:id (first load still running, + // or a failed one) would otherwise keep the previous feed's stories and + // let its in-flight page land in the new feed. + return ; } return ; @@ -95,6 +100,12 @@ export function MobileItemDetailWrapper() { // Newest snapshot taken on this story, read once (sticky for the wrapper's life); // used only by Branch 4b to recover the viewer on a stateless reload. const [recovered] = useState(() => readSwipePosition({ storyId: Number(id) })); + + // 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)) { + return ; + } if (canSwipe) { const state = location.state as LocationState | null; @@ -102,7 +113,7 @@ export function MobileItemDetailWrapper() { // 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 && id) { + if (state?.isComment) { return ; } @@ -117,18 +128,27 @@ export function MobileItemDetailWrapper() { // 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 && id && recovered.storyId === Number(id)) { + if (recovered?.storyId === Number(id)) { const viewer = renderSwipeViewer(recovered.viewer, id); if (viewer) return viewer; } // Branch 5: Direct URL (no state) → resolve type first - return ; + return ; } return ; } +function ItemNotFound() { + useDocumentTitle('Item not found'); + return ( +
+ +
+ ); +} + // Resolves item type for a direct URL hit on mobile (no `location.state`), // then mounts the matching viewer. function MobileItemResolver({ id }: { id: string }) { diff --git a/src/api/hn.ts b/src/api/hn.ts index 3677320..f48a653 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -586,22 +586,30 @@ export async function prefetchItemComments(id: number | string, signal?: AbortSi } export async function fetchCommentsForItem(id: number | string, signal: AbortSignal | null = null): Promise { + return (await fetchItemWithComments(id, signal)).comments; +} + +/** The comment tree plus the item it hangs off, which the ordering reads anyway. */ +export async function fetchItemWithComments(id: number | string, signal: AbortSignal | null = null): Promise { const itemId = Number(id); - + if (signal?.aborted) { throw new DOMException('Aborted', 'AbortError'); } - + const [item, comments] = await Promise.all([ fetchFirebaseItem(itemId, signal ?? undefined), fetchAllCommentsAlgolia(itemId, signal ?? undefined), ]); - + if (signal?.aborted) { throw new DOMException('Aborted', 'AbortError'); } - - return buildOrderedCommentTree(comments, itemId, item?.kids, signal ?? undefined); + + return { + item: normalizeFirebaseItem(item), + comments: await buildOrderedCommentTree(comments, itemId, item.kids, signal ?? undefined), + }; } // Algolia /items/{id} returns the full nested children tree in one request. diff --git a/src/components/CommentArticle.test.tsx b/src/components/CommentArticle.test.tsx index b219fe9..acf58b1 100644 --- a/src/components/CommentArticle.test.tsx +++ b/src/components/CommentArticle.test.tsx @@ -116,6 +116,28 @@ describe('CommentArticle', () => { ).toHaveAttribute('href', '/item/12345'); }); + it('keeps the placeholder, not the "story" fallback, while the title is still loading', () => { + render( + , + ); + + expect(screen.queryByText(/^story$/i)).not.toBeInTheDocument(); + const article = screen.getByRole('article'); + expect(article.querySelectorAll('.animate-pulse').length).toBeGreaterThan(0); + // The title fetch can hang until reconnect, so the way back to the + // story must not wait for it. + const link = screen.getByRole('link', { name: /^story$/i }); + expect(link).toHaveAttribute('href', '/item/12345'); + expect(link.querySelector('.animate-pulse')).not.toBeNull(); + }); + it('falls back to a generic "story" link when loading settles without a title', () => { // Failure mode: parent fetch errored or returned a titleless item. // Without the fallback, the skeleton would pulse forever and a diff --git a/src/components/CommentArticle.tsx b/src/components/CommentArticle.tsx index e9e1514..4534a7e 100644 --- a/src/components/CommentArticle.tsx +++ b/src/components/CommentArticle.tsx @@ -21,6 +21,8 @@ interface CommentArticleProps { replies: Comment[]; itemId: number | null; itemTitle: string | null; + /** The thread title is still being fetched (after `loading` clears). */ + itemTitleLoading?: boolean; loading: boolean; articleClassName?: string; /** Story author for OP detection. */ @@ -32,6 +34,7 @@ export function CommentArticle({ replies, itemId, itemTitle, + itemTitleLoading = false, loading, articleClassName = 'mb-4', storyAuthor = '', @@ -76,7 +79,19 @@ export function CommentArticle({ {itemTitle} - ) : itemId != null && !loading ? ( + ) : itemId != null && (loading || itemTitleLoading) ? ( + // Title still on its way: already a link, because the title + // fetch has no timeout and can wait out a dropped connection. + + + + + ) : itemId != null ? ( // Resolved-but-titleless fallback (parent fetch errored // or returned without a title). Show a generic "story" // link so the user still has a path back to the root diff --git a/src/components/CommentDetail.tsx b/src/components/CommentDetail.tsx index 758067c..e4899b6 100644 --- a/src/components/CommentDetail.tsx +++ b/src/components/CommentDetail.tsx @@ -42,7 +42,7 @@ export function CommentDetailSkeleton() { } export function CommentDetail({ commentId, initialData }: CommentDetailProps) { - const { comment, replies, itemId, itemTitle, itemAuthor, loading, error, retry } = useCommentDetail(commentId, initialData); + const { comment, replies, itemId, itemTitle, itemTitleLoading, itemAuthor, loading, error, retry } = useCommentDetail(commentId, initialData); const navigate = useNavigate(); const location = useLocation(); const locationState = location.state as LocationState | null; @@ -99,6 +99,7 @@ export function CommentDetail({ commentId, initialData }: CommentDetailProps) { replies={replies} itemId={itemId} itemTitle={itemTitle} + itemTitleLoading={itemTitleLoading} loading={loading} articleClassName="mb-6" storyAuthor={itemAuthor ?? ''} diff --git a/src/components/FullScreenComment.tsx b/src/components/FullScreenComment.tsx index 9cb9f2e..5145b88 100644 --- a/src/components/FullScreenComment.tsx +++ b/src/components/FullScreenComment.tsx @@ -45,7 +45,7 @@ interface FullScreenCommentProps { } export function FullScreenComment({ commentId, onAuthorLoaded }: FullScreenCommentProps) { - const { comment, replies, itemId, itemTitle, itemAuthor, loading, error, retry } = useCommentDetail(commentId); + const { comment, replies, itemId, itemTitle, itemTitleLoading, itemAuthor, loading, error, retry } = useCommentDetail(commentId); const { isOnline } = useNetworkStatus(); const { isRetrying } = useAutoRetry({ @@ -93,6 +93,7 @@ export function FullScreenComment({ commentId, onAuthorLoaded }: FullScreenComme replies={replies} itemId={itemId} itemTitle={itemTitle} + itemTitleLoading={itemTitleLoading} loading={loading} storyAuthor={itemAuthor ?? ''} /> diff --git a/src/components/SwipeCommentViewer.test.tsx b/src/components/SwipeCommentViewer.test.tsx index a29ca92..fede065 100644 --- a/src/components/SwipeCommentViewer.test.tsx +++ b/src/components/SwipeCommentViewer.test.tsx @@ -52,6 +52,61 @@ describe('SwipeCommentViewer', () => { }); }); + it('does not throw on a back-forward cache restore with site storage blocked', async () => { + window.scrollTo = vi.fn(); + render(, { + initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }], + }); + await waitFor(() => { + expect(screen.getAllByTestId('swipe-panel')).toHaveLength(4); + }); + + // Blocking site data makes the `sessionStorage` getter itself throw. + const storage = Object.getOwnPropertyDescriptor(globalThis, 'sessionStorage')!; + Object.defineProperty(globalThis, 'sessionStorage', { + configurable: true, + get() { throw new DOMException('Access is denied for this document.', 'SecurityError'); }, + }); + const onError = vi.fn((event: ErrorEvent) => event.preventDefault()); + window.addEventListener('error', onError); + try { + window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true })); + window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })); + } finally { + window.removeEventListener('error', onError); + Object.defineProperty(globalThis, 'sessionStorage', storage); + } + + expect(onError).not.toHaveBeenCalled(); + expect(window.scrollTo).toHaveBeenLastCalledWith(0, 0); + }); + + it('restores the offset on a back-forward cache restore over 30 minutes later', async () => { + window.scrollTo = vi.fn(); + render(, { + initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }], + }); + await waitFor(() => { + expect(screen.getAllByTestId('swipe-panel')).toHaveLength(4); + }); + + const now = Date.now(); + const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(now); + const scrollY = Object.getOwnPropertyDescriptor(window, 'scrollY'); + Object.defineProperty(window, 'scrollY', { configurable: true, value: 500 }); + try { + window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true })); + nowSpy.mockReturnValue(now + 31 * 60 * 1000); + window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })); + } finally { + nowSpy.mockRestore(); + if (scrollY) Object.defineProperty(window, 'scrollY', scrollY); + else delete (window as { scrollY?: unknown }).scrollY; + } + + expect(window.scrollTo).toHaveBeenLastCalledWith(0, 500); + }); + it('renders sibling comment panels after loading', async () => { render(, { initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }], diff --git a/src/components/SwipeCommentViewer.tsx b/src/components/SwipeCommentViewer.tsx index 6cd9d96..7064825 100644 --- a/src/components/SwipeCommentViewer.tsx +++ b/src/components/SwipeCommentViewer.tsx @@ -103,17 +103,16 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps } }, [scrollInitialized, currentIndex, siblingIds, navigate, location.pathname]); - // Save/restore scrollY for bfcache + // Save/restore scrollY for bfcache. In memory, not storage: bfcache keeps the + // JS heap, and stored values can be blocked or expire. + const scrollYOnHideRef = useRef(0); useEffect(() => { const handlePageHide = () => { - try { - sessionStorage.setItem('__swipe_comment_scrollY', String(window.scrollY)); - } catch { /* quota exceeded — non-critical */ } + scrollYOnHideRef.current = window.scrollY; }; const handlePageShow = (event: PageTransitionEvent) => { if (event.persisted) { - const savedY = Number(sessionStorage.getItem('__swipe_comment_scrollY')) || 0; - window.scrollTo(0, savedY); + window.scrollTo(0, scrollYOnHideRef.current); } }; window.addEventListener('pagehide', handlePageHide); diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx index 8ace2c1..7baf5f3 100644 --- a/src/components/SwipeStoryViewer.test.tsx +++ b/src/components/SwipeStoryViewer.test.tsx @@ -456,6 +456,67 @@ describe('SwipeStoryViewerCore — swipe-position restore', () => { expect(saved?.viewer).toEqual({ from: 'top' }); }); + it('does not throw when the tab is hidden and shown with site storage blocked', () => { + const stories = [createStoryItem({ id: 1 }), createStoryItem({ id: 2 })]; + render( + , + ); + + // Blocking site data makes the `sessionStorage` getter itself throw. + const storage = Object.getOwnPropertyDescriptor(globalThis, 'sessionStorage')!; + Object.defineProperty(globalThis, 'sessionStorage', { + configurable: true, + get() { throw new DOMException('Access is denied for this document.', 'SecurityError'); }, + }); + const onError = vi.fn((event: ErrorEvent) => event.preventDefault()); + window.addEventListener('error', onError); + const showTab = (state: 'hidden' | 'visible') => { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }); + act(() => { + document.dispatchEvent(new Event('visibilitychange')); + }); + }; + try { + showTab('hidden'); + showTab('visible'); + } finally { + window.removeEventListener('error', onError); + Object.defineProperty(globalThis, 'sessionStorage', storage); + delete (document as { visibilityState?: unknown }).visibilityState; + } + + expect(onError).not.toHaveBeenCalled(); + expect(window.scrollTo).toHaveBeenLastCalledWith(0, 0); + }); + + it('restores the offset within the story when the tab comes back over 30 minutes later', () => { + const stories = [createStoryItem({ id: 1 }), createStoryItem({ id: 2 })]; + render(); + + const now = Date.now(); + const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(now); + const scrollY = Object.getOwnPropertyDescriptor(window, 'scrollY'); + Object.defineProperty(window, 'scrollY', { configurable: true, value: 500 }); + const showTab = (state: 'hidden' | 'visible') => { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }); + act(() => { + document.dispatchEvent(new Event('visibilitychange')); + }); + }; + try { + showTab('hidden'); + nowSpy.mockReturnValue(now + 31 * 60 * 1000); + showTab('visible'); + } finally { + nowSpy.mockRestore(); + if (scrollY) Object.defineProperty(window, 'scrollY', scrollY); + else delete (window as { scrollY?: unknown }).scrollY; + delete (document as { visibilityState?: unknown }).visibilityState; + } + + expect(window.scrollTo).toHaveBeenLastCalledWith(0, 500); + }); + it('persists a snapshot of the current story when the viewer unmounts', () => { const stories = [createStoryItem({ id: 1 }), createStoryItem({ id: 2 }), createStoryItem({ id: 3 })]; diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx index 7947f50..c369c77 100644 --- a/src/components/SwipeStoryViewer.tsx +++ b/src/components/SwipeStoryViewer.tsx @@ -322,6 +322,9 @@ export function SwipeStoryViewerCore({ // Uses both pageshow (for bfcache) and visibilitychange (for tab switches) // pageshow fires BEFORE first paint on bfcache restore - critical for preventing flash const savedIndexOnHideRef = useRef(null); + // In memory, not storage: both restores run in the page that was hidden + // (bfcache keeps the JS heap), and stored values can be blocked or expire. + const savedScrollYOnHideRef = useRef(0); // Synced via effect so the long-lived hide listener reads the latest list/viewer // without re-subscribing (avoids a stale closure). const mergedStoriesRef = useRef(mergedStories); @@ -366,9 +369,7 @@ export function SwipeStoryViewerCore({ // Save position + scrollY when page is about to be hidden/cached const handlePageHide = () => { savedIndexOnHideRef.current = currentIndexRef.current; - try { - sessionStorage.setItem('__swipe_scrollY', String(window.scrollY)); - } catch { /* quota exceeded — non-critical */ } + savedScrollYOnHideRef.current = window.scrollY; persistSnapshot(); }; @@ -380,8 +381,7 @@ export function SwipeStoryViewerCore({ savedIndexOnHideRef.current = null; scrollToIndex(targetIndex); // Restore scrollY after panel activation - const savedY = Number(sessionStorage.getItem('__swipe_scrollY')) || 0; - window.scrollTo(0, savedY); + window.scrollTo(0, savedScrollYOnHideRef.current); } }; @@ -389,16 +389,13 @@ export function SwipeStoryViewerCore({ const handleVisibilityChange = () => { if (document.visibilityState === 'hidden') { savedIndexOnHideRef.current = currentIndexRef.current; - try { - sessionStorage.setItem('__swipe_scrollY', String(window.scrollY)); - } catch { /* quota exceeded — non-critical */ } + savedScrollYOnHideRef.current = window.scrollY; persistSnapshot(); } else if (document.visibilityState === 'visible' && savedIndexOnHideRef.current !== null) { const targetIndex = savedIndexOnHideRef.current; savedIndexOnHideRef.current = null; scrollToIndex(targetIndex); - const savedY = Number(sessionStorage.getItem('__swipe_scrollY')) || 0; - window.scrollTo(0, savedY); + window.scrollTo(0, savedScrollYOnHideRef.current); } }; diff --git a/src/hooks/useCommentDetail.test.ts b/src/hooks/useCommentDetail.test.ts index a437882..5526ba9 100644 --- a/src/hooks/useCommentDetail.test.ts +++ b/src/hooks/useCommentDetail.test.ts @@ -58,6 +58,26 @@ describe('useCommentDetail', () => { }); }); + it('reports the item title as loading until its fetch settles', async () => { + let resolveStory!: (item: FirebaseItem) => void; + vi.spyOn(hnSdk, 'readItem').mockImplementation(() => new Promise(resolve => { resolveStory = resolve; })); + + const { result } = renderHook(() => useCommentDetail(1001)); + + await waitFor(() => { + expect(result.current.loading).toBe(false); + }); + expect(result.current.itemTitle).toBeNull(); + expect(result.current.itemTitleLoading).toBe(true); + + resolveStory(mockStoryItem); + + await waitFor(() => { + expect(result.current.itemTitleLoading).toBe(false); + }); + expect(result.current.itemTitle).toBe('Rust Is the Future of JavaScript Infrastructure'); + }); + it('uses initialData for immediate display', async () => { const initialData = { author: 'patio11', @@ -113,6 +133,9 @@ describe('useCommentDetail', () => { // Item title is non-blocking: missing title must NOT propagate as an error. expect(result.current.itemTitle).toBeNull(); expect(result.current.error).toBeNull(); + await waitFor(() => { + expect(result.current.itemTitleLoading).toBe(false); + }); }); it('accepts string commentId', async () => { diff --git a/src/hooks/useCommentDetail.ts b/src/hooks/useCommentDetail.ts index dc34739..5a32ea6 100644 --- a/src/hooks/useCommentDetail.ts +++ b/src/hooks/useCommentDetail.ts @@ -15,6 +15,8 @@ interface UseCommentDetailResult { replies: Comment[]; itemId: number | null; itemTitle: string | null; + /** True while the parent story's title and author are being fetched. */ + itemTitleLoading: boolean; /** * Author handle of the parent story (not the comment's author). * Resolved asynchronously alongside `itemTitle`; `null` until that @@ -46,6 +48,7 @@ export function useCommentDetail( const [replies, setReplies] = useState([]); const [itemId, setItemId] = useState(null); const [itemTitle, setItemTitle] = useState(null); + const [itemTitleLoading, setItemTitleLoading] = useState(false); const [itemAuthor, setItemAuthor] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -68,6 +71,7 @@ export function useCommentDetail( }); setItemId(item.story_id ?? null); setReplies(normalizeAlgoliaItemChildren(item.children ?? [])); + setItemTitleLoading(!!item.story_id); setLoading(false); // Fetch parent title + author in background (non-blocking). @@ -85,6 +89,8 @@ export function useCommentDetail( // Degrade gracefully — title link still works with itemId // alone; OP badge stays off (consumers guard with // `isKnownAuthor(itemAuthor)`). + } finally { + if (!signal.aborted) setItemTitleLoading(false); } } } catch (err) { @@ -112,5 +118,5 @@ export function useCommentDetail( }; }, [load]); - return { comment, replies, itemId, itemTitle, itemAuthor, loading, error, retry }; + return { comment, replies, itemId, itemTitle, itemTitleLoading, itemAuthor, loading, error, retry }; } diff --git a/src/hooks/useInfiniteStories.test.ts b/src/hooks/useInfiniteStories.test.ts index 4f3c59e..f0a8d4c 100644 --- a/src/hooks/useInfiniteStories.test.ts +++ b/src/hooks/useInfiniteStories.test.ts @@ -7,7 +7,7 @@ import { createStoryItem } from '../test/factories'; import { server } from '../mocks/server'; import { hnSdk } from '../api/hnSdk'; import { __resetFetchCachesForTests } from '../api/hn'; -import type { FirebaseItem } from '../types'; +import type { FeedType, FirebaseItem } from '../types'; function makeFirebaseItem(id: number): FirebaseItem { return { @@ -127,4 +127,27 @@ describe('useInfiniteStories', () => { expect(result.current.stories).toHaveLength(50); }); + + it('does not repeat stories after going Back to a feed whose session was saved', async () => { + // StoryList stays mounted across feed routes and calls reset() when `type` changes. + const { result, rerender } = renderHook( + ({ type }: { type: FeedType }) => useInfiniteStories(type), + { initialProps: { type: 'best' } }, + ); + await act(() => result.current.loadMore()); + // Opening a story saves the session. + act(() => result.current.saveSessionState(0)); + + rerender({ type: 'newest' }); + act(() => result.current.reset()); + rerender({ type: 'best' }); + act(() => result.current.reset()); + + await act(() => result.current.loadMore()); + await act(() => result.current.loadMore()); + + const ids = result.current.stories.map(s => s.id); + expect(new Set(ids).size).toBe(ids.length); + expect(ids).toHaveLength(50); + }); }); diff --git a/src/hooks/useInfiniteStories.ts b/src/hooks/useInfiniteStories.ts index b38cba5..59a9a7c 100644 --- a/src/hooks/useInfiniteStories.ts +++ b/src/hooks/useInfiniteStories.ts @@ -42,6 +42,10 @@ function getInitialState(type: FeedType): InitialState { } } + return getCachedState(type); +} + +function getCachedState(type: FeedType): InitialState { const cached = getCachedFeed(type); if (cached && cached.stories.length > 0) { return { @@ -303,7 +307,9 @@ export function useInfiniteStories(type: FeedType = 'top') { versionRef.current += 1; inFlightRef.current = false; - const initial = getInitialState(type); + // The cache, not the session: the session's stories paired with the cursor + // reset below would make the next page repeat them. + const initial = getCachedState(type); setStories(initial.stories); setIsFromCache(initial.isFromCache); // We're starting fresh, not restoring — so explicitly drop session-restore flags. diff --git a/src/hooks/useItemWithComments.test.tsx b/src/hooks/useItemWithComments.test.tsx index bf482b3..e227209 100644 --- a/src/hooks/useItemWithComments.test.tsx +++ b/src/hooks/useItemWithComments.test.tsx @@ -96,6 +96,37 @@ describe('useItemWithComments', () => { }); }); + describe('initialItem without text (restored swipe position)', () => { + const body = '

Ask HN body

'; + + it('takes the body from the cached copy without fetching', () => { + setCachedItem(12345, { ...testItem, text: body }, testComments, 3); + + const { result } = renderHook(() => + useItemWithComments(12345, { initialItem: testItem }) + ); + + expect(result.current.item).toEqual({ ...testItem, text: body }); + expect(hnSdk.readItem).not.toHaveBeenCalled(); + }); + + it('takes the body from the item fetched with the comments, and caches it', async () => { + vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ ...mockFirebaseStory, text: body, score: 999 }); + const askItem = { ...testItem, type: 'ask' as const }; + + const { result } = renderHook(() => + useItemWithComments(12345, { initialItem: askItem }) + ); + + 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 }); + }); + }); + describe('deferComments option', () => { it('skips comment fetch when deferComments is true', async () => { const { result } = renderHook(() => @@ -725,6 +756,40 @@ describe('useItemWithComments', () => { expect(result.current.comments!.length).toBeGreaterThan(0); }); + it('keeps the body of a restored story whose comments arrive through the retry', async () => { + const body = '

Ask HN body

'; + vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ ...mockFirebaseStory, text: body }); + let resolveComments: (() => void) | undefined; + server.use( + http.get(`${ALGOLIA_API}/search`, async () => { + await new Promise(resolve => { resolveComments = resolve; }); + return HttpResponse.json({ hits: [], nbHits: 0, page: 0, nbPages: 0, hitsPerPage: 200 }); + }) + ); + + // testItem has no `text`, like a story restored from a swipe position. + const { result } = renderHook( + () => useItemWithComments(12345, { initialItem: testItem }), + { wrapper: networkWrapper } + ); + + server.use( + http.get(`${ALGOLIA_API}/search`, () => HttpResponse.json({ + hits: [{ objectID: '1001', author: 'user1', comment_text: 'Test', created_at_i: 1000, parent_id: 12345, story_id: 12345 }], + nbHits: 1, page: 0, nbPages: 1, hitsPerPage: 200, + })) + ); + act(() => { window.dispatchEvent(new Event('offline')); }); + act(() => { window.dispatchEvent(new Event('online')); }); + resolveComments?.(); + + await waitFor(() => { + expect(result.current.commentsLoading).toBe(false); + }); + expect(result.current.item).toEqual({ ...testItem, text: body }); + expect(getCachedItem(12345)?.item).toEqual({ ...testItem, text: body }); + }); + it('does not retry when comments already loaded', async () => { // Pre-cache so nothing should fetch on reconnect. setCachedItem(12345, testItem, testComments, 3); diff --git a/src/hooks/useItemWithComments.ts b/src/hooks/useItemWithComments.ts index 3a4638c..5845e71 100644 --- a/src/hooks/useItemWithComments.ts +++ b/src/hooks/useItemWithComments.ts @@ -1,5 +1,5 @@ import { useState, useEffect, useRef, useEffectEvent, useCallback } from 'react'; -import { fetchItemOnly, fetchCommentsForItem, NotFoundError } from '../api/hn'; +import { fetchItemOnly, fetchCommentsForItem, fetchItemWithComments, NotFoundError } from '../api/hn'; import { getCachedItem, setCachedItem } from '../utils/itemCache'; import { registerPriorityFetch, unregisterPriorityFetch } from '../utils/fetchPriority'; import { useNetworkStatus } from './useNetworkStatus'; @@ -28,11 +28,19 @@ interface UseItemWithCommentsResult { refresh: () => Promise; } +// Swipe-position snapshots store stories without `text` (see swipePosition.ts), +// so an initialItem can lack a body that another copy of the item has. +function withText(item: Item | null | undefined, source: Item | null | undefined): Item | null { + if (!item) return null; + if (item.text !== undefined || source?.id !== item.id || source.text === undefined) return item; + return { ...item, text: source.text }; +} + export function useItemWithComments(itemId: number | string, { initialItem = null, skipOrderingCompletion = false, isPriority = true, deferComments = false }: UseItemWithCommentsOptions = {}): UseItemWithCommentsResult { const initialCache = getCachedItem(itemId); // Lazy initialization from cache or initialItem for instant render - const [item, setItem] = useState(() => initialItem ?? initialCache?.item ?? null); + const [item, setItem] = useState(() => withText(initialItem, initialCache?.item) ?? initialCache?.item ?? null); const [comments, setComments] = useState(() => initialCache?.comments ?? null); const [itemLoading, setItemLoading] = useState(!initialItem && !initialCache?.item); @@ -76,7 +84,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul const cached = getCachedItem(itemId); - const hasItem = initialItem ?? cached?.item; + const hasItem = withText(initialItem, cached?.item) ?? cached?.item; const stateHasDifferentItem = currentItem && String(currentItemId) !== String(itemId); @@ -97,7 +105,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul const validInitialItem = initialItem && String(initialItem.id) === String(itemId) ? initialItem : null; - setItem(validInitialItem); + setItem(withText(validInitialItem, cached?.item)); setItemLoading(!validInitialItem); setComments(null); setCommentsLoading(true); @@ -166,14 +174,16 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul } try { - const commentsData = await fetchCommentsForItem(itemId, controller.signal); + const { item: fetchedItem, comments: commentsData } = await fetchItemWithComments(itemId, controller.signal); if (!controller.signal.aborted) { + setItem(current => withText(current, fetchedItem)); setComments(commentsData); setCommentsLoading(false); setCommentsError(null); - if (itemData) { - setCachedItem(itemId, itemData, commentsData, 3); + const fullItem = withText(itemData, fetchedItem); + if (fullItem) { + setCachedItem(itemId, fullItem, commentsData, 3); } // Unregister priority so section prefetch and other lower-priority @@ -205,9 +215,9 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul if (needsOrderingCompletion && hasItem) { // Show partial-ordering data immediately, complete ordering in background. - await loadComments(initialItem ?? cached.item, true); + await loadComments(hasItem, true); } else if (needsFullFetch) { - const itemData = hasItem ? (initialItem ?? cached?.item) : await loadItem(); + const itemData = hasItem ?? await loadItem(); // Comment items use a different fetch path (useCommentDetail via Algolia /items). if (itemData && itemData.type !== 'comment' && !controller.signal.aborted) { @@ -264,13 +274,15 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul controllerRef.current = controller; setCommentsLoading(true); - void fetchCommentsForItem(itemId, controller.signal) - .then(commentsData => { + void fetchItemWithComments(itemId, controller.signal) + .then(({ item: fetchedItem, comments: commentsData }) => { if (controller.signal.aborted) return; + setItem(current => withText(current, fetchedItem)); setComments(commentsData); setCommentsLoading(false); setCommentsError(null); - if (item) setCachedItem(itemId, item, commentsData, 3); + const fullItem = withText(item, fetchedItem); + if (fullItem) setCachedItem(itemId, fullItem, commentsData, 3); }) .catch(err => { if (controller.signal.aborted || (err instanceof Error && err.name === 'AbortError')) return; diff --git a/src/utils/sanitize.test.ts b/src/utils/sanitize.test.ts index 187baf8..39e9113 100644 --- a/src/utils/sanitize.test.ts +++ b/src/utils/sanitize.test.ts @@ -335,10 +335,16 @@ describe('sanitizeHtml', () => { }); describe('attribute filtering', () => { - it('preserves allowed attributes', () => { - const result = sanitizeHtml('text'); - expect(result).toContain('href='); - expect(result).toContain('class="link"'); + it('preserves href', () => { + const result = sanitizeHtml('text'); + expect(result).toContain('href="https://example.com"'); + }); + + it('removes class and id, which could restyle the page or shadow its ids', () => { + const result = sanitizeHtml('

text

'); + expect(result).not.toContain('class='); + expect(result).not.toContain('id='); + expect(result).toContain('href="https://example.com"'); }); it('removes disallowed attributes', () => { diff --git a/src/utils/sanitize.ts b/src/utils/sanitize.ts index 13acc88..d959293 100644 --- a/src/utils/sanitize.ts +++ b/src/utils/sanitize.ts @@ -22,7 +22,9 @@ const PURIFY_CONFIG: Config = { 'p', 'br', 'a', 'b', 'i', 'u', 'strong', 'em', 'code', 'pre', 'blockquote', 'ul', 'ol', 'li', 'span', 'div', ], - ALLOWED_ATTR: ['href', 'class', 'id'], + // No class or id: HN never emits them, and they'd let the text pick up the + // app's styles (utility classes) or shadow ids the app looks up. + ALLOWED_ATTR: ['href'], ALLOW_DATA_ATTR: false, ALLOW_ARIA_ATTR: false, }; diff --git a/src/utils/swipePosition.ts b/src/utils/swipePosition.ts index 7f09477..b062c16 100644 --- a/src/utils/swipePosition.ts +++ b/src/utils/swipePosition.ts @@ -30,7 +30,7 @@ export function sameViewer(a: LocationState, b: LocationState): boolean { ); } -/** Lean projection: omits `text` (the heavy Ask/Show HTML body); FullScreenItem re-fetches. */ +/** Lean projection: omits `text` (the heavy Ask/Show HTML body); useItemWithComments fills it back in. */ function projectStory(s: StoryItem): StoryItem { return { id: s.id,