From 287bbe08b2231735e9f4cedcd5172f9f5ae2e454 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:50:49 +0100 Subject: [PATCH] fix: comment retries, a stuck prefetch flag, a double feed fetch and compact errors, plus three behavior changes Four bug fixes and three behavior changes, each with its tests. The comments section's automatic retry called refresh(), which refetches the item and then its comments, and set the page-level error when the comments failed again, so ItemDetail and FullScreenItem replaced a story that had loaded with "Failed to load item". The section now retries the comments only, with a new retryComments(), and keeps the comments error set until each attempt settles. refresh() reports a comments failure after the item loads as a comments error, so the page's Try Again shows the story. A reconnect retry aborted the request that had registered a priority fetch and fetched again without one, so the count stayed up and background prefetching stayed off until the page was reloaded. The reconnect retry now releases the registration when it settles, whether it succeeds, fails or is aborted, and a comment item releases it once the item loads. On a phone the feed routes and /item/:id rendered different components, so the swipe viewer remounted when it moved the URL to its first story and fetched the feed's first page again. They now render one component, MobileStoryRoute, keyed by the times a feed route is entered from another route. A compact StateView showed its default title, "Something went wrong", in place of a passed-in description, so the comments error's "Failed to load comments" never showed. A passed-in description now takes the default title's place. The story lists' load-more error no longer passes its raw error, so it still reads "Something went wrong". Desktop Back from another feed now restores the feed's saved list instead of starting it over, as reset() had done since 03dbe95. The list is keyed by feed, so it mounts for each one and restores its session, cursor included. A header tab still starts its feed over. The desktop comment page keeps a comment it got from Firebase when Algolia fails. Its replies show their skeleton during the retries, then "Failed to load replies" with a Retry button, instead of the page error, which is left for a comment with nothing to show. The item cache stays within 3 million of the 5,242,880 characters of localStorage an origin gets, and doesn't keep a thread over half that. The feed lists, viewed times and theme choice write through setLocalStorageItem(), which drops the older half of the cached items and tries once more when storage is full. --- e2e/comment-detail.spec.ts | 29 ++- e2e/story-browsing.spec.ts | 6 +- src/App.test.tsx | 83 +++++++- src/App.tsx | 81 ++++---- src/App.viewer.test.tsx | 51 +++++ src/components/Comment.tsx | 2 +- src/components/CommentArticle.tsx | 5 + src/components/CommentDetail.test.tsx | 47 ++++- src/components/CommentDetail.tsx | 12 +- src/components/CommentsSection.tsx | 16 +- src/components/FullScreenItem.tsx | 4 +- src/components/InfiniteStoryListPage.test.tsx | 7 +- src/components/InfiniteStoryListPage.tsx | 1 - src/components/StateView.test.tsx | 18 ++ src/components/StateView.tsx | 6 +- src/components/SwipeStoryViewer.tsx | 5 +- src/components/SwipeUserSubmissionsViewer.tsx | 2 +- src/context/ThemeContext.tsx | 8 +- src/hooks/useInfiniteStories.test.ts | 4 +- src/hooks/useItemWithComments.test.tsx | 188 ++++++++++++++++++ src/hooks/useItemWithComments.ts | 89 ++++++--- src/pages/ItemDetail.test.tsx | 94 ++++++++- src/pages/ItemDetail.tsx | 4 +- src/pages/StoryList.test.tsx | 64 ++++++ src/pages/StoryList.tsx | 13 +- src/test/storageQuota.ts | 41 ++++ src/utils/feedCache.test.ts | 20 +- src/utils/feedCache.ts | 3 +- src/utils/itemCache.test.ts | 119 ++++++++++- src/utils/itemCache.ts | 135 ++++++++----- src/utils/viewedItems.test.ts | 19 ++ src/utils/viewedItems.ts | 9 +- 32 files changed, 998 insertions(+), 187 deletions(-) create mode 100644 src/App.viewer.test.tsx create mode 100644 src/pages/StoryList.test.tsx create mode 100644 src/test/storageQuota.ts diff --git a/e2e/comment-detail.spec.ts b/e2e/comment-detail.spec.ts index 6902dea..52227dc 100644 --- a/e2e/comment-detail.spec.ts +++ b/e2e/comment-detail.spec.ts @@ -97,7 +97,7 @@ test.describe('Comment Detail - Error + Retry', () => { // Auto-retry exhausts 3 backoff attempts (2s+4s+8s) before surfacing error UI. test.setTimeout(60000); - test('shows error state with retry button when Algolia fails', async ({ page }) => { + test('keeps the comment and offers to retry its replies when Algolia fails', async ({ page }) => { await setupApiMocks(page); await page.route(`${ALGOLIA_API}/items/1001`, async (route) => { @@ -106,12 +106,18 @@ test.describe('Comment Detail - Error + Retry', () => { await page.goto('/#/item/1001'); + // The comment itself comes from Firebase. + const firebaseText = page.getByText(/really well-written piece/); + await expect(firebaseText).toBeVisible(); + // 30s timeout covers the 2+4+8 backoff plus slack. - await expect(page.getByText('Failed to load comment')).toBeVisible({ timeout: 30000 }); - await expect(page.getByRole('button', { name: /retry/i })).toBeVisible(); + await expect(page.getByRole('button', { name: /retry/i })).toBeVisible({ timeout: 30000 }); + await expect(page.getByText('Failed to load replies')).toBeVisible(); + await expect(firebaseText).toBeVisible(); + await expect(page.getByText('Failed to load comment')).not.toBeVisible(); }); - test('recovers after retry when Algolia temporarily fails', async ({ page }) => { + test('loads the replies on retry once Algolia recovers', async ({ page }) => { await setupApiMocks(page); let shouldFail = true; @@ -127,7 +133,14 @@ test.describe('Comment Detail - Error + Retry', () => { created_at_i: Math.floor(Date.now() / 1000) - 1800, parent_id: 12345, story_id: 12345, - children: [], + children: [{ + id: 2001, + author: 'tptacek', + text: 'A reply that loaded on retry.', + created_at_i: Math.floor(Date.now() / 1000) - 900, + parent_id: 1001, + children: [], + }], type: 'comment', }, }); @@ -136,15 +149,15 @@ test.describe('Comment Detail - Error + Retry', () => { await page.goto('/#/item/1001'); - await expect(page.getByText('Failed to load comment')).toBeVisible({ timeout: 30000 }); const retryButton = page.getByRole('button', { name: /retry/i }); - await expect(retryButton).toBeVisible(); + await expect(retryButton).toBeVisible({ timeout: 30000 }); // Flip the failure switch BEFORE the retry click so the next request succeeds. shouldFail = false; await retryButton.click(); - await expect(page.getByText('patio11').first()).toBeVisible({ timeout: 10000 }); + await expect(page.getByText('A reply that loaded on retry.')).toBeVisible({ timeout: 10000 }); await expect(page.getByText(/wasm-bindgen/i).first()).toBeVisible(); + await expect(retryButton).not.toBeVisible(); }); }); diff --git a/e2e/story-browsing.spec.ts b/e2e/story-browsing.spec.ts index c5984ee..1c2c866 100644 --- a/e2e/story-browsing.spec.ts +++ b/e2e/story-browsing.spec.ts @@ -181,14 +181,12 @@ test.describe('Item Browsing - Desktop Back between feeds', () => { 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. + // Best's list mounts again and restores the session the story saved. 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); + expect(await page.evaluate(() => sessionStorage.getItem('feed:session:best'))).not.toBeNull(); }); }); diff --git a/src/App.test.tsx b/src/App.test.tsx index 960afd9..d2390f1 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { screen, fireEvent } from '@testing-library/react'; import { Routes, Route, Link, useNavigate } from 'react-router'; import { render } from './test/test-utils'; -import { MobileItemDetailWrapper, MobileStoryListWrapper } from './App'; +import { MobileStoryRoute } from './App'; import { fetchItemOnly } from './api/hn'; import { saveSwipePosition } from './utils/swipePosition'; import { createStoryItem } from './test/factories'; @@ -16,11 +16,13 @@ vi.mock('./hooks/useCanSwipe', () => ({ useCanSwipe: () => true })); // mounts (and with what props) without their data hooks / async state. vi.mock('./components/SwipeStoryViewer', async () => { const { useState } = await import('react'); + let mounts = 0; return { SwipeStoryViewer: function SwipeStoryViewer({ type, initialItemId }: { type: string; initialItemId?: string }) { // Frozen at mount: a reused instance keeps the feed and item it was mounted for. const [mountedType] = useState(type); const [mountedItem] = useState(initialItemId ?? ''); + const [mount] = useState(() => ++mounts); return (
{ data-mounted-type={mountedType} data-item={initialItemId ?? ''} data-mounted-item={mountedItem} + data-mount={mount} /> ); }, @@ -55,7 +58,7 @@ vi.mock('./api/hn', async (importOriginal) => ({ function renderWrapper(id: number | string, state?: LocationState) { return render( - } /> + } /> , { initialEntries: [{ pathname: `/item/${id}`, state }] }, ); @@ -66,7 +69,7 @@ function seedSnapshot(viewer: LocationState, storyId: number) { saveSwipePosition({ viewer, storyId, index: 0, scrollY: 0, stories }); } -describe('MobileItemDetailWrapper — viewer recovery (stateless reload)', () => { +describe('MobileStoryRoute — viewer recovery (stateless reload)', () => { beforeEach(() => { sessionStorage.clear(); }); @@ -150,7 +153,7 @@ describe('MobileItemDetailWrapper — viewer recovery (stateless reload)', () => }); }); -describe('MobileItemDetailWrapper — direct link', () => { +describe('MobileStoryRoute — direct link', () => { beforeEach(() => { sessionStorage.clear(); }); @@ -169,7 +172,7 @@ describe('MobileItemDetailWrapper — direct link', () => { vi.mocked(fetchItemOnly).mockResolvedValueOnce(createStoryItem({ id: 88888 })); render( - } /> + } /> , { initialEntries: ['/item/88888'] }, ); @@ -185,7 +188,7 @@ describe('MobileItemDetailWrapper — direct link', () => { }); }); -describe('MobileItemDetailWrapper — ids that are not numbers', () => { +describe('MobileStoryRoute — 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' }); @@ -196,13 +199,42 @@ describe('MobileItemDetailWrapper — ids that are not numbers', () => { }); }); -describe('MobileStoryListWrapper', () => { +describe('MobileStoryRoute — feed routes', () => { + beforeEach(() => { + sessionStorage.clear(); + }); + + // What the feed's viewer does once its first story shows. + function MoveToFirstStory({ feed }: { feed: LocationState['from'] }) { + const navigate = useNavigate(); + return ( + + ); + } + + function renderFeedRoutes() { + return render( + <> + + } /> + } /> + } /> + + + best + , + { initialEntries: ['/best'] }, + ); + } + it('mounts a new viewer when you switch feeds before the URL moves to a story', () => { render( <> - } /> - } /> + } /> + } /> best , @@ -215,4 +247,37 @@ describe('MobileStoryListWrapper', () => { expect(viewer).toHaveAttribute('data-type', 'best'); expect(viewer).toHaveAttribute('data-mounted-type', 'best'); }); + + it('keeps the viewer when it moves the URL to its first story', () => { + renderFeedRoutes(); + const mount = screen.getByTestId('feed-viewer').getAttribute('data-mount'); + + fireEvent.click(screen.getByRole('button', { name: 'first story' })); + + const viewer = screen.getByTestId('feed-viewer'); + expect(viewer).toHaveAttribute('data-item', '1000'); + expect(viewer).toHaveAttribute('data-mounted-item', ''); + expect(viewer).toHaveAttribute('data-mount', mount); + }); + + it('starts the feed over when its tab is opened from one of its stories', () => { + renderFeedRoutes(); + fireEvent.click(screen.getByRole('button', { name: 'first story' })); + const mount = screen.getByTestId('feed-viewer').getAttribute('data-mount'); + + fireEvent.click(screen.getByRole('link', { name: 'best' })); + + const viewer = screen.getByTestId('feed-viewer'); + expect(viewer).toHaveAttribute('data-item', ''); + expect(viewer).not.toHaveAttribute('data-mount', mount); + }); + + it('keeps the viewer when its tab is opened again before the URL moves', () => { + renderFeedRoutes(); + const mount = screen.getByTestId('feed-viewer').getAttribute('data-mount'); + + fireEvent.click(screen.getByRole('link', { name: 'best' })); + + expect(screen.getByTestId('feed-viewer')).toHaveAttribute('data-mount', mount); + }); }); diff --git a/src/App.tsx b/src/App.tsx index 78ada1a..8a698db 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -21,21 +21,6 @@ import { fetchItemOnly } from './api/hn'; import { readSwipePosition } from './utils/swipePosition'; import type { FeedType, LocationState, SwipePosition } from './types'; -// Exported for focused unit testing. -export function MobileStoryListWrapper({ type }: { type: FeedType }) { - const canSwipe = useCanSwipe(); - - if (canSwipe) { - // 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 ; -} - // Falls through to the desktop list when the URL has no domain (empty `/from/`) // so the "No domain specified" fallback in DomainStories handles it consistently // on both platforms. @@ -74,10 +59,12 @@ function MobileUserSubmissionsWrapper() { } // Maps a viewer context to its swipe viewer (priority fromUser → fromDomain → from; -// written mutually exclusively). Shared by the location.state path (Branches 2–4) -// and snapshot recovery (4b); the `key` mirrors viewer identity so switching paths -// reuses the instance. `id` is the story id here (/item/:id), so it's initialItemId. -function renderSwipeViewer(viewer: LocationState, id: string | undefined): ReactNode { +// written mutually exclusively). Shared by the feed routes, the location.state path +// (Branches 2–4) and snapshot recovery (4b); the `key` mirrors viewer identity so +// switching paths reuses the instance. `id` is the story id here (/item/:id), so +// it's initialItemId. A feed viewer's key also carries `feedEntries` (see +// MobileStoryRoute). +function renderSwipeViewer(viewer: LocationState, id: string | undefined, feedEntries: number): ReactNode { if (viewer.fromUser) { return ; } @@ -85,30 +72,53 @@ function renderSwipeViewer(viewer: LocationState, id: string | undefined): React return ; } if (viewer.from) { - return ; + return ; } return null; } -// Routes /item/:id to the correct mobile viewer based on `location.state` +// The element for the feed routes (`feed` set) and /item/:id. On a phone the +// feed's viewer moves the URL to /item/:id as soon as its first story shows, +// and React keeps that viewer only if both routes render the same component: +// as two components, the viewer mounted again there and fetched the first +// page a second time. On /item/:id it picks the viewer from `location.state` // (or the item type for direct URLs without state). -// Exported for focused unit testing of the viewer-recovery branch. -export function MobileItemDetailWrapper() { +// Exported for focused unit testing. +export function MobileStoryRoute({ feed }: { feed?: FeedType }) { const { id } = useParams(); const canSwipe = useCanSwipe(); const location = useLocation(); // 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) })); + const [recovered] = useState(() => (feed ? null : readSwipePosition({ storyId: Number(id) }))); + + // Counts the feed routes entered from another route. It's in the feed + // viewer's key, so opening a feed (a tab, the logo, Back to a feed URL) + // starts it over, while the viewer's own move to /item/:id keeps the key. + // A tab switch made before that move (first load still running, or a + // failed one) mounts the new feed's viewer too, so the previous feed's + // in-flight page can't land in it. + const [feedEntries, setFeedEntries] = useState(0); + const [lastFeed, setLastFeed] = useState(feed); + if (feed !== lastFeed) { + setLastFeed(feed); + if (feed) setFeedEntries(feedEntries + 1); + } // 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. const isNumericId = id !== undefined && /^\d+$/.test(id); const viewer = canSwipe && isNumericId - ? pickSwipeViewer(location.state as LocationState | null, recovered, id) + ? pickSwipeViewer(location.state as LocationState | null, recovered, id, feedEntries) : null; const isResolvedStory = useResolveDirectLink(id, canSwipe && isNumericId && !viewer); + if (feed) { + // key={feed}: a list mounts for each feed, so Back to one restores its + // saved session, as Back from a story does. + return canSwipe ? renderSwipeViewer({ from: feed }, undefined, feedEntries) : ; + } + if (!isNumericId) { return ; } @@ -120,7 +130,7 @@ export function MobileItemDetailWrapper() { // 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); + if (isResolvedStory) return renderSwipeViewer({ from: 'top' }, id, feedEntries); return ; } @@ -131,6 +141,7 @@ function pickSwipeViewer( state: LocationState | null, recovered: SwipePosition | null, id: string, + feedEntries: number, ): ReactNode { // Branch 1: Known comment → SwipeCommentViewer immediately. // Comments take priority over user/domain/from to match the header pill @@ -141,7 +152,7 @@ function pickSwipeViewer( // Branches 2–4: viewer context from location.state (zero-latency path). if (state) { - const viewer = renderSwipeViewer(state, id); + const viewer = renderSwipeViewer(state, id, feedEntries); if (viewer) return viewer; } @@ -151,7 +162,7 @@ function pickSwipeViewer( // 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 renderSwipeViewer(recovered.viewer, id, feedEntries); } return null; @@ -181,7 +192,7 @@ function useResolveDirectLink(id: string | undefined, enabled: boolean): boolean .then(item => { if (controller.signal.aborted) return; if (item.type === 'comment') { - // Navigate with state so MobileItemDetailWrapper Branch 1 picks it up + // Navigate with state so MobileStoryRoute Branch 1 picks it up void navigate(`/item/${id}`, { replace: true, state: { isComment: true } }); } else { setStoryId(id); @@ -289,12 +300,12 @@ function App() { - } /> - } /> - } /> - } /> - } /> - } /> + } /> + } /> + } /> + } /> + } /> + } /> } /> } /> } /> diff --git a/src/App.viewer.test.tsx b/src/App.viewer.test.tsx new file mode 100644 index 0000000..1e3b211 --- /dev/null +++ b/src/App.viewer.test.tsx @@ -0,0 +1,51 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { Routes, Route, useLocation } from 'react-router'; +import { render, screen, waitFor, act } from './test/test-utils'; +import { MobileStoryRoute } from './App'; +import { ScrollContainerProvider } from './context/ScrollContainerContext'; +import { hnSdk } from './api/hnSdk'; +import { __resetFetchCachesForTests } from './api/hn'; +import type { FirebaseItem } from './types'; + +// App.test.tsx stubs the swipe viewers; this file runs the real one. +vi.mock('./hooks/useCanSwipe', () => ({ useCanSwipe: () => true })); + +const ids = Array.from({ length: 60 }, (_, i) => 1000 + i); +const story = (id: number): FirebaseItem => ({ + id, type: 'story', title: `Story ${id}`, by: 'u', score: 1, + time: Math.floor(Date.now() / 1000) - 60, descendants: 0, url: `https://example.com/${id}`, +}); + +function Pathname() { + return
{useLocation().pathname}
; +} + +describe('opening a feed on a phone', () => { + beforeEach(() => { + __resetFetchCachesForTests(); + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(ids); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => story(Number(id))); + }); + + it('fetches the first page once', async () => { + render( + + + } /> + } /> + + + , + { initialEntries: ['/best'] }, + ); + + await waitFor(() => expect(screen.getByTestId('pathname')).toHaveTextContent('/item/1000')); + await act(async () => { await new Promise(r => setTimeout(r, 300)); }); + + // Index 20 is past the rendered panels and the 6-story prefetch, so only + // a page request reads it. + const reads = vi.mocked(hnSdk.readItem).mock.calls.filter(([id]) => Number(id) === 1020); + expect(reads).toHaveLength(1); + expect(hnSdk.readRankedIds).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/components/Comment.tsx b/src/components/Comment.tsx index 4522c28..ef50b01 100644 --- a/src/components/Comment.tsx +++ b/src/components/Comment.tsx @@ -80,7 +80,7 @@ export function Comment({ comment, storyAuthor = '', stageIdx }: CommentProps) { )} · {/* Time IS the permalink (HN convention). `state.isComment: - true` lets MobileItemDetailWrapper short-circuit straight + true` lets MobileStoryRoute short-circuit straight to SwipeCommentViewer without a resolver round-trip. */} void; articleClassName?: string; /** Story author for OP detection. */ storyAuthor?: string; @@ -36,6 +38,7 @@ export function CommentArticle({ itemTitle, itemTitleLoading = false, loading, + onRetryReplies, articleClassName = 'mb-4', storyAuthor = '', }: CommentArticleProps) { @@ -129,6 +132,8 @@ export function CommentArticle({ // for the ~100-500ms before the algolia fetch resolves. On // cold load PageStage's overlay covers this branch. + ) : onRetryReplies ? ( + ) : replies.length > 0 ? ( ) : ( diff --git a/src/components/CommentDetail.test.tsx b/src/components/CommentDetail.test.tsx index ad1ff6d..287e07c 100644 --- a/src/components/CommentDetail.test.tsx +++ b/src/components/CommentDetail.test.tsx @@ -1,8 +1,11 @@ -import { describe, it, expect } from 'vitest'; -import { screen, waitFor } from '@testing-library/react'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { screen, waitFor, act } from '@testing-library/react'; +import { http, HttpResponse } from 'msw'; import { render } from '../test/test-utils'; import { Routes, Route } from 'react-router'; import { CommentDetail } from './CommentDetail'; +import { server } from '../mocks/server'; +import { ALGOLIA_API } from '../config/api'; function renderCommentDetail(commentId: number | string, initialData?: { author: string; text: string; createdAt: number }) { return render( @@ -50,4 +53,44 @@ describe('CommentDetail', () => { expect(document.title).toContain('Comment by patio11'); }); }); + + describe('when the comment keeps failing to load', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + function failEveryRequest() { + vi.useFakeTimers({ shouldAdvanceTime: true }); + server.use(http.get(`${ALGOLIA_API}/items/:id`, () => new HttpResponse(null, { status: 503 }))); + } + + // The first load, then three retries 2s, 4s and 8s apart: about 14s. + async function waitOutRetries() { + for (let step = 0; step < 300 && !screen.queryByRole('button', { name: 'Retry' }); step++) { + await act(async () => { await vi.advanceTimersByTimeAsync(100); }); + } + } + + it('shows the page error once the retries run out with nothing to show', async () => { + failEveryRequest(); + renderCommentDetail(1001); + + await waitOutRetries(); + + expect(screen.getByText('Failed to load comment')).toBeInTheDocument(); + }); + + it('keeps a comment from initialData and offers to retry its replies', async () => { + failEveryRequest(); + renderCommentDetail(1001, { author: 'patio11', text: 'Seeded from Firebase.', createdAt: Date.now() }); + + await waitOutRetries(); + + expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument(); + expect(screen.getByText('Failed to load replies')).toBeInTheDocument(); + expect(screen.getByText('Seeded from Firebase.')).toBeInTheDocument(); + expect(screen.queryByText('Failed to load comment')).not.toBeInTheDocument(); + expect(screen.queryByText('No replies yet.')).not.toBeInTheDocument(); + }); + }); }); diff --git a/src/components/CommentDetail.tsx b/src/components/CommentDetail.tsx index e4899b6..32ee6e3 100644 --- a/src/components/CommentDetail.tsx +++ b/src/components/CommentDetail.tsx @@ -63,21 +63,24 @@ export function CommentDetail({ commentId, initialData }: CommentDetailProps) { useDocumentTitle(comment?.author ? `Comment by ${comment.author}` : undefined); - if (error && !isRetrying) { + const retryNow = () => void retry().catch(() => { /* error state set internally */ }); + + // A comment seeded from initialData stays on screen; only its replies fail. + if (error && !comment && !isRetrying) { return (
void retry().catch(() => { /* error state set internally */ }) }} + action={{ label: 'Retry', onClick: retryNow }} />
); } // Retry-in-progress skeleton (avoids error UI flash between attempts). - if (error && isRetrying) { + if (error && !comment) { return (
@@ -100,7 +103,8 @@ export function CommentDetail({ commentId, initialData }: CommentDetailProps) { itemId={itemId} itemTitle={itemTitle} itemTitleLoading={itemTitleLoading} - loading={loading} + loading={loading || (!!error && isRetrying)} + onRetryReplies={error && !isRetrying ? retryNow : undefined} articleClassName="mb-6" storyAuthor={itemAuthor ?? ''} /> diff --git a/src/components/CommentsSection.tsx b/src/components/CommentsSection.tsx index 1b983e7..9eaba42 100644 --- a/src/components/CommentsSection.tsx +++ b/src/components/CommentsSection.tsx @@ -1,3 +1,4 @@ +import { useState } from 'react'; import { CommentTree, CommentSkeletonTree } from '../components'; import { StateView } from './StateView'; import { useNetworkStatus } from '../hooks/useNetworkStatus'; @@ -7,6 +8,7 @@ import type { Comment } from '../types'; interface CommentsSectionProps { comments: Comment[] | null; commentsError: string | null; + /** Refetch the comments only. `commentsError` stays set until it settles. */ onRetry: () => void | Promise; /** Story author for OP detection. */ storyAuthor?: string; @@ -20,11 +22,19 @@ export function CommentsSection({ comments, commentsError, onRetry, storyAuthor retryFn: onRetry, isOnline, }); + const [isManualRetrying, setIsManualRetrying] = useState(false); - if (commentsError && !comments?.length && !isRetrying) { - return void onRetry()?.catch(() => { /* error state set internally */ }) }} />; + const retryNow = () => { + setIsManualRetrying(true); + void Promise.resolve(onRetry()) + .catch(() => { /* error state set internally */ }) + .finally(() => setIsManualRetrying(false)); + }; + + if (commentsError && !comments?.length && !isRetrying && !isManualRetrying) { + return ; } - if (commentsError && !comments?.length && isRetrying) { + if (commentsError && !comments?.length) { return ; } // startIdx=1 reserves slot 0 for the `.story-stage-leader` header diff --git a/src/components/FullScreenItem.tsx b/src/components/FullScreenItem.tsx index c0848e6..74c513c 100644 --- a/src/components/FullScreenItem.tsx +++ b/src/components/FullScreenItem.tsx @@ -52,7 +52,7 @@ interface FullScreenItemProps { } export function FullScreenItem({ itemId, initialItem, isPriority = true, deferComments = false }: FullScreenItemProps) { - const { item, comments, itemLoading, commentsLoading, error, isNotFound, commentsError, refresh } = useItemWithComments(itemId, { + const { item, comments, itemLoading, commentsLoading, error, isNotFound, commentsError, refresh, retryComments } = useItemWithComments(itemId, { initialItem: initialItem ?? null, skipOrderingCompletion: true, isPriority, @@ -112,7 +112,7 @@ export function FullScreenItem({ itemId, initialItem, isPriority = true, deferCo diff --git a/src/components/InfiniteStoryListPage.test.tsx b/src/components/InfiniteStoryListPage.test.tsx index dc4dd3c..2f323c2 100644 --- a/src/components/InfiniteStoryListPage.test.tsx +++ b/src/components/InfiniteStoryListPage.test.tsx @@ -183,10 +183,8 @@ describe('InfiniteStoryListPage', () => { // Pagination failure — the list stays visible, the error sits in // the footer slot instead of replacing the layout. Lighter // affordance ("Retry", not "Try Again") to keep the fix-it - // surface secondary to the cards. StateView's compact branch - // hides the verbose description when a title resolves (which - // it always does — DEFAULTS.error.title is "Something went - // wrong"), so we assert the visible markers, not the raw error. + // surface secondary to the cards. It shows StateView's default + // title, "Something went wrong", rather than the raw error. const stories = [createStoryItem({ id: 1, title: 'Loaded story' })]; renderPage({ @@ -195,6 +193,7 @@ describe('InfiniteStoryListPage', () => { expect(screen.getByRole('link', { name: 'Loaded story' })).toBeInTheDocument(); expect(screen.getByText(/something went wrong/i)).toBeInTheDocument(); + expect(screen.queryByText('Page 2 failed')).not.toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument(); }); diff --git a/src/components/InfiniteStoryListPage.tsx b/src/components/InfiniteStoryListPage.tsx index c6ff583..b6c45ee 100644 --- a/src/components/InfiniteStoryListPage.tsx +++ b/src/components/InfiniteStoryListPage.tsx @@ -152,7 +152,6 @@ export function InfiniteStoryListPage({ diff --git a/src/components/StateView.test.tsx b/src/components/StateView.test.tsx index e6ac55f..9b10e94 100644 --- a/src/components/StateView.test.tsx +++ b/src/components/StateView.test.tsx @@ -110,6 +110,24 @@ describe('StateView', () => { // And the title text is still surfaced as an inline label. expect(screen.getByText('Comment unavailable')).toBeInTheDocument(); }); + + it('shows a passed-in description instead of the default title', () => { + render(); + expect(screen.getByText('Failed to load comments')).toBeInTheDocument(); + expect(screen.queryByText('Something went wrong')).not.toBeInTheDocument(); + }); + + it('shows a passed-in title over a passed-in description', () => { + render(); + expect(screen.getByText('Boom')).toBeInTheDocument(); + expect(screen.queryByText('Details')).not.toBeInTheDocument(); + }); + + it('shows the default title when nothing is passed', () => { + render(); + expect(screen.getByText('Something went wrong')).toBeInTheDocument(); + expect(screen.queryByText(/couldn't load this content/)).not.toBeInTheDocument(); + }); }); describe('action element', () => { diff --git a/src/components/StateView.tsx b/src/components/StateView.tsx index 4201c11..e0fa58f 100644 --- a/src/components/StateView.tsx +++ b/src/components/StateView.tsx @@ -219,11 +219,13 @@ export function StateView({ variant, title, description, action, compact, classN const Scene = SCENES[variant]; if (compact) { + // One label fits, so a passed-in description takes the default title's place. + const compactTitle = title ?? (description ? undefined : defaults.title); return (
- {resolvedTitle && {resolvedTitle}} - {!resolvedTitle && resolvedDesc && {resolvedDesc}} + {compactTitle && {compactTitle}} + {!compactTitle && resolvedDesc && {resolvedDesc}} {action && }
); diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx index eab1de5..1c1a2d4 100644 --- a/src/components/SwipeStoryViewer.tsx +++ b/src/components/SwipeStoryViewer.tsx @@ -361,8 +361,9 @@ export function SwipeStoryViewerCore({ useLayoutEffect(() => () => persistSnapshot(), [persistSnapshot]); // Opening a feed from its tab (no story in the URL) starts it over. Drop the - // feed's old position now: the viewer that mounts once the URL moves to the - // first story would otherwise restore it if it was saved on that story. + // feed's old position now: a domain or user list mounts its viewer again + // once the URL moves to the first story, which would otherwise restore it if + // it was saved on that story. const opensFresh = initialItemId == null; useLayoutEffect(() => { if (opensFresh) clearSwipePosition(backState); diff --git a/src/components/SwipeUserSubmissionsViewer.tsx b/src/components/SwipeUserSubmissionsViewer.tsx index 9b0da69..67a3e64 100644 --- a/src/components/SwipeUserSubmissionsViewer.tsx +++ b/src/components/SwipeUserSubmissionsViewer.tsx @@ -9,7 +9,7 @@ interface SwipeUserSubmissionsViewerProps { /** HN username, case-preserved. Firebase and Algolia treat this as case-sensitive. */ username: string; /** - * Numeric story ID to anchor on (set by `MobileItemDetailWrapper` when the + * Numeric story ID to anchor on (set by `MobileStoryRoute` when the * route is `/item/:id` with `state.fromUser`). Must NOT be set for the bare * `/submitted/:id` route — `id` there is the username, and a non-numeric * `initialItemId` would `Number()` to `NaN`, triggering a wasteful injected diff --git a/src/context/ThemeContext.tsx b/src/context/ThemeContext.tsx index 184bdb7..6ea4e59 100644 --- a/src/context/ThemeContext.tsx +++ b/src/context/ThemeContext.tsx @@ -2,6 +2,7 @@ import { useEffect, useState, type ReactNode } from 'react'; import { ThemeContext } from './themeContextDef'; import { THEME_COLORS, nextMode } from './themeConfig'; import type { Theme, ThemeMode } from '../types'; +import { setLocalStorageItem } from '../utils/itemCache'; // Persisted user preference ('light' | 'dark' | 'system'). An absent or // invalid value falls back to 'system' (follow the device). @@ -70,11 +71,10 @@ export function ThemeProvider({ children }: { children: ReactNode }) { }, [mode]); // Persist only on an explicit choice. Mounting never writes, so a fresh user - // stays "follow the device" until they opt out. + // stays "follow the device" until they opt out. A write that still fails + // leaves the choice applied for this visit only. const setMode = (next: ThemeMode) => { - try { - localStorage.setItem(MODE_KEY, next); - } catch { /* not persisted — still applies for this visit */ } + setLocalStorageItem(MODE_KEY, next); setModeState(next); }; diff --git a/src/hooks/useInfiniteStories.test.ts b/src/hooks/useInfiniteStories.test.ts index 6d33ff0..db4cca8 100644 --- a/src/hooks/useInfiniteStories.test.ts +++ b/src/hooks/useInfiniteStories.test.ts @@ -128,8 +128,8 @@ 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. + it('does not repeat stories after reset() on a feed whose session was saved', async () => { + // reset() starts the feed over from its cache, with the cursor at zero. const { result, rerender } = renderHook( ({ type }: { type: FeedType }) => useInfiniteStories(type), { initialProps: { type: 'best' } }, diff --git a/src/hooks/useItemWithComments.test.tsx b/src/hooks/useItemWithComments.test.tsx index d5b33d7..e1be881 100644 --- a/src/hooks/useItemWithComments.test.tsx +++ b/src/hooks/useItemWithComments.test.tsx @@ -925,6 +925,94 @@ describe('useItemWithComments', () => { }); expect(result.current.commentsError).toBeTruthy(); }); + + describe('priority flag', () => { + const oneHit = () => 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, + }); + + // The first comments request hangs, like a fetch stalled by losing the network. + async function renderWithStalledComments() { + let stalled = false; + server.use( + http.get(`${ALGOLIA_API}/search`, async () => { + stalled = true; + await new Promise(() => { /* never settles */ }); + return oneHit(); + }) + ); + const hook = renderHook( + ({ deferComments }) => useItemWithComments(12345, { initialItem: testItem, deferComments }), + { wrapper: networkWrapper, initialProps: { deferComments: false } } + ); + await waitFor(() => expect(stalled).toBe(true)); + expect(isPriorityFetchActive()).toBe(true); + return hook; + } + + it('is released when the comments arrive through the reconnect retry', async () => { + const { result, rerender, unmount } = await renderWithStalledComments(); + + server.use(http.get(`${ALGOLIA_API}/search`, oneHit)); + act(() => { window.dispatchEvent(new Event('offline')); }); + act(() => { window.dispatchEvent(new Event('online')); }); + + await waitFor(() => expect(result.current.comments).toHaveLength(1)); + expect(isPriorityFetchActive()).toBe(false); + + // A swipe panel two away turns deferred, then unmounts. + rerender({ deferComments: true }); + unmount(); + expect(isPriorityFetchActive()).toBe(false); + }); + + it('is released when the reconnect retry fails', async () => { + const { result } = await renderWithStalledComments(); + + server.use(http.get(`${ALGOLIA_API}/search`, () => new HttpResponse(null, { status: 500 }))); + act(() => { window.dispatchEvent(new Event('offline')); }); + act(() => { window.dispatchEvent(new Event('online')); }); + + await waitFor(() => expect(result.current.commentsError).toBeTruthy()); + expect(isPriorityFetchActive()).toBe(false); + }); + + it('is released when the panel turns deferred before the reconnect retry settles', async () => { + const { result, rerender } = await renderWithStalledComments(); + + let release: (() => void) | undefined; + server.use( + http.get(`${ALGOLIA_API}/search`, async () => { + await new Promise(resolve => { release = resolve; }); + return oneHit(); + }) + ); + act(() => { window.dispatchEvent(new Event('offline')); }); + act(() => { window.dispatchEvent(new Event('online')); }); + await waitFor(() => expect(release).toBeDefined()); + + rerender({ deferComments: true }); + expect(isPriorityFetchActive()).toBe(true); + + release!(); + await waitFor(() => expect(result.current.comments).toHaveLength(1)); + expect(isPriorityFetchActive()).toBe(false); + }); + }); + }); + + describe('priority flag for a comment item', () => { + it('is released once the comment item loads', async () => { + vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ + id: 1001, by: 'user1', text: 'A comment', time: Math.floor(Date.now() / 1000) - 60, parent: 12345, type: 'comment', + }); + + const { result } = renderHook(() => useItemWithComments(1001)); + + await waitFor(() => expect(result.current.item?.type).toBe('comment')); + expect(isPriorityFetchActive()).toBe(false); + }); }); describe('refresh loading states', () => { @@ -1003,5 +1091,105 @@ describe('useItemWithComments', () => { expect(result.current.error).toBeTruthy(); }); + + it('reports a refresh whose comments fail as a comments error', async () => { + server.use( + http.get(`${ALGOLIA_API}/search`, () => new HttpResponse(null, { status: 503 })) + ); + + const { result } = renderHook(() => useItemWithComments(12345)); + + await waitFor(() => { + expect(result.current.commentsError).toBeTruthy(); + }); + + await act(async () => { + await result.current.refresh(); + }); + + expect(result.current.error).toBeNull(); + expect(result.current.commentsError).toBeTruthy(); + expect(result.current.item?.id).toBe(12345); + expect(result.current.itemLoading).toBe(false); + expect(result.current.commentsLoading).toBe(false); + }); + }); + + describe('retryComments', () => { + const askItem = createStoryItem({ ...testItem, type: 'ask' }); + + beforeEach(() => { + server.use( + http.get(`${ALGOLIA_API}/search`, () => new HttpResponse(null, { status: 503 })) + ); + }); + + it('keeps the item when the comments fail again', async () => { + const { result } = renderHook(() => + useItemWithComments(12345, { initialItem: askItem }) + ); + + await waitFor(() => { + expect(result.current.commentsError).toBeTruthy(); + }); + + let rejected = false; + await act(async () => { + await result.current.retryComments().catch(() => { rejected = true; }); + }); + + expect(rejected).toBe(true); + expect(result.current.error).toBeNull(); + expect(result.current.commentsError).toBeTruthy(); + expect(result.current.item?.type).toBe('ask'); + }); + + it('keeps the comments error set while the retry is in flight', async () => { + const { result } = renderHook(() => + useItemWithComments(12345, { initialItem: askItem }) + ); + + await waitFor(() => { + expect(result.current.commentsError).toBeTruthy(); + }); + + let retryPromise: Promise; + act(() => { + retryPromise = result.current.retryComments(); + }); + + expect(result.current.commentsError).toBeTruthy(); + expect(result.current.commentsLoading).toBe(false); + + await act(async () => { + await retryPromise!.catch(() => { /* still failing */ }); + }); + }); + + it('loads the comments and keeps the item type when the retry succeeds', async () => { + const { result } = renderHook(() => + useItemWithComments(12345, { initialItem: askItem }) + ); + + await waitFor(() => { + expect(result.current.commentsError).toBeTruthy(); + }); + + server.use( + http.get(`${ALGOLIA_API}/search`, () => HttpResponse.json({ + hits: [{ objectID: '1001', author: 'user1', comment_text: 'Back', created_at_i: 1000, parent_id: 12345, story_id: 12345 }], + nbHits: 1, page: 0, nbPages: 1, hitsPerPage: 200, + })) + ); + + await act(async () => { + await result.current.retryComments(); + }); + + expect(result.current.commentsError).toBeNull(); + expect(result.current.comments).toHaveLength(1); + expect(result.current.item?.type).toBe('ask'); + expect(getCachedItem(12345)?.comments).toHaveLength(1); + }); }); }); diff --git a/src/hooks/useItemWithComments.ts b/src/hooks/useItemWithComments.ts index 686eb65..b32d4b7 100644 --- a/src/hooks/useItemWithComments.ts +++ b/src/hooks/useItemWithComments.ts @@ -26,6 +26,8 @@ interface UseItemWithCommentsResult { isNotFound: boolean; commentsError: string | null; refresh: () => Promise; + /** Refetch the comments only; a failure stays a `commentsError`. */ + retryComments: () => Promise; } // Swipe-position snapshots store stories without `text` (see swipePosition.ts), @@ -69,6 +71,10 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul // Ref to the main effect's AbortController so the reconnect handler can abort stale fetches const controllerRef = useRef(null); + // Releases the main effect's priority registration. The reconnect handler + // calls it: the fetch it aborts no longer can, and a panel that turns + // deferred skips the effect cleanup. + const releasePriorityRef = useRef<(() => void) | null>(null); const getStableOptions = useEffectEvent(() => ({ isPriority, @@ -149,6 +155,13 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul registerPriorityFetch(); didRegister = true; } + const releasePriority = () => { + if (didRegister) { + unregisterPriorityFetch(); + didRegister = false; + } + }; + releasePriorityRef.current = releasePriority; async function loadItem() { if (initialItem) { @@ -174,10 +187,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul setCommentsLoading(false); // Unregister priority on item fetch failure so prefetchers aren't blocked - if (didRegister) { - unregisterPriorityFetch(); - didRegister = false; - } + releasePriority(); } return null; } @@ -206,10 +216,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul // Unregister priority so section prefetch and other lower-priority // fetches can proceed. - if (didRegister) { - unregisterPriorityFetch(); - didRegister = false; - } + releasePriority(); } } catch (err) { if (!controller.signal.aborted && !(err instanceof Error && err.name === 'AbortError')) { @@ -219,10 +226,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul console.warn('Failed to load comments:', err); // Unregister priority even on failure so prefetchers aren't blocked forever - if (didRegister) { - unregisterPriorityFetch(); - didRegister = false; - } + releasePriority(); } } } @@ -242,6 +246,9 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul await loadComments(itemData, false); } } + // A comment item fetches nothing more. After an abort, whoever + // aborted releases it. + if (!controller.signal.aborted) releasePriority(); } void load(); @@ -254,9 +261,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul // Cleanup from itemId change, unmount, or becoming non-deferred. controller.abort(); controllerRef.current = null; - if (didRegister) { - unregisterPriorityFetch(); - } + releasePriority(); }; }, [itemId, deferComments]); // All other values read via Effect Events @@ -287,6 +292,9 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul // Abort the hanging fetch so its promise settles (AbortError, swallowed by the effect) controllerRef.current?.abort(); + // Read now: by the time this fetch settles, the main effect may have + // re-run for another item. + const releasePriority = releasePriorityRef.current; const controller = new AbortController(); controllerRef.current = controller; @@ -306,7 +314,8 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul if (controller.signal.aborted || (err instanceof Error && err.name === 'AbortError')) return; setCommentsLoading(false); setCommentsError(err instanceof Error ? err.message : 'Failed to load comments'); - }); + }) + .finally(() => releasePriority?.()); return () => { controller.abort(); @@ -326,26 +335,51 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul setItemLoading(true); setCommentsLoading(true); + let itemData: Item; try { - const itemData = await fetchItemOnly(itemId); + itemData = await fetchItemOnly(itemId); setItem(itemData); - - // Comment items use a different fetch path (useCommentDetail via Algolia /items) - if (itemData.type !== 'comment') { - const commentsData = await fetchCommentsForItem(itemId); - setComments(commentsData); - setCachedItem(itemId, itemData, commentsData); - } } catch (err) { setError(err instanceof Error ? err.message : String(err)); setIsNotFound(err instanceof NotFoundError); - throw err; - } finally { setItemLoading(false); setCommentsLoading(false); + throw err; + } + setItemLoading(false); + + // Comment items use a different fetch path (useCommentDetail via Algolia /items) + if (itemData.type !== 'comment') { + try { + const commentsData = await fetchCommentsForItem(itemId); + setComments(commentsData); + setCachedItem(itemId, itemData, commentsData); + } catch (err) { + // The item loaded, so the page can show it with the comments error. + setCommentsError(err instanceof Error ? err.message : 'Failed to load comments'); + } } + setCommentsLoading(false); }, [itemId]); + // Behind the comments section's retry. `commentsError` stays set until the + // fetch settles: the section shows its skeleton for it, and clearing it + // would show "No comments yet." meanwhile. It rejects on failure so + // useAutoRetry counts the attempt. + const retryComments = useCallback(async () => { + try { + const { item: fetchedItem, comments: commentsData } = await fetchItemWithComments(itemId); + setItem(current => withFetchedFields(current, fetchedItem)); + setComments(commentsData); + setCommentsError(null); + const fullItem = withFetchedFields(item, fetchedItem); + if (fullItem) setCachedItem(itemId, fullItem, commentsData, 3); + } catch (err) { + setCommentsError(err instanceof Error ? err.message : 'Failed to load comments'); + throw err; + } + }, [itemId, item]); + return { item, comments, @@ -355,6 +389,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul error, isNotFound, commentsError, - refresh + refresh, + retryComments }; } diff --git a/src/pages/ItemDetail.test.tsx b/src/pages/ItemDetail.test.tsx index 40f3982..44abb9e 100644 --- a/src/pages/ItemDetail.test.tsx +++ b/src/pages/ItemDetail.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'; -import { screen, waitFor, fireEvent } from '@testing-library/react'; +import { screen, waitFor, fireEvent, act } from '@testing-library/react'; import { render } from '../test/test-utils'; import { Routes, Route } from 'react-router'; import { ItemDetail } from './ItemDetail'; @@ -96,6 +96,98 @@ describe('ItemDetail', () => { }); }); + describe('comments that keep failing', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it('keeps the story on screen through every automatic comments retry', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + let commentRequests = 0; + server.use( + http.get(`${ALGOLIA_API}/search`, () => { + commentRequests++; + return new HttpResponse(null, { status: 503 }); + }), + ); + + const advance = (ms: number) => act(async () => { await vi.advanceTimersByTimeAsync(ms); }); + + renderItemDetail(12345); + + await screen.findByRole('heading', { level: 1 }); + // The first load, then three retries 2s, 4s and 8s apart. + for (let requests = 1; requests <= 4; requests++) { + for (let step = 0; step < 100 && commentRequests < requests; step++) await advance(100); + await advance(100); + expect(commentRequests).toBe(requests); + expect(screen.getByRole('heading', { level: 1 })).toBeInTheDocument(); + } + + for (let step = 0; step < 20 && !screen.queryByRole('button', { name: 'Retry' }); step++) await advance(100); + const retry = screen.getByRole('button', { name: 'Retry' }); + expect(screen.getByText('Failed to load comments')).toBeInTheDocument(); + expect(screen.queryByText('Failed to load item')).not.toBeInTheDocument(); + expect(commentRequests).toBe(4); + + server.use( + http.get(`${ALGOLIA_API}/search`, () => HttpResponse.json({ + hits: [{ objectID: '1001', author: 'patio11', comment_text: 'Loaded on retry', created_at_i: 1000, parent_id: 12345, story_id: 12345 }], + nbHits: 1, page: 0, nbPages: 1, hitsPerPage: 200, + })), + ); + fireEvent.click(retry); + + expect(await screen.findByText('Loaded on retry')).toBeInTheDocument(); + expect(screen.getByRole('heading', { level: 1 })).toBeInTheDocument(); + }); + + it('keeps a comment on screen through every automatic replies retry', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + const text = 'The wasm-bindgen approach is really interesting.'; + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => ( + Number(id) === 1001 + ? { id: 1001, by: 'patio11', text, time: Math.floor(Date.now() / 1000) - 1800, parent: 12345, type: 'comment' } + : defaultItem + )); + let repliesRequests = 0; + server.use( + http.get(`${ALGOLIA_API}/items/:id`, () => { + repliesRequests++; + return new HttpResponse(null, { status: 503 }); + }), + ); + + const advance = (ms: number) => act(async () => { await vi.advanceTimersByTimeAsync(ms); }); + + renderItemDetail(1001); + + await screen.findByText(text); + // The first load, then three retries 2s, 4s and 8s apart. + for (let requests = 1; requests <= 4; requests++) { + for (let step = 0; step < 100 && repliesRequests < requests; step++) await advance(100); + await advance(100); + expect(repliesRequests).toBe(requests); + expect(screen.getByText(text)).toBeInTheDocument(); + } + + for (let step = 0; step < 20 && !screen.queryByRole('button', { name: 'Retry' }); step++) await advance(100); + const retry = screen.getByRole('button', { name: 'Retry' }); + expect(screen.getByText('Failed to load replies')).toBeInTheDocument(); + expect(screen.queryByText('Failed to load comment')).not.toBeInTheDocument(); + expect(screen.getByText('patio11')).toBeInTheDocument(); + expect(repliesRequests).toBe(4); + + server.use( + http.get(`${ALGOLIA_API}/items/:id`, () => HttpResponse.json(mockAlgoliaCommentItem)), + ); + fireEvent.click(retry); + + expect(await screen.findByText('tptacek')).toBeInTheDocument(); + expect(screen.getByText('patio11')).toBeInTheDocument(); + }); + }); + describe('comment detection', () => { it('renders CommentDetail when item.type is comment', async () => { vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { diff --git a/src/pages/ItemDetail.tsx b/src/pages/ItemDetail.tsx index 2a40c6d..b950356 100644 --- a/src/pages/ItemDetail.tsx +++ b/src/pages/ItemDetail.tsx @@ -8,7 +8,7 @@ import { useAutoRetry } from '../hooks/useAutoRetry'; export function ItemDetail() { const { id } = useParams(); - const { item, comments, itemLoading, commentsLoading, error, isNotFound, commentsError, refresh } = useItemWithComments(id ?? ''); + const { item, comments, itemLoading, commentsLoading, error, isNotFound, commentsError, refresh, retryComments } = useItemWithComments(id ?? ''); const { isOnline } = useNetworkStatus(); const { isRetrying: isItemRetrying, resetRetry: resetItemRetry } = useAutoRetry({ @@ -91,7 +91,7 @@ export function ItemDetail() { diff --git a/src/pages/StoryList.test.tsx b/src/pages/StoryList.test.tsx new file mode 100644 index 0000000..066aaf0 --- /dev/null +++ b/src/pages/StoryList.test.tsx @@ -0,0 +1,64 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { Routes, Route, useNavigate } from 'react-router'; +import { render, screen, waitFor, act, fireEvent } from '../test/test-utils'; +import { MobileStoryRoute } from '../App'; +import { hnSdk } from '../api/hnSdk'; +import { __resetFetchCachesForTests } from '../api/hn'; +import { saveListSessionState, getListSessionState } from '../utils/itemCache'; +import { setCachedFeed } from '../utils/feedCache'; +import { createStoryItem } from '../test/factories'; +import type { FirebaseItem } from '../types'; + +const ids = Array.from({ length: 80 }, (_, i) => 1000 + i); +const story = (id: number): FirebaseItem => ({ + id, type: 'story', title: `Story ${id}`, by: 'u', score: 1, + time: Math.floor(Date.now() / 1000) - 60, descendants: 0, url: `https://example.com/${id}`, +}); + +function HistoryButtons() { + const navigate = useNavigate(); + return ( + <> + + + + ); +} + +// Under the app's feed routes, where one route component renders every feed. +describe('StoryList on the feed routes', () => { + beforeEach(() => { + __resetFetchCachesForTests(); + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(ids); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => story(Number(id))); + }); + + it('restores a feed\'s saved list on Back from another feed', async () => { + // Best as opening its 50th story left it: two pages loaded. + const best = ids.slice(0, 50).map(id => createStoryItem({ id, title: `Story ${id}` })); + setCachedFeed('best', best); + saveListSessionState('best', { + scrollY: 0, storyIds: best.map(s => s.id), position: 60, seenIds: best.map(s => s.id), hasMore: true, + }); + + render( + <> + + } /> + } /> + + + , + { initialEntries: ['/best'] }, + ); + await waitFor(() => expect(screen.getAllByTestId('story-card')).toHaveLength(50)); + + fireEvent.click(screen.getByRole('button', { name: 'show' })); + await waitFor(() => expect(screen.getByRole('link', { name: 'Story 1000' })).toBeInTheDocument()); + fireEvent.click(screen.getByRole('button', { name: 'back' })); + await act(async () => { await new Promise(r => setTimeout(r, 100)); }); + + expect(screen.getAllByTestId('story-card')).toHaveLength(50); + expect(getListSessionState('best')?.storyIds).toHaveLength(50); + }); +}); diff --git a/src/pages/StoryList.tsx b/src/pages/StoryList.tsx index fa0b601..ad42879 100644 --- a/src/pages/StoryList.tsx +++ b/src/pages/StoryList.tsx @@ -14,26 +14,15 @@ export function StoryList({ type }: { type: FeedType }) { error, hasMore, loadMore, - reset, isFromCache, isFromSession, initialScrollY, saveSessionState, } = useInfiniteStories(type); - // Track previous type so the reset effect only fires on type - // CHANGE, not on initial mount. - const prevTypeRef = useRef(type); + // `type` must not change for a mounted list: the feed routes key it by type. const hasRestoredScroll = useRef(false); - useEffect(() => { - if (prevTypeRef.current !== type) { - prevTypeRef.current = type; - hasRestoredScroll.current = false; - reset(); - } - }, [type, reset]); - // Restore scroll BEFORE paint so the user doesn't see a flash of // top-of-page on back-nav. useLayoutEffect(() => { diff --git a/src/test/storageQuota.ts b/src/test/storageQuota.ts new file mode 100644 index 0000000..f97bf29 --- /dev/null +++ b/src/test/storageQuota.ts @@ -0,0 +1,41 @@ +/** + * Swaps in a localStorage that throws, as a browser does, once its keys and + * values would pass `limit` characters. `fill` takes up whatever room is left; + * `restore` swaps the usual storage back. + */ +export function installStorageQuota(limit: number): { fill: () => void; restore: () => void } { + const original = globalThis.localStorage; + const store = new Map(); + const used = () => { + let chars = 0; + for (const [key, value] of store) chars += key.length + value.length; + return chars; + }; + + const storage = { + get length() { return store.size; }, + key: (index: number) => [...store.keys()][index] ?? null, + getItem: (key: string) => store.get(key) ?? null, + setItem: (key: string, value: string) => { + const replaced = store.has(key) ? key.length + store.get(key)!.length : 0; + if (used() - replaced + key.length + value.length > limit) { + throw new DOMException('The quota has been exceeded.', 'QuotaExceededError'); + } + store.set(key, String(value)); + }, + removeItem: (key: string) => { store.delete(key); }, + clear: () => { store.clear(); }, + }; + + const install = (value: unknown) => + Object.defineProperty(globalThis, 'localStorage', { value, writable: true, configurable: true }); + install(storage); + + return { + fill: () => { + const key = 'test:filler'; + storage.setItem(key, 'z'.repeat(limit - used() - key.length)); + }, + restore: () => { install(original); }, + }; +} diff --git a/src/utils/feedCache.test.ts b/src/utils/feedCache.test.ts index 84749f8..e19878f 100644 --- a/src/utils/feedCache.test.ts +++ b/src/utils/feedCache.test.ts @@ -1,6 +1,8 @@ import { describe, it, expect, beforeEach } from 'vitest'; import { getCachedFeed, setCachedFeed, clearFeedCache, isCacheFresh } from './feedCache'; -import { createStoryItem } from '../test/factories'; +import { setCachedItem } from './itemCache'; +import { createComment, createStoryItem } from '../test/factories'; +import { installStorageQuota } from '../test/storageQuota'; describe('feedCache', () => { beforeEach(() => { @@ -32,6 +34,22 @@ describe('feedCache', () => { expect(topResult.stories[0].title).toBe('Top Story'); expect(bestResult.stories[0].title).toBe('Best Story'); }); + + it('makes room for the list when cached items have filled the storage', () => { + const quota = installStorageQuota(20_000); + try { + for (let i = 0; i < 4; i++) { + setCachedItem(i, createStoryItem({ id: i }), [createComment({ id: i, text: 'x'.repeat(2_000) })]); + } + quota.fill(); + + setCachedFeed('top', Array.from({ length: 10 }, (_, i) => createStoryItem({ id: 100 + i }))); + + expect(getCachedFeed('top')?.stories).toHaveLength(10); + } finally { + quota.restore(); + } + }); }); describe('getCachedFeed', () => { diff --git a/src/utils/feedCache.ts b/src/utils/feedCache.ts index 8fe370b..e4ee2fa 100644 --- a/src/utils/feedCache.ts +++ b/src/utils/feedCache.ts @@ -1,4 +1,5 @@ import type { StoryItem, FeedType } from '../types'; +import { setLocalStorageItem } from './itemCache'; /** Feed list cache (localStorage, stale-while-revalidate). */ @@ -35,7 +36,7 @@ export function setCachedFeed(type: FeedType, stories: StoryItem[]): void { try { const key = `${FEED_CACHE_KEY_PREFIX}${type}`; const data = { stories, timestamp: Date.now() }; - localStorage.setItem(key, JSON.stringify(data)); + setLocalStorageItem(key, JSON.stringify(data)); } catch { /* best-effort */ } } diff --git a/src/utils/itemCache.test.ts b/src/utils/itemCache.test.ts index eb88e79..9c60715 100644 --- a/src/utils/itemCache.test.ts +++ b/src/utils/itemCache.test.ts @@ -5,11 +5,14 @@ import { saveListSessionState, getListSessionState, clearListSessionState, + setLocalStorageItem, ITEM_CACHE_KEY_PREFIX, FEED_SESSION_KEY_PREFIX, + MAX_ITEM_CACHE_CHARS, } from './itemCache'; import type { Comment, StoryItem } from '../types'; import { createStoryItem, createComment } from '../test/factories'; +import { installStorageQuota } from '../test/storageQuota'; describe('itemCache', () => { beforeEach(() => { @@ -178,14 +181,58 @@ describe('itemCache', () => { vi.advanceTimersByTime(100); } - let count = 0; - for (let i = 0; i < localStorage.length; i++) { - if (localStorage.key(i)?.startsWith(ITEM_CACHE_KEY_PREFIX)) { - count++; - } + expect(cachedItemKeys()).toHaveLength(60); + expect(getCachedItem(4)).toBeNull(); + expect(getCachedItem(5)).not.toBeNull(); + }); + + it('keeps the cached items within their size budget, dropping the oldest', () => { + // Five of these fit the budget; each write past that drops the oldest. + const text = 'x'.repeat(MAX_ITEM_CACHE_CHARS / 5 - 1_000); + for (let i = 0; i < 8; i++) { + setCachedItem(i, createStoryItem({ id: i }), [createComment({ id: i, text })]); + vi.advanceTimersByTime(100); } - expect(count).toBeLessThanOrEqual(61); // small slack for prune timing + expect(cachedItemChars()).toBeLessThanOrEqual(MAX_ITEM_CACHE_CHARS); + expect(cachedItemKeys()).toEqual([3, 4, 5, 6, 7].map(id => `${ITEM_CACHE_KEY_PREFIX}${id}`)); + }); + + it('does not keep a thread bigger than half the budget, nor its older copy', () => { + setCachedItem(123, mockItem, mockComments); + const text = 'x'.repeat(MAX_ITEM_CACHE_CHARS / 2); + + setCachedItem(123, mockItem, [createComment({ id: 1, text })]); + + expect(getCachedItem(123)).toBeNull(); + }); + + it('reads the age of each cached item without parsing its thread', () => { + for (let i = 0; i < 60; i++) { + setCachedItem(i, createStoryItem({ id: i }), mockComments); + vi.advanceTimersByTime(100); + } + const parse = vi.spyOn(JSON, 'parse'); + + setCachedItem(999, mockItem, mockComments); + + expect(parse).not.toHaveBeenCalled(); + parse.mockRestore(); + expect(getCachedItem(0)).toBeNull(); + expect(getCachedItem(999)).not.toBeNull(); + }); + + it('keeps a readable entry without a write time as the oldest', () => { + localStorage.setItem(`${ITEM_CACHE_KEY_PREFIX}1`, JSON.stringify({ item: mockItem, comments: [] })); + for (let i = 2; i <= 60; i++) { + setCachedItem(i, createStoryItem({ id: i }), []); + } + expect(getCachedItem(1)).not.toBeNull(); + + setCachedItem(61, mockItem, []); + + expect(getCachedItem(1)).toBeNull(); + expect(getCachedItem(2)).not.toBeNull(); }); it('removes corrupted entries during pruning', () => { @@ -212,8 +259,68 @@ describe('itemCache', () => { }); }); + describe('setLocalStorageItem', () => { + let quota: ReturnType; + + beforeEach(() => { + quota = installStorageQuota(20_000); + for (let i = 0; i < 4; i++) { + setCachedItem(i, createStoryItem({ id: i }), [createComment({ id: i, text: 'x'.repeat(2_000) })]); + vi.advanceTimersByTime(100); + } + }); + + afterEach(() => { + quota.restore(); + }); + + it('stores the value', () => { + setLocalStorageItem('feed:top', 'value'); + + expect(localStorage.getItem('feed:top')).toBe('value'); + expect(cachedItemKeys()).toHaveLength(4); + }); + + it('makes room in a full storage by dropping the older half of the cached items', () => { + quota.fill(); + + setLocalStorageItem('feed:top', 'y'.repeat(3_000)); + + expect(localStorage.getItem('feed:top')).toHaveLength(3_000); + expect(cachedItemKeys()).toEqual([`${ITEM_CACHE_KEY_PREFIX}2`, `${ITEM_CACHE_KEY_PREFIX}3`]); + }); + + it('makes room for a cached item the same way', () => { + quota.fill(); + + setCachedItem(99, mockItem, [createComment({ id: 99, text: 'y'.repeat(3_000) })]); + + expect(getCachedItem(99)).not.toBeNull(); + expect(getCachedItem(0)).toBeNull(); + }); + + it('gives up quietly when dropping cached items is not enough', () => { + quota.fill(); + + expect(() => setLocalStorageItem('feed:top', 'y'.repeat(30_000))).not.toThrow(); + expect(localStorage.getItem('feed:top')).toBeNull(); + }); + }); }); +function cachedItemKeys(): string[] { + const keys: string[] = []; + for (let i = 0; i < localStorage.length; i++) { + const key = localStorage.key(i); + if (key?.startsWith(ITEM_CACHE_KEY_PREFIX)) keys.push(key); + } + return keys.sort((a, b) => Number(a.slice(ITEM_CACHE_KEY_PREFIX.length)) - Number(b.slice(ITEM_CACHE_KEY_PREFIX.length))); +} + +function cachedItemChars(): number { + return cachedItemKeys().reduce((sum, key) => sum + key.length + localStorage.getItem(key)!.length, 0); +} + describe('sessionStorage - List Session State', () => { beforeEach(() => { sessionStorage.clear(); diff --git a/src/utils/itemCache.ts b/src/utils/itemCache.ts index c3f3627..80ff15b 100644 --- a/src/utils/itemCache.ts +++ b/src/utils/itemCache.ts @@ -6,6 +6,11 @@ export const ITEM_CACHE_KEY_PREFIX = 'item:'; const CACHE_MAX_AGE = 5 * 60 * 1000; // 5 minutes const CACHE_STALE_AGE = 24 * 60 * 60 * 1000; // 24 hours const MAX_CACHED_ITEMS = 60; +// Chromium, Firefox and WebKit give an origin 5,242,880 characters of +// localStorage. Items get up to this much of it, so the feed lists, viewed +// times and theme still fit beside them. +export const MAX_ITEM_CACHE_CHARS = 3_000_000; +const TIMESTAMP_FIELD = '"timestamp":'; export function getCachedItem(itemId: number | string): { item: Item; comments: Comment[]; timestamp: number; isFresh: boolean; orderedDepth: number } | null { try { @@ -38,62 +43,98 @@ export function getCachedItem(itemId: number | string): { item: Item; comments: /** `orderedDepth`: 1 = top-level only (prefetch), 3 = full ordering. */ export function setCachedItem(itemId: number | string, item: Item, comments: Comment[], orderedDepth = 3): void { + const key = `${ITEM_CACHE_KEY_PREFIX}${itemId}`; try { - // Clean up old entries first - pruneItemCache(); - - const key = `${ITEM_CACHE_KEY_PREFIX}${itemId}`; - const data = { - item, - comments, - timestamp: Date.now(), - orderedDepth, - }; - localStorage.setItem(key, JSON.stringify(data)); - } catch { - // localStorage might be full - try to make room - try { - pruneItemCache(5); - const key = `${ITEM_CACHE_KEY_PREFIX}${itemId}`; - localStorage.setItem(key, JSON.stringify({ item, comments, timestamp: Date.now(), orderedDepth })); - } catch { /* best-effort */ } - } + const value = JSON.stringify({ item, comments, timestamp: Date.now(), orderedDepth }); + // A thread this big would push out half the cache, so it isn't kept. + if (value.length > MAX_ITEM_CACHE_CHARS / 2) { + // An older copy would still be read as fresh in its place. + localStorage.removeItem(key); + return; + } + pruneItemCache(key, key.length + value.length); + setLocalStorageItem(key, value); + } catch { /* best-effort */ } } -function pruneItemCache(removeCount = 0): void { +/** + * `localStorage.setItem` that makes room when storage is full: the older half + * of the cached items goes, and the write is tried once more. + */ +export function setLocalStorageItem(key: string, value: string): void { try { - const itemKeys = []; - const corruptKeys: string[] = []; - - for (let i = 0; i < localStorage.length; i++) { - const key = localStorage.key(i); - if (key?.startsWith(ITEM_CACHE_KEY_PREFIX)) { - try { - const data = JSON.parse(localStorage.getItem(key)!) as { timestamp?: number }; - itemKeys.push({ key, timestamp: data.timestamp ?? 0 }); - } catch { - // Corrupted entry, collect for removal after the scan - corruptKeys.push(key); - } - } - } - - // Remove corrupted entries in a separate pass to avoid - // mutating localStorage indices during the scan loop. - for (const key of corruptKeys) { - localStorage.removeItem(key); + localStorage.setItem(key, value); + return; + } catch { /* full, most likely */ } + try { + const entries = readItemCache(); + for (const entry of entries.slice(0, Math.ceil(entries.length / 2))) { + localStorage.removeItem(entry.key); } - - itemKeys.sort((a, b) => a.timestamp - b.timestamp); - - // Remove oldest entries if over limit or if forced - const toRemove = removeCount || Math.max(0, itemKeys.length - MAX_CACHED_ITEMS); - for (let i = 0; i < toRemove && i < itemKeys.length; i++) { - localStorage.removeItem(itemKeys[i].key); + localStorage.setItem(key, value); + } catch { /* best-effort */ } +} + +interface ItemCacheEntry { key: string; timestamp: number; chars: number } + +/** Drops the oldest items until one more of `incomingChars` fits the budget. */ +function pruneItemCache(incomingKey: string, incomingChars: number): void { + try { + const entries = readItemCache().filter(entry => entry.key !== incomingKey); + let count = entries.length + 1; + let chars = incomingChars; + for (const entry of entries) chars += entry.chars; + + for (const entry of entries) { + if (count <= MAX_CACHED_ITEMS && chars <= MAX_ITEM_CACHE_CHARS) break; + localStorage.removeItem(entry.key); + count--; + chars -= entry.chars; } } catch { /* best-effort */ } } +/** The cached items, oldest first. Unreadable entries are removed. */ +function readItemCache(): ItemCacheEntry[] { + const entries: ItemCacheEntry[] = []; + const corruptKeys: string[] = []; + + for (let i = 0; i < localStorage.length; i++) { + const key = localStorage.key(i); + if (!key?.startsWith(ITEM_CACHE_KEY_PREFIX)) continue; + const value = localStorage.getItem(key) ?? ''; + const timestamp = readTimestamp(value); + if (timestamp === null) corruptKeys.push(key); + else entries.push({ key, timestamp, chars: key.length + value.length }); + } + + // Removed after the scan, which reads localStorage by index. + for (const key of corruptKeys) { + localStorage.removeItem(key); + } + + return entries.sort((a, b) => a.timestamp - b.timestamp); +} + +/** + * An entry's write time, read without parsing its thread. The field comes after + * the item and comments, whose quotes are escaped, so its last match is the one. + */ +function readTimestamp(value: string): number | null { + const at = value.lastIndexOf(TIMESTAMP_FIELD); + if (at !== -1) { + const timestamp = Number.parseInt(value.slice(at + TIMESTAMP_FIELD.length), 10); + if (Number.isFinite(timestamp)) return timestamp; + } + try { + // A readable entry with no write time counts as the oldest. + const data = JSON.parse(value) as { timestamp?: number }; + return data.timestamp ?? 0; + } catch { + return null; + } +} + // ============================================================================ // Session State (for instant back navigation) // Uses sessionStorage - clears when tab closes (desired behavior) diff --git a/src/utils/viewedItems.test.ts b/src/utils/viewedItems.test.ts index 020d355..e35b845 100644 --- a/src/utils/viewedItems.test.ts +++ b/src/utils/viewedItems.test.ts @@ -21,6 +21,9 @@ import { DETAIL_DWELL_LONG_MS, detailTtlHoursForDwell, } from './viewedItems'; +import { setCachedItem } from './itemCache'; +import { createComment, createStoryItem } from '../test/factories'; +import { installStorageQuota } from '../test/storageQuota'; describe('viewedItems', () => { beforeEach(() => { @@ -97,6 +100,22 @@ describe('viewedItems', () => { const stored = JSON.parse(localStorage.getItem(VIEWED_KEY)!) as number[]; expect(stored.length).toBe(50_000); }); + + it('makes room to save when cached items have filled the storage', () => { + const quota = installStorageQuota(20_000); + try { + for (let i = 0; i < 4; i++) { + setCachedItem(i, createStoryItem({ id: i }), [createComment({ id: i, text: 'x'.repeat(2_000) })]); + } + quota.fill(); + + markViewed(12345); + + expect(JSON.parse(localStorage.getItem(VIEWED_KEY)!)).toEqual([12345]); + } finally { + quota.restore(); + } + }); }); describe('clearViewed', () => { diff --git a/src/utils/viewedItems.ts b/src/utils/viewedItems.ts index 55d3a8b..54756c4 100644 --- a/src/utils/viewedItems.ts +++ b/src/utils/viewedItems.ts @@ -1,4 +1,5 @@ import { useSyncExternalStore } from 'react'; +import { setLocalStorageItem } from './itemCache'; /** Track viewed items in localStorage. */ @@ -55,9 +56,7 @@ export function markViewed(itemId: number | string): void { if (first !== undefined) set.delete(first); } - try { - localStorage.setItem(VIEWED_KEY, JSON.stringify([...set])); - } catch { /* best-effort */ } + setLocalStorageItem(VIEWED_KEY, JSON.stringify([...set])); notifyListeners(); } @@ -134,9 +133,7 @@ function createTimeMap(storageKey: string) { return cache; }, save(): void { - try { - localStorage.setItem(storageKey, JSON.stringify(cache)); - } catch { /* best-effort */ } + setLocalStorageItem(storageKey, JSON.stringify(cache)); }, reset(): void { cache = null;