From e5111e87a60cdbb16a06e2c3f9a549bc108eb72d Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:06:30 +0100 Subject: [PATCH 1/3] fix: show flagged and deleted replies on a comment's own page A comment's page built its replies from Algolia's item tree, which leaves out flagged and deleted comments along with every reply under them. The story thread already brings those back, so the same comment showed fewer replies on its own page. On story 50319510, comment 50320482 showed 23 replies in the thread and 8 on its page, desktop and phone alike: a flagged reply and its 14 replies were missing. The page still shows the item tree's replies first. It then reads the story's comments from search and the missing parents from Firebase, as the thread does, and swaps in the fuller tree when it has more comments. A flagged reply shows [flagged] with its replies, and a deleted one shows [deleted]. If that read fails, the item tree's replies stay. When the item tree has no replies, the page first reads the comment and its replies from Firebase, and searches only if one of those has replies of its own or is live. Most such comments have no replies at all, and the rest mostly have only flagged or deleted replies with nothing under them, which the page doesn't show. While a search that may add replies runs, the replies section keeps its skeleton instead of saying "No replies yet." Comments on the same story share one read for five minutes, so the swipe viewer's neighbouring panels don't each search the whole story. Threads bigger than search returns (1,000 comments) skip it after the first page and keep the item tree's replies. --- src/api/hn.test.ts | 137 ++++++++++++++++++++- src/api/hn.ts | 82 +++++++++++- src/components/CommentArticle.test.tsx | 28 +++++ src/components/CommentArticle.tsx | 9 +- src/components/CommentDetail.test.tsx | 7 +- src/components/CommentDetail.tsx | 3 +- src/components/FullScreenComment.test.tsx | 44 +++++++ src/components/FullScreenComment.tsx | 3 +- src/components/SwipeCommentViewer.test.tsx | 2 + src/hooks/useCommentDetail.test.ts | 109 ++++++++++++++++ src/hooks/useCommentDetail.ts | 32 ++++- 11 files changed, 442 insertions(+), 14 deletions(-) diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts index ac28557..4248d43 100644 --- a/src/api/hn.test.ts +++ b/src/api/hn.test.ts @@ -15,12 +15,13 @@ import { fetchItemOnly, fetchAlgoliaItem, fetchCommentsForItem, + fetchCommentReplies, normalizeAlgoliaItemChildren, NotFoundError, __resetFetchCachesForTests, } from './hn'; import { hnSdk } from './hnSdk'; -import type { FirebaseItem } from '../types'; +import type { AlgoliaItemResponse, FirebaseItem } from '../types'; const mockFirebaseItem: FirebaseItem = { id: 12345, @@ -1222,4 +1223,138 @@ describe('hn API utilities', () => { }); }); }); + + describe('fetchCommentReplies', () => { + const storyId = 9200; + + // Comment 101 as Algolia's item tree has it: flagged 202 and deleted 302 + // are left out, and so are their replies. + const item: AlgoliaItemResponse = { + id: 101, type: 'comment', author: 'alice', text: 'Root', created_at_i: 1700000100, + parent_id: storyId, story_id: storyId, + children: [{ id: 201, author: 'bob', text: 'Live reply', created_at_i: 1700000200, parent_id: 101, children: [] }], + }; + const searchHits = [ + { objectID: '101', author: 'alice', comment_text: 'Root', created_at_i: 1700000100, parent_id: storyId }, + { objectID: '201', author: 'bob', comment_text: 'Live reply', created_at_i: 1700000200, parent_id: 101 }, + { objectID: '301', author: 'dave', comment_text: 'Reply to a flagged comment', created_at_i: 1700000400, parent_id: 202 }, + { objectID: '401', author: 'frank', comment_text: 'Reply to a deleted comment', created_at_i: 1700000600, parent_id: 302 }, + { objectID: '102', author: 'gina', comment_text: 'Another top-level comment', created_at_i: 1700000700, parent_id: storyId }, + ]; + const firebaseItems: FirebaseItem[] = [ + { id: 201, type: 'comment', by: 'bob', text: 'Live reply', time: 1700000200, parent: 101, kids: [302] }, + { id: 202, type: 'comment', by: 'carol', text: 'Killed text', dead: true, time: 1700000300, parent: 101, kids: [301] }, + { id: 302, type: 'comment', deleted: true, time: 1700000500, parent: 201, kids: [401] }, + { id: 401, type: 'comment', by: 'frank', text: 'Reply to a deleted comment', time: 1700000600, parent: 302 }, + { id: 102, type: 'comment', by: 'gina', text: 'Another top-level comment', time: 1700000700, parent: storyId, kids: [203] }, + { id: 203, type: 'comment', by: 'hank', text: 'Killed, no replies', dead: true, time: 1700000800, parent: 102 }, + ]; + // 201's only reply is deleted 302, so the item tree has none for it. + const liveReply: AlgoliaItemResponse = { ...item, id: 201, author: 'bob', parent_id: 101, children: [] }; + // 102's only reply is flagged 203, which has none of its own. + const flaggedLeafParent: AlgoliaItemResponse = { ...item, id: 102, author: 'gina', children: [] }; + + function mockStory(search: { nbHits: number; nbPages: number } = { nbHits: searchHits.length, nbPages: 1 }) { + const readItem = vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => firebaseItems.find(fb => fb.id === Number(id)) ?? null); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => + Response.json({ hits: searchHits, page: 0, hitsPerPage: 200, ...search })); + return { readItem, fetchSpy }; + } + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('adds flagged and deleted replies with the replies under them', async () => { + mockStory(); + + const replies = await fetchCommentReplies(item); + + expect(replies.map(c => c.id)).toEqual([201, 202]); + expect(replies[1]).toMatchObject({ author: 'carol', text: '[flagged]', parentId: 101 }); + expect(replies[1].children.map(c => c.id)).toEqual([301]); + expect(replies[0].children).toHaveLength(1); + expect(replies[0].children[0]).toMatchObject({ id: 302, deleted: true, author: '' }); + expect(replies[0].children[0].children.map(c => c.id)).toEqual([401]); + }); + + it('keeps the item tree replies for a thread bigger than search returns', async () => { + const { readItem, fetchSpy } = mockStory({ nbHits: 1500, nbPages: 5 }); + + const replies = await fetchCommentReplies(item); + + expect(replies.map(c => c.id)).toEqual([201]); + expect(replies[0].children).toEqual([]); + expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(readItem).not.toHaveBeenCalled(); + }); + + it('looks up the replies of a comment whose replies are all flagged or deleted', async () => { + mockStory(); + + const replies = await fetchCommentReplies(liveReply); + + expect(replies.map(c => c.id)).toEqual([302]); + expect(replies[0]).toMatchObject({ deleted: true }); + expect(replies[0].children.map(c => c.id)).toEqual([401]); + }); + + it('skips the story search for a comment with no replies', async () => { + const { readItem, fetchSpy } = mockStory(); + + const replies = await fetchCommentReplies({ ...item, id: 401, author: 'frank', parent_id: 302, children: [] }); + + expect(replies).toEqual([]); + expect(readItem).toHaveBeenCalledWith(401); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('skips the story search when the only replies are flagged ones without replies', async () => { + const { readItem, fetchSpy } = mockStory(); + + const replies = await fetchCommentReplies(flaggedLeafParent); + + expect(replies).toEqual([]); + expect(readItem.mock.calls.map(([id]) => Number(id))).toEqual([102, 203]); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('stops before the story search once the caller is gone', async () => { + const { readItem, fetchSpy } = mockStory(); + const controller = new AbortController(); + readItem.mockImplementation(async (id) => { + controller.abort(); + return firebaseItems.find(fb => fb.id === Number(id)) ?? null; + }); + + await expect(fetchCommentReplies(liveReply, controller.signal)).rejects.toThrow('Aborted'); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it("reads a story's comments once for comments on the same story", async () => { + const { readItem, fetchSpy } = mockStory(); + + const [rootReplies, liveReplyReplies] = await Promise.all([ + fetchCommentReplies(item), + fetchCommentReplies(liveReply), + ]); + + expect(rootReplies.map(c => c.id)).toEqual([201, 202]); + expect(liveReplyReplies.map(c => c.id)).toEqual([302]); + expect(fetchSpy).toHaveBeenCalledTimes(1); + // 201 and its reply 302 to see whether to search, then each missing parent once. + expect(readItem.mock.calls.map(([id]) => Number(id)).sort()).toEqual([201, 202, 302, 302]); + }); + + it('reads the story again after a failed read', async () => { + const { fetchSpy } = mockStory(); + fetchSpy.mockResolvedValueOnce(new Response(null, { status: 503 })); + + await expect(fetchCommentReplies(item)).rejects.toThrow(/503/); + const replies = await fetchCommentReplies(item); + + expect(replies.map(c => c.id)).toEqual([201, 202]); + expect(fetchSpy).toHaveBeenCalledTimes(2); + }); + }); }); diff --git a/src/api/hn.ts b/src/api/hn.ts index d5fb1c7..ec2e887 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -13,6 +13,7 @@ let bestStoriesCache: { ids: number[] | null; timestamp: number } = { ids: null, let showStoriesCache: { ids: number[] | null; timestamp: number } = { ids: null, timestamp: 0 }; let askStoriesCache: { ids: number[] | null; timestamp: number } = { ids: null, timestamp: 0 }; let newStoriesCache: { ids: number[] | null; timestamp: number } = { ids: null, timestamp: 0 }; +let storyCommentsCache: { storyId: number; comments: Promise; timestamp: number } | null = null; const CACHE_TTL = 5 * 60 * 1000; // 5 minutes /** @internal Testing helper to reset module-level caches between tests. */ @@ -21,6 +22,7 @@ export function __resetFetchCachesForTests() { showStoriesCache = { ids: null, timestamp: 0 }; askStoriesCache = { ids: null, timestamp: 0 }; newStoriesCache = { ids: null, timestamp: 0 }; + storyCommentsCache = null; } function getDayRange(daysAgo = 0) { @@ -355,15 +357,20 @@ export async function fetchFirebaseItem(id: number | string, signal?: AbortSigna } // Algolia is much faster than Firebase here — 1-2 requests instead of hundreds -// of recursive item fetches. -async function fetchAllCommentsAlgolia(itemId: number, signal?: AbortSignal): Promise { - const allComments: AlgoliaComment[] = []; +// of recursive item fetches. `stopIfCapped` skips the remaining pages of a +// thread bigger than search returns. +async function searchItemComments( + itemId: number, + signal?: AbortSignal, + { stopIfCapped = false } = {}, +): Promise<{ comments: AlgoliaComment[]; isCapped: boolean }> { + const comments: AlgoliaComment[] = []; let page = 0; const hitsPerPage = 200; // Algolia max let isCapped = false; while (true) { - if (signal?.aborted) return allComments; + if (signal?.aborted) break; const url = `${ALGOLIA_API}/search?tags=comment,story_${itemId}&hitsPerPage=${hitsPerPage}&page=${page}`; const response = await fetch(url, { signal }); @@ -372,11 +379,11 @@ async function fetchAllCommentsAlgolia(itemId: number, signal?: AbortSignal): Pr } const data = await response.json() as AlgoliaSearchResponse; - allComments.push(...data.hits); + comments.push(...data.hits); // Search returns at most 1,000 hits and caps nbPages to match. if (page === 0) isCapped = data.nbHits > data.nbPages * hitsPerPage; - if (data.hits.length < hitsPerPage || allComments.length >= data.nbHits || page >= data.nbPages - 1) { + if ((isCapped && stopIfCapped) || data.hits.length < hitsPerPage || comments.length >= data.nbHits || page >= data.nbPages - 1) { break; } page++; @@ -385,6 +392,12 @@ async function fetchAllCommentsAlgolia(itemId: number, signal?: AbortSignal): Pr if (page > 10) break; } + return { comments, isCapped }; +} + +async function fetchAllCommentsAlgolia(itemId: number, signal?: AbortSignal): Promise { + const { comments: allComments, isCapped } = await searchItemComments(itemId, signal); + // The item endpoint has the rest of a bigger thread. It also misses a few // comments that search has, so it adds to search's results. if (isCapped && !signal?.aborted) { @@ -725,6 +738,63 @@ export async function fetchCommentItem(id: number | string, signal?: AbortSignal }; } +// A story's comments from search, with the flagged and deleted parents it +// leaves out. Null for a thread bigger than search returns. Comments next to +// each other in the swipe viewer share one read, so no caller's signal ends it. +function fetchStoryComments(storyId: number): Promise { + if (storyCommentsCache?.storyId === storyId && Date.now() - storyCommentsCache.timestamp < CACHE_TTL) { + return storyCommentsCache.comments; + } + + const comments = (async () => { + const { comments: found, isCapped } = await searchItemComments(storyId, undefined, { stopIfCapped: true }); + if (isCapped) return null; + const missingParents = await fetchMissingParents(found, storyId); + return [...found, ...missingParents.map(threadCommentFromFirebase)]; + })(); + const entry = { storyId, comments, timestamp: Date.now() }; + storyCommentsCache = entry; + comments.catch(() => { + if (storyCommentsCache === entry) storyCommentsCache = null; + }); + return comments; +} + +// For a comment with no replies in the item tree. Most have none at all. The +// rest mostly have only flagged or deleted replies with nothing under them, +// which aren't shown. A live reply can still be in search without being in +// the item tree. +async function hasRepliesOutsideItemTree(id: number, signal?: AbortSignal): Promise { + const { kids = [] } = await fetchFirebaseItem(id, signal); + if (kids.length === 0) return false; + const replies = await readItemsBatched(kids, signal); + return replies.some(reply => (reply.kids?.length ?? 0) > 0 || (!reply.dead && !reply.deleted)); +} + +/** + * A comment's replies, with the flagged and deleted ones that have live + * replies. Algolia's item tree leaves those out along with their replies, so + * they come from the story's comments, as in the story thread. + */ +export async function fetchCommentReplies(item: AlgoliaItemResponse, signal?: AbortSignal): Promise { + if (item.story_id == null) return normalizeAlgoliaItemChildren(item.children ?? []); + const mayHaveMore = !!item.children?.length || await hasRepliesOutsideItemTree(item.id, signal); + if (signal?.aborted) { + throw new DOMException('Aborted', 'AbortError'); + } + if (!mayHaveMore) return []; + + const storyComments = await fetchStoryComments(item.story_id); + if (signal?.aborted) { + throw new DOMException('Aborted', 'AbortError'); + } + if (!storyComments) return normalizeAlgoliaItemChildren(item.children ?? []); + + const replies = flattenAlgoliaItemChildren(item.children ?? []); + const seen = new Set(replies.map(c => c.objectID)); + return buildCommentTree([...replies, ...storyComments.filter(c => !seen.has(c.objectID))], item.id); +} + export function normalizeAlgoliaItemChildren(children: AlgoliaItemChild[]): Comment[] { return children .filter(child => child.author) // skip deleted comments (no author) diff --git a/src/components/CommentArticle.test.tsx b/src/components/CommentArticle.test.tsx index 004ce2f..fe1d129 100644 --- a/src/components/CommentArticle.test.tsx +++ b/src/components/CommentArticle.test.tsx @@ -167,6 +167,34 @@ describe('CommentArticle', () => { }); }); + describe('replies while flagged and deleted ones are looked up', () => { + const replySkeleton = () => document.querySelector('section .animate-pulse'); + + it('keeps the skeleton instead of "No replies yet."', () => { + renderArticle({ moreRepliesLoading: true }); + + expect(replySkeleton()).toBeInTheDocument(); + expect(screen.queryByText('No replies yet.')).not.toBeInTheDocument(); + }); + + it('shows the replies it already has', () => { + renderArticle({ + moreRepliesLoading: true, + replies: [{ id: 2001, author: 'tptacek', text: 'A reply.', createdAt: Date.now(), parentId: 1001, children: [] }], + }); + + expect(screen.getByText('tptacek')).toBeInTheDocument(); + expect(replySkeleton()).not.toBeInTheDocument(); + }); + + it('says "No replies yet." once the lookup is done', () => { + renderArticle({ moreRepliesLoading: false }); + + expect(screen.getByText('No replies yet.')).toBeInTheDocument(); + expect(replySkeleton()).not.toBeInTheDocument(); + }); + }); + describe('author guard', () => { // 'unknown' / '' must not mint a dead /user/unknown or /user/ link — // fall back to a plain non-link byline. See isKnownAuthor. diff --git a/src/components/CommentArticle.tsx b/src/components/CommentArticle.tsx index 179c76a..9aa67f8 100644 --- a/src/components/CommentArticle.tsx +++ b/src/components/CommentArticle.tsx @@ -24,6 +24,8 @@ interface CommentArticleProps { /** The thread title is still being fetched (after `loading` clears). */ itemTitleLoading?: boolean; loading: boolean; + /** Flagged and deleted replies are still being looked up, so no replies isn't final yet. */ + moreRepliesLoading?: boolean; /** Set when the replies failed to load: their section offers a Retry that calls it. */ onRetryReplies?: () => void; articleClassName?: string; @@ -38,6 +40,7 @@ export function CommentArticle({ itemTitle, itemTitleLoading = false, loading, + moreRepliesLoading = false, onRetryReplies, articleClassName = 'mb-4', storyAuthor = '', @@ -130,12 +133,14 @@ export function CommentArticle({
- {loading ? ( + {loading || (moreRepliesLoading && replies.length === 0) ? ( // Bridges CommentDetail's initialData progressive-rendering // gap: when `comment` is seeded, PageStage skips its skeleton // and `replies=[]` would otherwise flash "No replies yet." // for the ~100-500ms before the algolia fetch resolves. On - // cold load PageStage's overlay covers this branch. + // cold load PageStage's overlay covers this branch. A comment + // whose replies are all flagged or deleted has none from + // Algolia, so it waits for those too. ) : onRetryReplies ? ( diff --git a/src/components/CommentDetail.test.tsx b/src/components/CommentDetail.test.tsx index 287e07c..3f99c16 100644 --- a/src/components/CommentDetail.test.tsx +++ b/src/components/CommentDetail.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, afterEach, vi } from 'vitest'; +import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'; import { screen, waitFor, act } from '@testing-library/react'; import { http, HttpResponse } from 'msw'; import { render } from '../test/test-utils'; @@ -6,6 +6,7 @@ import { Routes, Route } from 'react-router'; import { CommentDetail } from './CommentDetail'; import { server } from '../mocks/server'; import { ALGOLIA_API } from '../config/api'; +import { __resetFetchCachesForTests } from '../api/hn'; function renderCommentDetail(commentId: number | string, initialData?: { author: string; text: string; createdAt: number }) { return render( @@ -17,6 +18,10 @@ function renderCommentDetail(commentId: number | string, initialData?: { author: } describe('CommentDetail', () => { + beforeEach(() => { + __resetFetchCachesForTests(); + }); + // Content rendering (author, text, parent link, title link, replies) is tested // in FullScreenComment.test.tsx. These tests focus on CommentDetail-specific behavior: // routing integration, progressive rendering, skeleton, and document title. diff --git a/src/components/CommentDetail.tsx b/src/components/CommentDetail.tsx index 32ee6e3..85d1b17 100644 --- a/src/components/CommentDetail.tsx +++ b/src/components/CommentDetail.tsx @@ -42,7 +42,7 @@ export function CommentDetailSkeleton() { } export function CommentDetail({ commentId, initialData }: CommentDetailProps) { - const { comment, replies, itemId, itemTitle, itemTitleLoading, itemAuthor, loading, error, retry } = useCommentDetail(commentId, initialData); + const { comment, replies, moreRepliesLoading, itemId, itemTitle, itemTitleLoading, itemAuthor, loading, error, retry } = useCommentDetail(commentId, initialData); const navigate = useNavigate(); const location = useLocation(); const locationState = location.state as LocationState | null; @@ -104,6 +104,7 @@ export function CommentDetail({ commentId, initialData }: CommentDetailProps) { itemTitle={itemTitle} itemTitleLoading={itemTitleLoading} loading={loading || (!!error && isRetrying)} + moreRepliesLoading={moreRepliesLoading} onRetryReplies={error && !isRetrying ? retryNow : undefined} articleClassName="mb-6" storyAuthor={itemAuthor ?? ''} diff --git a/src/components/FullScreenComment.test.tsx b/src/components/FullScreenComment.test.tsx index 99166f2..51fa5f7 100644 --- a/src/components/FullScreenComment.test.tsx +++ b/src/components/FullScreenComment.test.tsx @@ -6,6 +6,7 @@ import { http, HttpResponse } from 'msw'; import { server } from '../mocks/server'; import { ALGOLIA_API } from '../config/api'; import { hnSdk } from '../api/hnSdk'; +import { __resetFetchCachesForTests } from '../api/hn'; import type { FirebaseItem } from '../types'; const mockItem: FirebaseItem = { @@ -22,6 +23,7 @@ const mockItem: FirebaseItem = { describe('FullScreenComment', () => { beforeEach(() => { + __resetFetchCachesForTests(); vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { if (Number(id) === 12345) return mockItem; return null; @@ -194,4 +196,46 @@ describe('FullScreenComment', () => { expect(screen.getByText('No replies yet.')).toBeInTheDocument(); }); }); + + it('keeps the replies skeleton, not "No replies yet.", until a flagged only reply loads', async () => { + const now = Math.floor(Date.now() / 1000); + const items: Record = { + 12345: mockItem, + 6667: { id: 6667, type: 'comment', by: 'asker', text: 'Only a flagged reply.', parent: 12345, kids: [6668], time: now - 600 }, + 6668: { id: 6668, type: 'comment', by: 'troll', text: 'Killed text', dead: true, parent: 6667, kids: [6669], time: now - 500 }, + }; + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => items[Number(id)] ?? null); + let serve!: () => void; + const served = new Promise(resolve => { serve = resolve; }); + server.use( + http.get(`${ALGOLIA_API}/items/:id`, () => HttpResponse.json({ + id: 6667, type: 'comment', author: 'asker', text: 'Only a flagged reply.', created_at_i: now - 600, + parent_id: 12345, story_id: 12345, children: [], + })), + http.get(`${ALGOLIA_API}/search`, async ({ request }) => { + if (new URL(request.url).searchParams.get('tags') !== 'comment,story_12345') return; + await served; + return HttpResponse.json({ + hits: [ + { objectID: '6667', author: 'asker', comment_text: 'Only a flagged reply.', created_at_i: now - 600, parent_id: 12345 }, + { objectID: '6669', author: 'replier', comment_text: 'Reply to a flagged comment', created_at_i: now - 400, parent_id: 6668 }, + ], + nbHits: 2, + nbPages: 1, + }); + }), + ); + + render(); + + const replies = (await screen.findByText('asker')).closest('article')!.nextElementSibling!; + expect(replies.querySelector('.animate-pulse')).not.toBeNull(); + expect(screen.queryByText('No replies yet.')).not.toBeInTheDocument(); + + serve(); + expect(await screen.findByText('[flagged]')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: '1 reply' })).toBeInTheDocument(); + expect(replies.querySelector('.animate-pulse')).toBeNull(); + expect(screen.queryByText('No replies yet.')).not.toBeInTheDocument(); + }); }); diff --git a/src/components/FullScreenComment.tsx b/src/components/FullScreenComment.tsx index 5145b88..ef26331 100644 --- a/src/components/FullScreenComment.tsx +++ b/src/components/FullScreenComment.tsx @@ -45,7 +45,7 @@ interface FullScreenCommentProps { } export function FullScreenComment({ commentId, onAuthorLoaded }: FullScreenCommentProps) { - const { comment, replies, itemId, itemTitle, itemTitleLoading, itemAuthor, loading, error, retry } = useCommentDetail(commentId); + const { comment, replies, moreRepliesLoading, itemId, itemTitle, itemTitleLoading, itemAuthor, loading, error, retry } = useCommentDetail(commentId); const { isOnline } = useNetworkStatus(); const { isRetrying } = useAutoRetry({ @@ -95,6 +95,7 @@ export function FullScreenComment({ commentId, onAuthorLoaded }: FullScreenComme itemTitle={itemTitle} itemTitleLoading={itemTitleLoading} loading={loading} + moreRepliesLoading={moreRepliesLoading} storyAuthor={itemAuthor ?? ''} /> )} diff --git a/src/components/SwipeCommentViewer.test.tsx b/src/components/SwipeCommentViewer.test.tsx index fede065..12d9b9c 100644 --- a/src/components/SwipeCommentViewer.test.tsx +++ b/src/components/SwipeCommentViewer.test.tsx @@ -5,6 +5,7 @@ import { SwipeCommentViewer } from './SwipeCommentViewer'; import { http, HttpResponse } from 'msw'; import { server } from '../mocks/server'; import { hnSdk } from '../api/hnSdk'; +import { __resetFetchCachesForTests } from '../api/hn'; import { ALGOLIA_API } from '../config/api'; import type { FirebaseItem } from '../types'; @@ -27,6 +28,7 @@ const defaultItems: Record = { describe('SwipeCommentViewer', () => { beforeEach(() => { + __resetFetchCachesForTests(); vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => defaultItems[Number(id)] ?? null); }); diff --git a/src/hooks/useCommentDetail.test.ts b/src/hooks/useCommentDetail.test.ts index 8fd89a7..4f8cc55 100644 --- a/src/hooks/useCommentDetail.test.ts +++ b/src/hooks/useCommentDetail.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, afterEach, vi, beforeEach } from 'vitest'; import { renderHook, waitFor } from '@testing-library/react'; import { http, HttpResponse } from 'msw'; import { useCommentDetail } from './useCommentDetail'; +import { __resetFetchCachesForTests } from '../api/hn'; import { hnSdk } from '../api/hnSdk'; import { server } from '../mocks/server'; import { ALGOLIA_API } from '../config/api'; @@ -20,6 +21,7 @@ const mockStoryItem: FirebaseItem = { describe('useCommentDetail', () => { beforeEach(() => { + __resetFetchCachesForTests(); vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { if (Number(id) === 12345) return mockStoryItem; return null; @@ -154,6 +156,113 @@ describe('useCommentDetail', () => { }); }); + describe('a flagged reply, which Algolia leaves out of the item tree', () => { + const now = Math.floor(Date.now() / 1000); + const flaggedReply: FirebaseItem = { + id: 2002, type: 'comment', by: 'eve', text: 'Killed text', dead: true, time: now - 800, parent: 1001, kids: [3001], + }; + + function mockStoryComments(response: () => Response | Promise, firebaseItems: FirebaseItem[] = [flaggedReply]) { + server.use( + http.get(`${ALGOLIA_API}/search`, ({ request }) => + new URL(request.url).searchParams.get('tags') === 'comment,story_12345' ? response() : HttpResponse.json({ hits: [], nbHits: 0, nbPages: 0 })), + ); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345) return mockStoryItem; + return firebaseItems.find(item => item.id === Number(id)) ?? null; + }); + } + + it('adds it with its replies once the story comments load', async () => { + mockStoryComments(() => HttpResponse.json({ + hits: [ + { objectID: '1001', author: 'patio11', comment_text: 'Root', created_at_i: now - 1800, parent_id: 12345 }, + { objectID: '2001', author: 'tptacek', comment_text: 'Live reply', created_at_i: now - 900, parent_id: 1001 }, + { objectID: '3001', author: 'mallory', comment_text: 'Reply to a flagged comment', created_at_i: now - 700, parent_id: 2002 }, + ], + nbHits: 3, + nbPages: 1, + })); + + const { result } = renderHook(() => useCommentDetail(1001)); + + await waitFor(() => { + expect(result.current.replies.map(c => c.id)).toEqual([2001, 2002]); + }); + expect(result.current.replies[1]).toMatchObject({ author: 'eve', text: '[flagged]' }); + expect(result.current.replies[1].children.map(c => c.id)).toEqual([3001]); + expect(result.current.error).toBeNull(); + }); + + it("keeps Algolia's replies when the story comments fail to load", async () => { + let served = false; + mockStoryComments(() => { + served = true; + return new HttpResponse(null, { status: 503 }); + }); + + const { result } = renderHook(() => useCommentDetail(1001)); + + await waitFor(() => { + expect(served).toBe(true); + expect(result.current.moreRepliesLoading).toBe(false); + }); + expect(result.current.replies.map(c => c.id)).toEqual([2001]); + expect(result.current.error).toBeNull(); + }); + + it("waits for them when they're a comment's only replies", async () => { + let serve!: () => void; + const served = new Promise(resolve => { serve = resolve; }); + mockStoryComments(async () => { + await served; + return HttpResponse.json({ + hits: [ + { objectID: '1002', author: 'jgrahamc', comment_text: 'Root', created_at_i: now - 1200, parent_id: 12345 }, + { objectID: '3001', author: 'mallory', comment_text: 'Reply to a flagged comment', created_at_i: now - 700, parent_id: 2002 }, + ], + nbHits: 2, + nbPages: 1, + }); + }, [ + { id: 1002, type: 'comment', by: 'jgrahamc', text: 'Root', time: now - 1200, parent: 12345, kids: [2002] }, + { ...flaggedReply, parent: 1002 }, + ]); + + const { result } = renderHook(() => useCommentDetail(1002)); + + await waitFor(() => { + expect(result.current.loading).toBe(false); + }); + expect(result.current.replies).toEqual([]); + expect(result.current.moreRepliesLoading).toBe(true); + + serve(); + await waitFor(() => { + expect(result.current.moreRepliesLoading).toBe(false); + }); + expect(result.current.replies.map(c => c.id)).toEqual([2002]); + expect(result.current.replies[0].children.map(c => c.id)).toEqual([3001]); + }); + + it('settles a comment with no replies without reading the story', async () => { + let served = false; + mockStoryComments(() => { + served = true; + return HttpResponse.json({ hits: [], nbHits: 0, nbPages: 0 }); + }, [{ id: 1003, type: 'comment', by: 'dang', text: 'Root', time: now - 600, parent: 12345 }]); + + const { result } = renderHook(() => useCommentDetail(1003)); + + await waitFor(() => { + expect(result.current.loading).toBe(false); + expect(result.current.moreRepliesLoading).toBe(false); + }); + expect(result.current.replies).toEqual([]); + expect(served).toBe(false); + }); + }); + it('accepts string commentId', async () => { const { result } = renderHook(() => useCommentDetail('1001')); diff --git a/src/hooks/useCommentDetail.ts b/src/hooks/useCommentDetail.ts index ea80a6c..77e8564 100644 --- a/src/hooks/useCommentDetail.ts +++ b/src/hooks/useCommentDetail.ts @@ -1,7 +1,11 @@ import { useState, useEffect, useCallback, useRef } from 'react'; -import { fetchCommentItem, fetchFirebaseItem, normalizeAlgoliaItemChildren } from '../api/hn'; +import { fetchCommentItem, fetchCommentReplies, fetchFirebaseItem, normalizeAlgoliaItemChildren } from '../api/hn'; import type { Comment } from '../types'; +function countComments(comments: Comment[]): number { + return comments.reduce((count, comment) => count + 1 + countComments(comment.children), 0); +} + interface CommentData { id: number; author: string; @@ -13,6 +17,11 @@ interface CommentData { interface UseCommentDetailResult { comment: CommentData | null; replies: Comment[]; + /** + * True while flagged and deleted replies, which Algolia's item tree + * leaves out, are being looked up. `replies` can still grow until then. + */ + moreRepliesLoading: boolean; itemId: number | null; itemTitle: string | null; /** True while the parent story's title and author are being fetched. */ @@ -46,6 +55,7 @@ export function useCommentDetail( : null, ); const [replies, setReplies] = useState([]); + const [moreRepliesLoading, setMoreRepliesLoading] = useState(false); const [itemId, setItemId] = useState(null); const [itemTitle, setItemTitle] = useState(null); const [itemTitleLoading, setItemTitleLoading] = useState(false); @@ -57,6 +67,7 @@ export function useCommentDetail( const load = useCallback(async (signal: AbortSignal) => { setError(null); setLoading(true); + setMoreRepliesLoading(false); try { const item = await fetchCommentItem(commentId, signal); @@ -72,8 +83,25 @@ export function useCommentDetail( setItemId(item.story_id ?? null); setReplies(normalizeAlgoliaItemChildren(item.children ?? [])); setItemTitleLoading(!!item.story_id); + setMoreRepliesLoading(!!item.story_id); setLoading(false); + // Algolia's item tree leaves out flagged and deleted replies along with + // the replies under them. Those fill in once the story's comments are read. + if (item.story_id) { + void fetchCommentReplies(item, signal).then( + all => { + if (signal.aborted) return; + setReplies(shown => (countComments(all) > countComments(shown) ? all : shown)); + setMoreRepliesLoading(false); + }, + () => { + // Algolia's replies stay. + if (!signal.aborted) setMoreRepliesLoading(false); + }, + ); + } + // Fetch parent title + author in background (non-blocking). // The author drives OP detection; landing ~100-300ms after the // comment renders means the badge pops in late, which is the @@ -118,5 +146,5 @@ export function useCommentDetail( }; }, [load]); - return { comment, replies, itemId, itemTitle, itemTitleLoading, itemAuthor, loading, error, retry }; + return { comment, replies, moreRepliesLoading, itemId, itemTitle, itemTitleLoading, itemAuthor, loading, error, retry }; } From c4f09249ac1d1670e3aaa2600ac7a83568a6b117 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:06:31 +0100 Subject: [PATCH 2/3] fix: keep the phone's comment viewer on the comment a link or Back leads to In the swipe comment viewer, tapping "parent" pushed the parent's URL, then about 16ms later replaced it with the reply's URL, then replaced it with the parent's again once the parent's siblings loaded, around 600ms later. A reload or share in that window used the reply's URL. Back from the parent replaced the reply's history entry with the parent's URL, and could land on one of the reply's siblings instead of the reply. The URL-sync effect ran in the same pass as the effect that handles an outside navigation, while its state still held the previous comment's siblings. It now also checks the scroll-init ref, which the navigation effect resets before it runs. --- src/components/SwipeCommentViewer.test.tsx | 98 +++++++++++++++++++++- src/components/SwipeCommentViewer.tsx | 5 +- 2 files changed, 101 insertions(+), 2 deletions(-) diff --git a/src/components/SwipeCommentViewer.test.tsx b/src/components/SwipeCommentViewer.test.tsx index 12d9b9c..3734f8c 100644 --- a/src/components/SwipeCommentViewer.test.tsx +++ b/src/components/SwipeCommentViewer.test.tsx @@ -1,5 +1,7 @@ import { describe, it, expect, afterEach, vi, beforeEach } from 'vitest'; -import { screen, waitFor } from '@testing-library/react'; +import { useEffect } from 'react'; +import { Route, Routes, useLocation, useNavigate, useParams } from 'react-router'; +import { fireEvent, screen, waitFor } from '@testing-library/react'; import { render } from '../test/test-utils'; import { SwipeCommentViewer } from './SwipeCommentViewer'; import { http, HttpResponse } from 'msw'; @@ -235,6 +237,100 @@ describe('SwipeCommentViewer', () => { expect(panels[6].querySelector('.animate-pulse')).not.toBeNull(); }); + // Renders the viewer on its route, with a Back button, and returns every + // pathname the route lands on. + function renderViewerRoute(pathnames: string[]) { + const paths: string[] = []; + function PathLog() { + const { pathname } = useLocation(); + useEffect(() => { + paths.push(pathname); + }, [pathname]); + return null; + } + function BackButton() { + const navigate = useNavigate(); + return ; + } + function ViewerRoute() { + return ; + } + + render( + <> + + + + } /> + + , + { initialEntries: pathnames.map(pathname => ({ pathname, state: { isComment: true } })) }, + ); + return paths; + } + + const activePanelId = () => document.querySelector('.swipe-snap-panel.active')?.getAttribute('data-item-id'); + + it('stays on the parent after its "parent" link, without going back to the reply', async () => { + const reply = { id: 2001, by: 'tptacek', text: 'Agreed.', time: Math.floor(Date.now() / 1000) - 900, parent: 1001, type: 'comment' } satisfies FirebaseItem; + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => (Number(id) === 2001 ? reply : defaultItems[Number(id)] ?? null)); + server.use( + http.get(`${ALGOLIA_API}/items/2001`, () => HttpResponse.json({ + id: 2001, type: 'comment', author: 'tptacek', text: 'Agreed.', created_at_i: reply.time, + parent_id: 1001, story_id: 12345, children: [], + })), + ); + + const paths = renderViewerRoute(['/item/2001']); + + fireEvent.click(await screen.findByRole('link', { name: 'parent' })); + + // 1001's siblings: [1001, 1002, 1003, 1004]. + await waitFor(() => { + expect(screen.getAllByTestId('swipe-panel')).toHaveLength(4); + }); + await waitFor(() => { + expect(screen.getByText('patio11')).toBeInTheDocument(); + }); + expect(paths).toEqual(['/item/2001', '/item/1001']); + }); + + it('lands on the reply after Back from its parent, without rewriting history', async () => { + const time = Math.floor(Date.now() / 1000) - 200; + const replyIds = [3101, 3102, 3103]; + const items: Record = { + ...defaultItems, + 1003: { ...defaultItems[1003], kids: replyIds }, + ...Object.fromEntries(replyIds.map(id => [id, { id, by: `user${id}`, text: 'Reply.', time, parent: 1003, type: 'comment' }])), + }; + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => items[Number(id)] ?? null); + server.use( + http.get(`${ALGOLIA_API}/items/:id`, ({ params }) => { + const id = Number(params.id); + if (!replyIds.includes(id)) return; + return HttpResponse.json({ + id, type: 'comment', author: `user${id}`, text: 'Reply.', created_at_i: time, + parent_id: 1003, story_id: 12345, children: [], + }); + }), + ); + + // On 1003, third of [1001, 1002, 1003, 1004], with its first reply behind it. + const paths = renderViewerRoute(['/item/3101', '/item/1003']); + await waitFor(() => { + expect(screen.getAllByTestId('swipe-panel')).toHaveLength(4); + expect(activePanelId()).toBe('1003'); + }); + + fireEvent.click(screen.getByRole('button', { name: 'Back' })); + + await waitFor(() => { + expect(screen.getAllByTestId('swipe-panel')).toHaveLength(3); + expect(activePanelId()).toBe('3101'); + }); + expect(paths).toEqual(['/item/1003', '/item/3101']); + }); + it('sets data-item-id on each panel', async () => { render(, { initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }], diff --git a/src/components/SwipeCommentViewer.tsx b/src/components/SwipeCommentViewer.tsx index 7064825..9339faa 100644 --- a/src/components/SwipeCommentViewer.tsx +++ b/src/components/SwipeCommentViewer.tsx @@ -87,8 +87,11 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps // URL update on swipe — only after scroll position is initialized. // Uses scrollInitialized state (not ref) so it's batched with setCurrentIndex // and both take effect in the same render — preventing a stale currentIndex=0 navigation. + // The ref check covers the render after an external navigation: the effect + // above has just reset the ref, but this render's state still holds the old + // siblings, and navigating to one of them would undo that navigation. useEffect(() => { - if (!scrollInitialized) return; + if (!scrollInitialized || !hasInitializedScrollRef.current) return; if (siblingIds.length === 0) return; const commentId = siblingIds[currentIndex]; if (!commentId) return; From e48954202f321b29f3f16bc8f7dedaf79781af35 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:06:31 +0100 Subject: [PATCH 3/3] fix: describe the empty domain page instead of a missing item /from/ with no domain showed "No domain specified" over the default not-found text, "This item doesn't exist or may have been removed." --- e2e/domain-filter.spec.ts | 2 ++ src/pages/DomainStories.tsx | 1 + 2 files changed, 3 insertions(+) diff --git a/e2e/domain-filter.spec.ts b/e2e/domain-filter.spec.ts index 4ceedb1..6fb7108 100644 --- a/e2e/domain-filter.spec.ts +++ b/e2e/domain-filter.spec.ts @@ -207,6 +207,8 @@ test.describe('Domain Filter - Empty domain', () => { // Should show error message await expect(page.getByText('No domain specified')).toBeVisible(); + await expect(page.getByText("Pick a story's site to see more submissions from it.")).toBeVisible(); + await expect(page.getByText(/This item doesn't exist/)).toHaveCount(0); await setOfflineAndWaitForBar(page, context); diff --git a/src/pages/DomainStories.tsx b/src/pages/DomainStories.tsx index 0cb2191..ae83ef6 100644 --- a/src/pages/DomainStories.tsx +++ b/src/pages/DomainStories.tsx @@ -31,6 +31,7 @@ export function DomainStories() {