From c4a9171e5ec938738b536c64da9083c096e5d630 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:48:20 +0100 Subject: [PATCH 1/6] fix: keep replies to flagged and deleted comments in the thread Algolia's comment search leaves out flagged and deleted comments but returns their replies, and buildCommentTree dropped any reply whose parent wasn't in the results, on the premise that HN hides the subtree under a dead comment. It doesn't: HN shows the flagged comment as a [flagged] row and keeps its replies, collapsed. Story 50299427 had 11 comments and showed 6; 5 of the top 14 stories were missing replies, including moderator replies. The tree now reads each missing parent from Firebase, and its parent when that is missing too, and puts it in the thread. A flagged comment shows its author, time and [flagged], as on HN. Firebase still has the original text of older killed comments (2018 and before in the ones checked), so that text is replaced. A deleted one shows as a [deleted] row through a new `deleted` flag on Comment. Replies whose parent Firebase doesn't have either are still dropped. The batched Firebase read in fetchKidsOrdering moves to a shared readItemsBatched, and a placeholder's kids order comes with it, so its replies keep HN's order without a second read. --- src/api/hn.test.ts | 102 +++++++++++++++++++-------- src/api/hn.ts | 119 ++++++++++++++++++++++---------- src/components/Comment.test.tsx | 18 +++++ src/components/Comment.tsx | 62 +++++++++-------- src/types.ts | 2 + 5 files changed, 210 insertions(+), 93 deletions(-) diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts index 820595e..caddf71 100644 --- a/src/api/hn.test.ts +++ b/src/api/hn.test.ts @@ -1036,10 +1036,10 @@ describe('hn API utilities', () => { }); describe('fetchCommentsForItem', () => { - it('drops orphaned comments whose parent is dead (not in Algolia)', async () => { + describe('replies to a comment search leaves out', () => { const itemId = 9000; - // Item has 3 root-level kids: 101 (alive), 102 (dead), 103 (alive) + // Item has 3 root-level kids: 101 (alive), 102 (flagged or deleted), 103 (alive) const firebaseItem: FirebaseItem = { id: itemId, title: 'Test Story', @@ -1051,42 +1051,90 @@ describe('hn API utilities', () => { type: 'story', }; - // Comment 102 is dead — Algolia won't return it. - // Comments 201, 202 are children of the dead comment 102. + // Algolia doesn't return 102, but does return its replies 201 and 202. const algoliaHits = [ { objectID: '101', author: 'alice', comment_text: 'Alive root', created_at_i: 1700000100, parent_id: itemId }, { objectID: '103', author: 'bob', comment_text: 'Also alive root', created_at_i: 1700000200, parent_id: itemId }, - { objectID: '201', author: 'charlie', comment_text: 'Reply to dead parent', created_at_i: 1700000300, parent_id: 102 }, - { objectID: '202', author: 'dave', comment_text: 'Another reply to dead parent', created_at_i: 1700000400, parent_id: 102 }, + { objectID: '201', author: 'charlie', comment_text: 'Reply to removed parent', created_at_i: 1700000300, parent_id: 102 }, + { objectID: '202', author: 'dave', comment_text: 'Another reply to removed parent', created_at_i: 1700000400, parent_id: 102 }, ]; - // Mock hnSdk.readItem for the initial item fetch and kids ordering - vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { - if (Number(id) === itemId) return firebaseItem; - return null; + function mockThread(firebase: FirebaseItem[], hits: typeof algoliaHits = algoliaHits) { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === itemId) return firebaseItem; + return firebase.find(item => item.id === Number(id)) ?? null; + }); + vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ hits, nbHits: hits.length })); + } + + afterEach(() => { + vi.restoreAllMocks(); }); - // Mock fetch for Algolia search - const mockFetch = vi.spyOn(globalThis, 'fetch').mockResolvedValue( - new Response(JSON.stringify({ hits: algoliaHits, nbHits: algoliaHits.length }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }), - ); + it('keeps replies to a flagged comment under its [flagged] row', async () => { + mockThread([ + { id: 102, type: 'comment', by: 'eve', text: '[flagged]', dead: true, time: 1700000150, parent: itemId, kids: [202, 201] }, + ]); - const comments = await fetchCommentsForItem(itemId); + const comments = await fetchCommentsForItem(itemId); + + expect(comments.map(c => c.id)).toEqual([101, 102, 103]); + expect(comments[1]).toMatchObject({ author: 'eve', text: '[flagged]', createdAt: 1700000150 * 1000 }); + expect(comments[1].deleted).toBeUndefined(); + // In the flagged comment's own kids order, not creation order. + expect(comments[1].children.map(c => c.id)).toEqual([202, 201]); + }); + + it('shows [flagged] for a killed comment whose text Firebase still has', async () => { + mockThread([ + { id: 102, type: 'comment', by: 'eve', text: 'Praise the iLord.', dead: true, time: 1700000150, parent: itemId, kids: [201, 202] }, + ]); - // Only the 2 alive root comments should appear; orphans 201/202 are dropped - expect(comments).toHaveLength(2); - expect(comments[0].id).toBe(101); - expect(comments[1].id).toBe(103); + const comments = await fetchCommentsForItem(itemId); + + expect(comments[1]).toMatchObject({ id: 102, author: 'eve', text: '[flagged]' }); + }); - // Orphaned comments should NOT be promoted to root - const allIds = comments.map(c => c.id); - expect(allIds).not.toContain(201); - expect(allIds).not.toContain(202); + it('keeps replies to a deleted comment under a deleted row', async () => { + mockThread([ + { id: 102, type: 'comment', deleted: true, time: 1700000150, parent: itemId, kids: [201, 202] }, + ]); - mockFetch.mockRestore(); + const comments = await fetchCommentsForItem(itemId); + + expect(comments.map(c => c.id)).toEqual([101, 102, 103]); + expect(comments[1]).toMatchObject({ deleted: true, author: '', text: '' }); + expect(comments[1].children.map(c => c.id)).toEqual([201, 202]); + }); + + it('follows missing parents up to one search has', async () => { + // 301 replies to flagged 201, which replies to deleted 102. + mockThread( + [ + { id: 201, type: 'comment', by: 'carol', text: '[flagged]', dead: true, time: 1700000300, parent: 102, kids: [301] }, + { id: 102, type: 'comment', deleted: true, time: 1700000150, parent: itemId, kids: [201] }, + ], + [ + algoliaHits[0], + { objectID: '301', author: 'frank', comment_text: 'Deep reply', created_at_i: 1700000500, parent_id: 201 }, + ], + ); + + const comments = await fetchCommentsForItem(itemId); + + expect(comments.map(c => c.id)).toEqual([101, 102]); + expect(comments[1].children.map(c => c.id)).toEqual([201]); + expect(comments[1].children[0].children.map(c => c.id)).toEqual([301]); + }); + + it('drops the replies when Firebase does not have their parent either', async () => { + mockThread([]); + + const comments = await fetchCommentsForItem(itemId); + + expect(comments.map(c => c.id)).toEqual([101, 103]); + expect(comments.flatMap(c => c.children)).toEqual([]); + }); }); describe('a thread bigger than search returns', () => { diff --git a/src/api/hn.ts b/src/api/hn.ts index 6d4dd9a..ae7416a 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -400,8 +400,8 @@ async function fetchAllCommentsAlgolia(itemId: number, signal?: AbortSignal): Pr function flattenAlgoliaItemChildren(children: AlgoliaItemChild[], into: AlgoliaComment[] = []): AlgoliaComment[] { for (const child of children) { - // Deleted comments have no author; their replies are left as orphans, - // which buildCommentTree drops just as it does for search results. + // The item tree leaves out flagged and deleted comments along with their + // replies, so those replies only come from search. if (child.author) { into.push({ objectID: String(child.id), @@ -416,13 +416,54 @@ function flattenAlgoliaItemChildren(children: AlgoliaItemChild[], into: AlgoliaC return into; } +type ThreadComment = AlgoliaComment & { deleted?: boolean }; + +// Search and the item tree leave out flagged and deleted comments but keep +// their replies. HN shows those replies under a [flagged] or [deleted] row, +// so the missing parents (and theirs, when also missing) come from Firebase. +async function fetchMissingParents(comments: AlgoliaComment[], itemId: number, signal?: AbortSignal): Promise { + const MAX_DEPTH = 10; + const known = new Set(comments.map(c => Number(c.objectID))); + const found: FirebaseItem[] = []; + let missing = [...new Set(comments.map(c => c.parent_id))].filter(id => id !== itemId && !known.has(id)); + + for (let depth = 0; depth < MAX_DEPTH && missing.length > 0 && !signal?.aborted; depth++) { + const next = new Set(); + for (const item of await readItemsBatched(missing, signal)) { + if (item.parent == null) continue; + known.add(item.id); + found.push(item); + if (item.parent !== itemId) next.add(item.parent); + } + missing = [...next].filter(id => !known.has(id)); + } + + return found; +} + +// Firebase still has the text of older killed comments. HN shows [flagged]. +function firebaseCommentText(item: FirebaseItem): string | undefined { + return item.dead && item.text ? '[flagged]' : item.text; +} + +function threadCommentFromFirebase(item: FirebaseItem): ThreadComment { + return { + objectID: String(item.id), + author: item.by ?? '', + comment_text: firebaseCommentText(item) ?? '', + created_at_i: item.time ?? 0, + parent_id: item.parent ?? 0, + deleted: item.deleted === true || !item.by, + }; +} + // `kidsOrder` (from Firebase kids arrays) maintains HN's ranking order; falls // back to creation time when not available. -function buildCommentTree(comments: AlgoliaComment[], itemId: number, kidsOrder = new Map()): Comment[] { +function buildCommentTree(comments: ThreadComment[], itemId: number, kidsOrder = new Map()): Comment[] { const commentMap = new Map(); - comments.forEach((comment: AlgoliaComment) => { - if (comment.author) { // Skip deleted comments (no author) + comments.forEach((comment: ThreadComment) => { + if (comment.author || comment.deleted) { commentMap.set(parseInt(comment.objectID, 10), { id: parseInt(comment.objectID, 10), author: comment.author, @@ -430,6 +471,7 @@ function buildCommentTree(comments: AlgoliaComment[], itemId: number, kidsOrder createdAt: comment.created_at_i * 1000, parentId: comment.parent_id, children: [], + ...(comment.deleted && { deleted: true }), }); } }); @@ -440,13 +482,8 @@ function buildCommentTree(comments: AlgoliaComment[], itemId: number, kidsOrder if (comment.parentId === itemId) { rootComments.push(comment); } else { - const parent = commentMap.get(comment.parentId); - if (parent) { - parent.children.push(comment); - } - // Parent not in map → parent is dead/deleted. HN hides the entire - // subtree under a dead comment, so we drop the orphan (its children - // still attach to it in the map but the subtree is unreachable). + // Orphans whose parent Firebase couldn't supply either are dropped. + commentMap.get(comment.parentId)?.children.push(comment); } }); @@ -481,7 +518,7 @@ function buildCommentTree(comments: AlgoliaComment[], itemId: number, kidsOrder } async function buildOrderedCommentTree( - comments: AlgoliaComment[], + searchComments: AlgoliaComment[], itemId: number, itemKids: number[] | undefined, signal?: AbortSignal, @@ -492,6 +529,12 @@ async function buildOrderedCommentTree( kidsOrder.set(itemId, itemKids); } + const missingParents = await fetchMissingParents(searchComments, itemId, signal); + missingParents.forEach(parent => { + if (parent.kids) kidsOrder.set(parent.id, parent.kids); + }); + const comments: ThreadComment[] = [...searchComments, ...missingParents.map(threadCommentFromFirebase)]; + const childrenCount = new Map(); comments.forEach((c: AlgoliaComment) => { const count = childrenCount.get(c.parent_id) ?? 0; @@ -538,7 +581,7 @@ async function buildOrderedCommentTree( .map(([parentId]) => parentId); } - const nestedKidsOrder = await fetchKidsOrdering(parentsNeedingOrder, signal); + const nestedKidsOrder = await fetchKidsOrdering(parentsNeedingOrder.filter(id => !kidsOrder.has(id)), signal); nestedKidsOrder.forEach((kids, parentId) => kidsOrder.set(parentId, kids)); return buildCommentTree(comments, itemId, kidsOrder); @@ -551,38 +594,38 @@ export async function fetchItemOnly(id: number | string, signal?: AbortSignal): return normalizeFirebaseItem(item); } -// Required for HN's ranking order (not chronological). Batched to avoid -// overwhelming the API. -async function fetchKidsOrdering(commentIds: number[], signal?: AbortSignal): Promise> { +// Batched to avoid overwhelming the API. Items that fail or don't exist are +// left out. +async function readItemsBatched(ids: number[], signal?: AbortSignal): Promise { const BATCH_SIZE = 10; // Reduced from 20 to lower concurrent requests - const kidsOrder = new Map(); - - for (let i = 0; i < commentIds.length; i += BATCH_SIZE) { - if (signal?.aborted) return kidsOrder; - - const batch = commentIds.slice(i, i + BATCH_SIZE); - - const results = await Promise.all( - batch.map(async (id) => { + const items: FirebaseItem[] = []; + + for (let i = 0; i < ids.length; i += BATCH_SIZE) { + if (signal?.aborted) return items; + + const batch = await Promise.all( + ids.slice(i, i + BATCH_SIZE).map(async (id) => { try { - const item = await hnSdk.readItem(id); - if (item?.kids) { - return { id: item.id, kids: item.kids }; - } - return null; + return await hnSdk.readItem(id); } catch { return null; } }) ); - - results.forEach((result: { id: number; kids: number[] } | null) => { - if (result) { - kidsOrder.set(result.id, result.kids); - } - }); + for (const item of batch) { + if (item) items.push(item); + } + } + + return items; +} + +// Required for HN's ranking order (not chronological). +async function fetchKidsOrdering(commentIds: number[], signal?: AbortSignal): Promise> { + const kidsOrder = new Map(); + for (const item of await readItemsBatched(commentIds, signal)) { + if (item.kids) kidsOrder.set(item.id, item.kids); } - return kidsOrder; } diff --git a/src/components/Comment.test.tsx b/src/components/Comment.test.tsx index cfe28b3..3948037 100644 --- a/src/components/Comment.test.tsx +++ b/src/components/Comment.test.tsx @@ -117,6 +117,24 @@ describe('Comment', () => { }, ); + it('renders a deleted comment as a [deleted] row that keeps its replies', () => { + const deleted = createComment({ + id: 300, + author: '', + text: '', + deleted: true, + children: [createComment({ id: 301, author: 'replier', text: '

Still here

' })], + }); + render(); + + expect(screen.getByText('[deleted]')).toBeInTheDocument(); + expect(screen.queryByText('unknown')).not.toBeInTheDocument(); + expect(screen.queryByRole('link')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: /1 reply/ })); + expect(screen.getByText('Still here')).toBeInTheDocument(); + }); + // OP badge must be a SIBLING (not child) of the author span/link so // the link's accessible name stays exactly the handle. it('renders an OP badge when storyAuthor matches comment.author', () => { diff --git a/src/components/Comment.tsx b/src/components/Comment.tsx index ef50b01..c4348f0 100644 --- a/src/components/Comment.tsx +++ b/src/components/Comment.tsx @@ -57,38 +57,44 @@ export function Comment({ comment, storyAuthor = '', stageIdx }: CommentProps) { {/* Compact byline — lucide meta row is for the focal comment. */}
- {isOp ? ( - + {comment.deleted ? ( + [deleted] + ) : ( + <> + {isOp ? ( + + + {comment.author} + + + ) : isKnownAuthor(comment.author) ? ( + + {comment.author} + + ) : ( + + {comment.author || 'unknown'} + + )} + · + {/* Time IS the permalink (HN convention). `state.isComment: + true` lets MobileStoryRoute short-circuit straight + to SwipeCommentViewer without a resolver round-trip. */} - {comment.author} + - - ) : isKnownAuthor(comment.author) ? ( - - {comment.author} - - ) : ( - - {comment.author || 'unknown'} - + )} - · - {/* Time IS the permalink (HN convention). `state.isComment: - true` lets MobileStoryRoute short-circuit straight - to SwipeCommentViewer without a resolver round-trip. */} - - -
{hasChildren ? ( diff --git a/src/types.ts b/src/types.ts index 7728448..a82d3b5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -45,6 +45,8 @@ export interface Comment { createdAt: number; parentId: number; children: Comment[]; + /** A deleted comment kept as a [deleted] row because it has live replies. */ + deleted?: boolean; } export interface AlgoliaHit { From 50c514eea9b13ddef315ada8f204fa43d2aec298 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:49:26 +0100 Subject: [PATCH 2/6] fix: keep paging a domain feed when search only estimated its size A domain feed is a query search on the URL, and Algolia can stop counting a query early: for dev.to it reports nbHits 150 with exhaustiveNbHits false, returns 3 full pages of 50, and nothing past them. nextAlgoliaPage only started over from the oldest hit when nbHits went past the 1,000-hit cap, so /from/dev.to ended after 147 stories from 2021 while a search from the oldest one finds about 6,500 more. It now also starts over when the count is an estimate and the last page came back full. A short page still ends the feed. --- src/hooks/useDomainInfiniteStories.test.ts | 39 ++++++++++++++++++++++ src/types.ts | 2 ++ src/utils/algoliaPaging.ts | 11 +++--- 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/hooks/useDomainInfiniteStories.test.ts b/src/hooks/useDomainInfiniteStories.test.ts index e6edc6c..09c41bc 100644 --- a/src/hooks/useDomainInfiniteStories.test.ts +++ b/src/hooks/useDomainInfiniteStories.test.ts @@ -714,6 +714,45 @@ describe('useDomainInfiniteStories', () => { expect(result.current.stories.map((s) => s.id)).toEqual([1, 2, 3]); expect(result.current.hasMore).toBe(false); }); + + // dev.to: search reports nbHits 150 with exhaustiveNbHits false, has + // thousands more, and returns nothing past its third page of 50. + const hits = (from: number, count: number) => + Array.from({ length: count }, (_, i) => ({ ...body('example.com', [from + i]).hits[0], created_at_i: 10_000 - from - i })); + + it('loads past a full last page when nbHits is an estimate', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((input) => { + const filter = new URL(fetchInputToUrl(input)).searchParams.get('numericFilters'); + return Promise.resolve(Response.json(filter === null + ? { hits: hits(1, 50), nbHits: 50, nbPages: 1, page: 0, hitsPerPage: 50, exhaustiveNbHits: false } + : { hits: hits(50, 3), nbHits: 3, nbPages: 1, page: 0, hitsPerPage: 50, exhaustiveNbHits: false })); + }); + + const { result } = renderHook(() => useDomainInfiniteStories('example.com')); + await waitFor(() => expect(result.current.stories).toHaveLength(50)); + expect(result.current.hasMore).toBe(true); + + await act(async () => { + await result.current.loadMore(); + }); + + const nextUrl = new URL(fetchInputToUrl(fetchSpy.mock.calls[1]?.[0])); + expect(nextUrl.searchParams.get('numericFilters')).toBe(`created_at_i<=${10_000 - 50}`); + expect(result.current.stories.map((s) => s.id)).toEqual([...hits(1, 50), ...hits(51, 2)].map((h) => Number(h.objectID))); + // A short page is the end, estimate or not. + expect(result.current.hasMore).toBe(false); + }); + + it('stops at a full last page when nbHits is exact', async () => { + vi.spyOn(globalThis, 'fetch').mockResolvedValue( + Response.json({ hits: hits(1, 50), nbHits: 50, nbPages: 1, page: 0, hitsPerPage: 50, exhaustiveNbHits: true }), + ); + + const { result } = renderHook(() => useDomainInfiniteStories('example.com')); + await waitFor(() => expect(result.current.stories).toHaveLength(50)); + + expect(result.current.hasMore).toBe(false); + }); }); describe('reset', () => { diff --git a/src/types.ts b/src/types.ts index a82d3b5..be3a77a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -77,6 +77,8 @@ export interface AlgoliaSearchResponse { nbPages: number; page: number; hitsPerPage: number; + /** False when `nbHits` is an estimate, which a query search can return. */ + exhaustiveNbHits?: boolean; } export interface FirebaseItem { diff --git a/src/utils/algoliaPaging.ts b/src/utils/algoliaPaging.ts index 99c1511..7cfdf0b 100644 --- a/src/utils/algoliaPaging.ts +++ b/src/utils/algoliaPaging.ts @@ -12,9 +12,11 @@ export function algoliaPageParams({ page, before }: AlgoliaPageCursor): string { return `&page=${page}${filter}`; } -// Search returns at most 1,000 hits and caps nbPages to match. Results are -// newest first, so past the last page the next request starts over at page 0 -// from the oldest hit so far. That hit comes back once; callers already dedup. +// Search returns at most 1,000 hits and caps nbPages to match. A query search +// can also stop counting early and size nbPages from an estimate, so a full +// last page may not be the end either. Results are newest first, so past the +// last page the next request starts over at page 0 from the oldest hit so far. +// That hit comes back once; callers already dedup. export function nextAlgoliaPage( data: AlgoliaSearchResponse, hitsPerPage: number, @@ -24,7 +26,8 @@ export function nextAlgoliaPage( const oldest = data.hits[data.hits.length - 1]?.created_at_i; const isCapped = data.nbHits > data.nbPages * hitsPerPage; - if (isCapped && oldest !== undefined && oldest !== cursor.before) { + const mayHaveMore = data.exhaustiveNbHits === false && data.hits.length >= hitsPerPage; + if ((isCapped || mayHaveMore) && oldest !== undefined && oldest !== cursor.before) { return { page: 0, before: oldest }; } return null; From 8e2ce5fcb0ead45c91f3d0c4ac960c1d14d5d18a Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:51:48 +0100 Subject: [PATCH 3/6] fix: show flagged and deleted comments instead of a load error The comment swiper's panels come from parent.kids in Firebase, which lists flagged and deleted comments, and each panel loads from Algolia's /items, which 404s them. Swiping onto one showed "Failed to load comment" with a Retry that could never work. On the largest current thread, 35 of 243 top-level comments are flagged or deleted, and every story checked had some. A permalink to one failed the same way. fetchAlgoliaItem now throws NotFoundError on a 404, and the comment pages load through a new fetchCommentItem, which reads a comment Algolia doesn't have from Firebase and its live replies from Algolia. A flagged comment shows its author and [flagged] with its replies, as on HN, even when Firebase still has its original text. On a phone a deleted one shows the existing "Comment deleted" state; on desktop it shows [deleted] where the author goes, with its replies, instead of "unknown" over an empty body. Other Algolia errors still show the error and its Retry. The desktop page first shows the copy of the comment it already read from Firebase, and keeps it if its own request fails, so that copy shows [flagged] too. --- src/api/hn.test.ts | 2 + src/api/hn.ts | 34 ++++++++++++++- src/components/CommentArticle.test.tsx | 7 +++ src/components/CommentArticle.tsx | 7 ++- src/components/FullScreenComment.test.tsx | 52 +++++++++++++++++++++++ src/hooks/useCommentDetail.test.ts | 16 +++++++ src/hooks/useCommentDetail.ts | 4 +- src/pages/ItemDetail.test.tsx | 16 +++++++ 8 files changed, 133 insertions(+), 5 deletions(-) diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts index caddf71..74ad733 100644 --- a/src/api/hn.test.ts +++ b/src/api/hn.test.ts @@ -990,6 +990,8 @@ describe('hn API utilities', () => { it('throws on 404 for unknown items', async () => { await expect(fetchAlgoliaItem(999999999)) .rejects.toThrow(/404/); + await expect(fetchAlgoliaItem(999999999)) + .rejects.toBeInstanceOf(NotFoundError); }); }); diff --git a/src/api/hn.ts b/src/api/hn.ts index ae7416a..0ea39f8 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -65,7 +65,7 @@ function normalizeFirebaseItem(fbItem: FirebaseItem): Item { return { ...base, type: 'comment' as const, - text: fbItem.text ?? '', + text: firebaseCommentText(fbItem) ?? '', parent: fbItem.parent ?? 0, }; } @@ -690,11 +690,41 @@ export async function fetchItemWithComments(id: number | string, signal: AbortSi export async function fetchAlgoliaItem(id: number | string, signal?: AbortSignal): Promise { const response = await fetch(`${ALGOLIA_API}/items/${id}`, { signal }); if (!response.ok) { - throw new Error(`Failed to fetch item ${id}: ${response.status}`); + const message = `Failed to fetch item ${id}: ${response.status}`; + throw response.status === 404 ? new NotFoundError(message) : new Error(message); } return response.json() as Promise; } +/** + * A comment with its reply tree, in Algolia's item shape. Algolia 404s + * flagged and deleted comments (and ones it hasn't indexed yet), so those + * come from Firebase, with the replies Algolia has. + */ +export async function fetchCommentItem(id: number | string, signal?: AbortSignal): Promise { + try { + return await fetchAlgoliaItem(id, signal); + } catch (err) { + if (!(err instanceof NotFoundError)) throw err; + } + + const item = await fetchFirebaseItem(id, signal); + const replies = (await Promise.all( + (item.kids ?? []).map(kid => fetchAlgoliaItem(kid, signal).catch(() => null)), + )).filter(reply => reply !== null); + + return { + id: item.id, + type: item.type ?? 'comment', + author: item.by ?? null, + text: firebaseCommentText(item) ?? null, + created_at_i: item.time ?? 0, + parent_id: item.parent ?? null, + story_id: replies[0]?.story_id ?? null, + children: replies.map(reply => ({ ...reply, parent_id: 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 acf58b1..004ce2f 100644 --- a/src/components/CommentArticle.test.tsx +++ b/src/components/CommentArticle.test.tsx @@ -73,6 +73,13 @@ describe('CommentArticle', () => { expect(Number.isNaN(Date.parse(isoAttr))).toBe(false); }); + it('shows a deleted comment as [deleted], not as an unknown author', () => { + renderArticle({ comment: { ...mockComment, author: '', text: '' } }); + + expect(screen.getByText('[deleted]')).toBeInTheDocument(); + expect(screen.queryByText('unknown')).not.toBeInTheDocument(); + }); + it('renders sanitized comment HTML', () => { // sanitizeHtml + dangerouslySetInnerHTML:

must survive as a real // paragraph (not escaped text or an inert div). diff --git a/src/components/CommentArticle.tsx b/src/components/CommentArticle.tsx index 81b0ec6..179c76a 100644 --- a/src/components/CommentArticle.tsx +++ b/src/components/CommentArticle.tsx @@ -43,6 +43,7 @@ export function CommentArticle({ storyAuthor = '', }: CommentArticleProps) { const isOp = isKnownAuthor(storyAuthor) && comment.author === storyAuthor; + const isDeleted = !comment.author && !comment.text; const sanitizedText = useMemo( () => comment.text ? sanitizeHtml(comment.text) : '', [comment.text], @@ -53,7 +54,11 @@ export function CommentArticle({

{/* Meta row: author, time, parent, thread-title. Icons aria-hidden. */}
- + {isDeleted ? ( + [deleted] + ) : ( + + )} diff --git a/src/components/FullScreenComment.test.tsx b/src/components/FullScreenComment.test.tsx index a9c982d..99166f2 100644 --- a/src/components/FullScreenComment.test.tsx +++ b/src/components/FullScreenComment.test.tsx @@ -120,6 +120,58 @@ describe('FullScreenComment', () => { }); }); + describe('a comment Algolia 404s', () => { + const now = Math.floor(Date.now() / 1000); + + function mockMissingFromAlgolia(commentId: number, firebase: FirebaseItem, replies: object[] = []) { + server.use( + http.get(`${ALGOLIA_API}/items/:id`, ({ params }) => { + const reply = replies.find(r => (r as { id: number }).id === Number(params.id)); + return reply ? HttpResponse.json(reply) : HttpResponse.json({ status: 404 }, { status: 404 }); + }), + ); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345) return mockItem; + return Number(id) === commentId ? firebase : null; + }); + } + + it('shows a flagged comment from Firebase with its replies', async () => { + mockMissingFromAlgolia( + 7777, + { id: 7777, type: 'comment', by: 'flaggeduser', text: '[flagged]', dead: true, parent: 12345, kids: [7778], time: now - 600 }, + [{ id: 7778, type: 'comment', author: 'dang', text: 'Please don't.', created_at_i: now - 300, parent_id: 7777, story_id: 12345, children: [] }], + ); + + render(); + + expect(await screen.findByText('[flagged]')).toBeInTheDocument(); + expect(screen.getByText('flaggeduser')).toBeInTheDocument(); + expect(screen.getByText('dang')).toBeInTheDocument(); + expect(screen.getByText("Please don't.")).toBeInTheDocument(); + expect(await screen.findByRole('link', { name: 'Rust Is the Future of JavaScript Infrastructure' })).toHaveAttribute('href', '/item/12345'); + expect(screen.queryByText('Failed to load comment')).not.toBeInTheDocument(); + }); + + it('shows [flagged] for a killed comment whose text Firebase still has', async () => { + mockMissingFromAlgolia(7777, { id: 7777, type: 'comment', by: 'flaggeduser', text: 'Praise the iLord.', dead: true, parent: 12345, time: now - 600 }); + + render(); + + expect(await screen.findByText('[flagged]')).toBeInTheDocument(); + expect(screen.queryByText('Praise the iLord.')).not.toBeInTheDocument(); + }); + + it('shows a deleted comment as deleted', async () => { + mockMissingFromAlgolia(8888, { id: 8888, type: 'comment', deleted: true, parent: 12345, time: now - 600 }); + + render(); + + expect(await screen.findByText('Comment deleted')).toBeInTheDocument(); + expect(screen.queryByText('Failed to load comment')).not.toBeInTheDocument(); + }); + }); + it('shows "No replies yet" for comment with no children', async () => { server.use( http.get(`${ALGOLIA_API}/items/:id`, () => { diff --git a/src/hooks/useCommentDetail.test.ts b/src/hooks/useCommentDetail.test.ts index 5526ba9..8fd89a7 100644 --- a/src/hooks/useCommentDetail.test.ts +++ b/src/hooks/useCommentDetail.test.ts @@ -118,6 +118,22 @@ describe('useCommentDetail', () => { expect(result.current.comment).toBeNull(); }); + it('keeps an Algolia server error as an error without asking Firebase', async () => { + server.use( + http.get(`${ALGOLIA_API}/items/:id`, () => new HttpResponse(null, { status: 500 })), + ); + const readItem = vi.spyOn(hnSdk, 'readItem'); + + const { result } = renderHook(() => useCommentDetail(1001)); + + await waitFor(() => { + expect(result.current.loading).toBe(false); + }); + + expect(result.current.error).toMatch(/500/); + expect(readItem).not.toHaveBeenCalledWith(1001); + }); + it('degrades gracefully when item title fetch fails', async () => { // Only the SDK item fetch fails — Algolia (comment + replies) still succeeds. vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('SDK error')); diff --git a/src/hooks/useCommentDetail.ts b/src/hooks/useCommentDetail.ts index 5a32ea6..ea80a6c 100644 --- a/src/hooks/useCommentDetail.ts +++ b/src/hooks/useCommentDetail.ts @@ -1,5 +1,5 @@ import { useState, useEffect, useCallback, useRef } from 'react'; -import { fetchAlgoliaItem, fetchFirebaseItem, normalizeAlgoliaItemChildren } from '../api/hn'; +import { fetchCommentItem, fetchFirebaseItem, normalizeAlgoliaItemChildren } from '../api/hn'; import type { Comment } from '../types'; interface CommentData { @@ -59,7 +59,7 @@ export function useCommentDetail( setLoading(true); try { - const item = await fetchAlgoliaItem(commentId, signal); + const item = await fetchCommentItem(commentId, signal); if (signal.aborted) return; setComment({ diff --git a/src/pages/ItemDetail.test.tsx b/src/pages/ItemDetail.test.tsx index 44abb9e..8cbf075 100644 --- a/src/pages/ItemDetail.test.tsx +++ b/src/pages/ItemDetail.test.tsx @@ -216,5 +216,21 @@ describe('ItemDetail', () => { // CommentDetail (not ItemArticle). expect(screen.queryByText(/points/)).not.toBeInTheDocument(); }); + + it('shows [flagged] for a killed comment before its own request returns', async () => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => ( + Number(id) === 1001 + ? { id: 1001, by: 'patio11', text: 'Praise the iLord.', dead: true, time: Math.floor(Date.now() / 1000) - 1800, parent: 12345, type: 'comment' } + : defaultItem + )); + server.use( + http.get(`${ALGOLIA_API}/items/:id`, () => new Promise(() => { /* never resolves */ })), + ); + + renderItemDetail(1001); + + expect(await screen.findByText('[flagged]')).toBeInTheDocument(); + expect(screen.queryByText('Praise the iLord.')).not.toBeInTheDocument(); + }); }); }); From d9c6feb97d50d63784c9b9d6bd638d1295717033 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:55:20 +0100 Subject: [PATCH 4/6] fix: don't mark the first story viewed when the viewer lands on a later one A restore or Back mounts the swipe viewer on index 0 and jumps to its story in a layout effect, before paint. The dwell effect for index 0 still ran, so the top story got hidden for 12 hours without being seen. --- src/components/SwipeStoryViewer.test.tsx | 86 ++++++++++++++++++++++++ src/components/SwipeStoryViewer.tsx | 10 ++- 2 files changed, 95 insertions(+), 1 deletion(-) diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx index a0827e1..eaa8779 100644 --- a/src/components/SwipeStoryViewer.test.tsx +++ b/src/components/SwipeStoryViewer.test.tsx @@ -8,6 +8,7 @@ import { clearViewedTimes, clearSessionViewed, addToSessionViewed, + getSessionViewedIds, VIEWED_DETAIL_TIMES_KEY, } from '../utils/viewedItems'; import { saveSwipePosition, readSwipePosition } from '../utils/swipePosition'; @@ -663,4 +664,89 @@ describe('SwipeStoryViewerCore — end-of-feed panel', () => { expect(screen.queryByTestId('swipe-panel-loading')).not.toBeInTheDocument(); expect(activePanel()?.getAttribute('data-item-id')).toBe('2'); }); +}); + +describe('SwipeStoryViewerCore — viewed marks on landing', () => { + const baseProps = { + loading: false, + error: null, + hasMore: false, + loadMore: vi.fn().mockResolvedValue(undefined), + }; + + beforeEach(() => { + clearViewed(); + clearViewedTimes(); + clearSessionViewed(); + sessionStorage.clear(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + const markedIds = () => + Object.keys(JSON.parse(localStorage.getItem(VIEWED_DETAIL_TIMES_KEY) ?? '{}') as Record).map(Number); + + it('marks only the restored story, not the first one it jumps past', () => { + const stories = Array.from({ length: 21 }, (_, i) => createStoryItem({ id: 100 + i })); + saveSwipePosition({ viewer: { from: 'best' }, storyId: 110, index: 10, scrollY: 0, stories }); + + render(); + + expect(activePanel()?.getAttribute('data-item-id')).toBe('110'); + expect(markedIds()).toEqual([110]); + expect([...getSessionViewedIds()]).toEqual([110]); + }); + + it('marks only the story Back returns to, not a new first story', () => { + const stories = [1, 2, 3, 4, 5].map(id => createStoryItem({ id })); + + render( + , + { initialEntries: [{ pathname: '/item/4', state: { from: 'top' } }] }, + ); + + expect(activePanel()?.getAttribute('data-item-id')).toBe('4'); + expect(markedIds()).toEqual([4]); + }); + + it('marks the story Back returns to when the feed arrives after mount', () => { + const stories = [1, 2, 3, 4, 5].map(id => createStoryItem({ id })); + const backState: LocationState = { from: 'top' }; + const props = { ...baseProps, initialItemId: '4', backState }; + const entries = { initialEntries: [{ pathname: '/item/4', state: { from: 'top' } }] }; + + const { rerender } = render(, entries); + rerender(); + + expect(activePanel()?.getAttribute('data-item-id')).toBe('4'); + expect(markedIds()).toEqual([4]); + }); + + it('marks the stories a reader swipes to after landing', () => { + vi.useFakeTimers(); + const stories = [1, 2, 3, 4, 5].map(id => createStoryItem({ id })); + + render( + , + { initialEntries: [{ pathname: '/item/2', state: { from: 'top' } }] }, + ); + // Touches are ignored while the landing jump settles. + act(() => { + vi.advanceTimersByTime(50); + }); + swipeToNext(); + + expect(activePanel()?.getAttribute('data-item-id')).toBe('3'); + expect(markedIds().sort((a, b) => a - b)).toEqual([2, 3]); + }); + + it('marks the first story when the viewer opens on it', () => { + const stories = [1, 2, 3].map(id => createStoryItem({ id })); + + render(); + + expect(markedIds()).toEqual([1]); + }); }); \ No newline at end of file diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx index 88b4eca..4d630b4 100644 --- a/src/components/SwipeStoryViewer.tsx +++ b/src/components/SwipeStoryViewer.tsx @@ -513,9 +513,17 @@ export function SwipeStoryViewerCore({ usePrefetchItems(currentIndex, mergedStories, 6); + // A restore or Back mounts on index 0 and scroll-init jumps to its story + // before paint, so until currentIndex reaches that story, the panel it + // shows was never seen. + const [landingStoryId, setLandingStoryId] = useState(() => (anchorStoryId == null ? initialItemIdNum ?? null : null)); + const landingIndex = landingStoryId == null ? -1 : mergedStories.findIndex(s => s.id === landingStoryId); + if (landingIndex >= 0 && landingIndex === currentIndex) setLandingStoryId(null); + const isBeforeLanding = landingIndex > 0 && landingIndex !== currentIndex; + // Each panel IS the story detail on mobile — track how long the active story // is looked at and hide it for a window scaled to that dwell time. - useViewDwell(currentStory?.id); + useViewDwell(isBeforeLanding ? undefined : currentStory?.id); useLayoutEffect(() => { onReachedStoriesChange?.(mergedStories.slice(0, currentIndex + 1).map(story => story.id)); From 4a334f8eb3f7b99fcdd7d189218505ab2536291c Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:56:14 +0100 Subject: [PATCH 5/6] fix: say 1 point and 1 comment instead of 1 points and 1 comments --- src/components/ItemArticle.test.tsx | 7 +++++++ src/components/ItemArticle.tsx | 5 +++-- src/components/StoryCard.test.tsx | 7 +++++++ src/components/StoryCard.tsx | 4 ++-- 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/components/ItemArticle.test.tsx b/src/components/ItemArticle.test.tsx index 65a1b5d..b0b7370 100644 --- a/src/components/ItemArticle.test.tsx +++ b/src/components/ItemArticle.test.tsx @@ -114,6 +114,13 @@ describe('ItemArticle', () => { expect(screen.getByText(/^0\s+comments$/)).toBeInTheDocument(); }); + it('says "1 point" and "1 comment" for a count of one', () => { + render(); + + expect(screen.getByText(/^1\s+point$/)).toBeInTheDocument(); + expect(screen.getByText(/^1\s+comment$/)).toBeInTheDocument(); + }); + it('forces "0 comments" on job posts even when API reports a non-zero count', () => { // type: 'job' never accepts comments, but the API sometimes ships // a stale descendants count anyway. The render coerces to 0 so we diff --git a/src/components/ItemArticle.tsx b/src/components/ItemArticle.tsx index 741aeb5..05f5d80 100644 --- a/src/components/ItemArticle.tsx +++ b/src/components/ItemArticle.tsx @@ -20,6 +20,7 @@ interface ItemArticleProps { export function ItemArticle({ item, className = 'mb-4 pb-4 border-b border-border' }: ItemArticleProps) { const viewed = useIsViewed(item.id); const hostname = getHostname(item.url); + const commentCount = item.type !== 'job' ? (item.commentCount ?? 0) : 0; // Gate the outbound href to http(s) so javascript:/data: URLs can't reach the // DOM; anything else degrades to plain text. Keep it ONE `startsWith` — a `||` @@ -57,7 +58,7 @@ export function ItemArticle({ item, className = 'mb-4 pb-4 border-b border-borde
- {item.points ?? 0} points + {item.points ?? 0} {item.points === 1 ? 'point' : 'points'} {hostname && ( @@ -76,7 +77,7 @@ export function ItemArticle({ item, className = 'mb-4 pb-4 border-b border-borde - {item.type !== 'job' ? (item.commentCount ?? 0) : 0} comments + {commentCount} {commentCount === 1 ? 'comment' : 'comments'} diff --git a/src/components/StoryCard.test.tsx b/src/components/StoryCard.test.tsx index 3822151..d4a791c 100644 --- a/src/components/StoryCard.test.tsx +++ b/src/components/StoryCard.test.tsx @@ -122,6 +122,13 @@ describe('StoryCard', () => { expect(screen.getByRole('link', { name: /^0\s+comments$/ })).toBeInTheDocument(); }); + + it('says "1 point" and "1 comment" for a count of one', () => { + render(); + + expect(screen.getByText(/^1\s+point$/)).toBeInTheDocument(); + expect(screen.getByRole('link', { name: /^1\s+comment$/ })).toBeInTheDocument(); + }); }); describe('link behavior', () => { diff --git a/src/components/StoryCard.tsx b/src/components/StoryCard.tsx index c3f76e7..d41e003 100644 --- a/src/components/StoryCard.tsx +++ b/src/components/StoryCard.tsx @@ -191,7 +191,7 @@ export function StoryCard({ story, index = 0, listType = 'top', fromDomain, from
- {story.points ?? 0} points + {story.points ?? 0} {story.points === 1 ? 'point' : 'points'} {hostname && ( @@ -219,7 +219,7 @@ export function StoryCard({ story, index = 0, listType = 'top', fromDomain, from className={metaPillClass} > - {story.commentCount ?? 0} comments + {story.commentCount ?? 0} {story.commentCount === 1 ? 'comment' : 'comments'}
From e47b2f83624303cbb6cbfe5bff12cc64098b9d6a Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:56:40 +0100 Subject: [PATCH 6/6] fix: say 11 months ago, not 12 months ago, for items 360-364 days old --- src/api/hn.test.ts | 7 +++++++ src/api/hn.ts | 3 ++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts index 74ad733..ac28557 100644 --- a/src/api/hn.test.ts +++ b/src/api/hn.test.ts @@ -121,6 +121,13 @@ describe('hn API utilities', () => { expect(formatTimeAgo(now - 90 * 24 * 60 * 60 * 1000)).toBe('3 months ago'); }); + it('stays at 11 months until a full year has passed', () => { + const now = Date.now(); + expect(formatTimeAgo(now - 360 * 24 * 60 * 60 * 1000)).toBe('11 months ago'); + expect(formatTimeAgo(now - 364 * 24 * 60 * 60 * 1000)).toBe('11 months ago'); + expect(formatTimeAgo(now - 365 * 24 * 60 * 60 * 1000)).toBe('1 year ago'); + }); + it('formats years correctly', () => { const now = Date.now(); expect(formatTimeAgo(now - 365 * 24 * 60 * 60 * 1000)).toBe('1 year ago'); diff --git a/src/api/hn.ts b/src/api/hn.ts index 0ea39f8..d5fb1c7 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -783,7 +783,8 @@ export function formatTimeAgo(timestamp: number): string { const minutes = Math.floor(seconds / 60); const hours = Math.floor(minutes / 60); const days = Math.floor(hours / 24); - const months = Math.floor(days / 30); + // 30-day months reach 12 at day 360, five days short of a year. + const months = Math.min(Math.floor(days / 30), 11); const years = Math.floor(days / 365); if (years > 0) return `${years} year${years > 1 ? 's' : ''} ago`;