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 (