Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions e2e/domain-filter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
137 changes: 136 additions & 1 deletion src/api/hn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
});
});
});
82 changes: 76 additions & 6 deletions src/api/hn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ThreadComment[] | null>; timestamp: number } | null = null;
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

/** @internal Testing helper to reset module-level caches between tests. */
Expand All @@ -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) {
Expand Down Expand Up @@ -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<AlgoliaComment[]> {
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 });
Expand All @@ -372,11 +379,11 @@ async function fetchAllCommentsAlgolia(itemId: number, signal?: AbortSignal): Pr
}

const data = await response.json() as AlgoliaSearchResponse<AlgoliaComment>;
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++;
Expand All @@ -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<AlgoliaComment[]> {
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) {
Expand Down Expand Up @@ -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<ThreadComment[] | null> {
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<boolean> {
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<Comment[]> {
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)
Expand Down
28 changes: 28 additions & 0 deletions src/components/CommentArticle.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 7 additions & 2 deletions src/components/CommentArticle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -38,6 +40,7 @@ export function CommentArticle({
itemTitle,
itemTitleLoading = false,
loading,
moreRepliesLoading = false,
onRetryReplies,
articleClassName = 'mb-4',
storyAuthor = '',
Expand Down Expand Up @@ -130,12 +133,14 @@ export function CommentArticle({
</article>

<section>
{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.
<CommentSkeletonTree count={6} />
) : onRetryReplies ? (
<StateView variant="error" compact description="Failed to load replies" action={{ label: 'Retry', onClick: onRetryReplies }} />
Expand Down
7 changes: 6 additions & 1 deletion src/components/CommentDetail.test.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
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';
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(
Expand All @@ -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.
Expand Down
Loading
Loading