From 04c9e742d1a6b31448ccbdab4489fc41901fbab0 Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Sun, 22 Nov 2026 02:14:50 +0200
Subject: [PATCH 1/6] fix: open a job from a direct link on a phone
On a phone, a direct link to a job, such as #/item/50593679, showed
"This item is not a story". The link resolver sent every top-level item
to the story viewer, which only takes stories. It now tells stories from
jobs and opens a job on the item page, as desktop does.
The e2e test that expected the old message now checks for the item page.
---
e2e/fixtures/mock-data.ts | 2 +-
e2e/mobile-swipe.spec.ts | 17 +++++++++--------
src/App.test.tsx | 14 ++++++++++++++
src/App.tsx | 22 ++++++++++++----------
4 files changed, 36 insertions(+), 19 deletions(-)
diff --git a/e2e/fixtures/mock-data.ts b/e2e/fixtures/mock-data.ts
index 06c1a2c..777bd83 100644
--- a/e2e/fixtures/mock-data.ts
+++ b/e2e/fixtures/mock-data.ts
@@ -326,7 +326,7 @@ export const mockAlgoliaCommentItem1004 = {
children: [],
};
-// Job item — type=job triggers SwipeStoryViewer's "not a story" error path on mobile.
+// Job item — a direct link opens it on the item page on mobile too.
export const mockJobItem = {
id: 55555,
type: 'job',
diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts
index 4338dff..9a1a24a 100644
--- a/e2e/mobile-swipe.spec.ts
+++ b/e2e/mobile-swipe.spec.ts
@@ -938,16 +938,17 @@ test.describe('Mobile Direct Item Access', () => {
await expect(page).toHaveURL(/\/item\/1001/);
});
- test('shows not-available message for job items', async ({ page }) => {
- // Job items (type: 'job') are not stories — SwipeStoryViewer shows an error.
- // Flow: MobileItemResolver fetches item → type is 'job' (not 'comment') →
- // renders SwipeStoryViewer → it fetches again → detects type === 'job' →
- // sets injectedError('job') → renders error UI.
+ test('opens job items on the item page', async ({ page }) => {
+ // The swipe viewer only takes stories, and no feed lists jobs, so a direct
+ // link to one gets the item page, as on desktop.
await page.goto('/#/item/55555');
- await expect(page.getByText('This item is not a story')).toBeVisible({ timeout: 10000 });
- await expect(page.getByRole('link', { name: /back to home/i })).toBeVisible();
- await expect(page).toHaveTitle(/Item not available.*HackerTok/);
+ await expect(page.getByRole('heading', { name: 'YC Startup Is Hiring Engineers' })).toBeVisible({ timeout: 10000 });
+ await expect(page).toHaveTitle(/YC Startup Is Hiring Engineers.*HackerTok/);
+ await expect(page.getByTestId('swipe-container')).toHaveCount(0);
+ // index.html adds swipe-mode before paint for any /item/:id.
+ await expect(page.locator('html')).not.toHaveClass(/swipe-mode/);
+ await expect(page.locator('body')).not.toHaveClass(/swipe-mode/);
});
test('restores swipe position on the main feed after a full page reload', async ({ page }) => {
diff --git a/src/App.test.tsx b/src/App.test.tsx
index d2390f1..7dce0d6 100644
--- a/src/App.test.tsx
+++ b/src/App.test.tsx
@@ -46,6 +46,9 @@ vi.mock('./components/SwipeUserSubmissionsViewer', () => ({
),
}));
+vi.mock('./pages/ItemDetail', () => ({
+ ItemDetail: () => ,
+}));
// The resolver fallback (Branch 5) calls fetchItemOnly; keep it pending so the
// resolver stays on its skeleton — a deterministic signal that we did NOT take
@@ -186,6 +189,17 @@ describe('MobileStoryRoute — direct link', () => {
expect(viewer).toHaveAttribute('data-item', '12345');
expect(viewer).toHaveAttribute('data-mounted-item', '88888');
});
+
+ it('opens a job on the item page, since the story viewer only takes stories', async () => {
+ vi.mocked(fetchItemOnly).mockResolvedValueOnce({
+ id: 77777, type: 'job', title: 'Acme Is Hiring', author: 'acme', createdAt: 0, points: 1,
+ });
+
+ renderWrapper(77777);
+
+ expect(await screen.findByTestId('item-detail')).toBeInTheDocument();
+ expect(screen.queryByTestId('feed-viewer')).toBeNull();
+ });
});
describe('MobileStoryRoute — ids that are not numbers', () => {
diff --git a/src/App.tsx b/src/App.tsx
index 8a698db..9af2e81 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -111,7 +111,7 @@ export function MobileStoryRoute({ feed }: { feed?: FeedType }) {
const viewer = canSwipe && isNumericId
? pickSwipeViewer(location.state as LocationState | null, recovered, id, feedEntries)
: null;
- const isResolvedStory = useResolveDirectLink(id, canSwipe && isNumericId && !viewer);
+ const resolvedType = useResolveDirectLink(id, canSwipe && isNumericId && !viewer);
if (feed) {
// key={feed}: a list mounts for each feed, so Back to one restores its
@@ -129,8 +129,10 @@ export function MobileStoryRoute({ feed }: { feed?: FeedType }) {
// Branch 5: Direct URL (no state) → resolve type first. The story viewer
// must be the element Branch 4 renders for `{ from: 'top' }`: the first
// swipe writes that state, and a different element there would remount
- // the viewer and drop the story this link opened.
- if (isResolvedStory) return renderSwipeViewer({ from: 'top' }, id, feedEntries);
+ // the viewer and drop the story this link opened. A job has no comments
+ // to swipe through and no feed lists it, so it gets the item page.
+ if (resolvedType === 'job') return ;
+ if (resolvedType === 'story') return renderSwipeViewer({ from: 'top' }, id, feedEntries);
return ;
}
@@ -178,10 +180,10 @@ function ItemNotFound() {
}
// Resolves item type for a direct URL hit on mobile (no `location.state`):
-// a comment re-routes to Branch 1, and anything else reports `true` so the
-// wrapper mounts the story viewer.
-function useResolveDirectLink(id: string | undefined, enabled: boolean): boolean {
- const [storyId, setStoryId] = useState(null);
+// a comment re-routes to Branch 1, a job reports `'job'`, and anything else
+// reports `'story'` so the wrapper mounts the story viewer.
+function useResolveDirectLink(id: string | undefined, enabled: boolean): 'story' | 'job' | null {
+ const [resolved, setResolved] = useState<{ id: string; type: 'story' | 'job' } | null>(null);
const navigate = useNavigate();
useEffect(() => {
@@ -195,19 +197,19 @@ function useResolveDirectLink(id: string | undefined, enabled: boolean): boolean
// Navigate with state so MobileStoryRoute Branch 1 picks it up
void navigate(`/item/${id}`, { replace: true, state: { isComment: true } });
} else {
- setStoryId(id);
+ setResolved({ id, type: item.type === 'job' ? 'job' : 'story' });
}
})
.catch(() => {
if (controller.signal.aborted) return;
// Default to story viewer on error (it has its own error handling)
- setStoryId(id);
+ setResolved({ id, type: 'story' });
});
return () => controller.abort();
}, [id, enabled, navigate]);
- return storyId !== null && storyId === id;
+ return resolved && resolved.id === id ? resolved.type : null;
}
function MobileItemResolverSkeleton() {
From b0fdf277aee3f6fe021d44df7b52fa5101ad8838 Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Sun, 22 Nov 2026 02:15:18 +0200
Subject: [PATCH 2/6] fix: show a comment's replies in HN's order on its own
page
A comment's page listed its replies oldest first, the order Algolia's
item tree and search return them in, while HN ranks them. The story
thread already takes the order from Firebase's kids.
The page now sorts the replies it first shows by the comment's own
Firebase kids, read once Algolia's item has loaded, so the order settles
about 150ms after the replies appear instead of seconds later. Nested
replies and flagged ones take HN's order once the story's comments load.
That replacement now also happens when it adds no replies, and a thread
too big for search is ordered too instead of keeping the item tree.
---
src/api/hn.test.ts | 16 ++++++++--
src/api/hn.ts | 18 ++++++++---
src/hooks/useCommentDetail.test.ts | 49 ++++++++++++++++++++++++++++++
src/hooks/useCommentDetail.ts | 22 ++++++++++++--
4 files changed, 97 insertions(+), 8 deletions(-)
diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts
index 4248d43..21d1be6 100644
--- a/src/api/hn.test.ts
+++ b/src/api/hn.test.ts
@@ -1342,8 +1342,20 @@ describe('hn API utilities', () => {
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]);
+ // 201 and its reply 302 to see whether to search, then each missing
+ // parent once, and 101 to order its two replies.
+ expect(readItem.mock.calls.map(([id]) => Number(id)).sort()).toEqual([101, 201, 202, 302, 302]);
+ });
+
+ it('orders the replies the way HN ranks them', async () => {
+ const { readItem } = mockStory();
+ readItem.mockImplementation(async (id) => Number(id) === 101
+ ? { id: 101, type: 'comment', by: 'alice', time: 1700000100, parent: storyId, kids: [202, 201] }
+ : firebaseItems.find(fb => fb.id === Number(id)) ?? null);
+
+ const replies = await fetchCommentReplies(item);
+
+ expect(replies.map(c => c.id)).toEqual([202, 201]);
});
it('reads the story again after a failed read', async () => {
diff --git a/src/api/hn.ts b/src/api/hn.ts
index d6a8f3e..d657d0a 100644
--- a/src/api/hn.ts
+++ b/src/api/hn.ts
@@ -789,8 +789,9 @@ async function hasRepliesOutsideItemTree(id: number, signal?: AbortSignal): Prom
/**
* 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.
+ * replies, in HN's order. Algolia's item tree leaves those out along with
+ * their replies, so they come from the story's comments, as in the story
+ * thread. Both come in creation order, so the order comes from Firebase.
*/
export async function fetchCommentReplies(item: AlgoliaItemResponse, signal?: AbortSignal): Promise {
if (item.story_id == null) return normalizeAlgoliaItemChildren(item.children ?? []);
@@ -800,15 +801,24 @@ export async function fetchCommentReplies(item: AlgoliaItemResponse, signal?: Ab
}
if (!mayHaveMore) return [];
+ // Null for a thread bigger than search returns, which keeps the item tree's replies.
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);
+ const comments = [...replies, ...(storyComments ?? []).filter(c => !seen.has(c.objectID))];
+ const kidsOrder = await fetchKidsOrdering(parentsWithSiblings(buildCommentTree(comments, item.id), item.id), signal);
+ return buildCommentTree(comments, item.id, kidsOrder);
+}
+
+// The ids in a reply tree whose replies need ordering: those with more than one.
+function parentsWithSiblings(replies: Comment[], parentId: number, into: number[] = []): number[] {
+ if (replies.length > 1) into.push(parentId);
+ for (const reply of replies) parentsWithSiblings(reply.children, reply.id, into);
+ return into;
}
export function normalizeAlgoliaItemChildren(children: AlgoliaItemChild[]): Comment[] {
diff --git a/src/hooks/useCommentDetail.test.ts b/src/hooks/useCommentDetail.test.ts
index 4f8cc55..4978bfd 100644
--- a/src/hooks/useCommentDetail.test.ts
+++ b/src/hooks/useCommentDetail.test.ts
@@ -5,6 +5,7 @@ import { useCommentDetail } from './useCommentDetail';
import { __resetFetchCachesForTests } from '../api/hn';
import { hnSdk } from '../api/hnSdk';
import { server } from '../mocks/server';
+import { mockAlgoliaCommentItem } from '../mocks/handlers';
import { ALGOLIA_API } from '../config/api';
import type { FirebaseItem } from '../types';
@@ -120,6 +121,54 @@ describe('useCommentDetail', () => {
expect(result.current.comment).toBeNull();
});
+ describe("HN's order, which Algolia's item tree doesn't keep", () => {
+ const now = Math.floor(Date.now() / 1000);
+ const reply = (id: number, parentId: number, age: number, children: object[] = []) =>
+ ({ id, author: `user${id}`, text: 'Reply', created_at_i: now - age, parent_id: parentId, children });
+
+ function mockComment(children: object[], firebaseItems: FirebaseItem[], storyComments: () => Response | Promise) {
+ server.use(
+ http.get(`${ALGOLIA_API}/items/:id`, () => HttpResponse.json({ ...mockAlgoliaCommentItem, children })),
+ http.get(`${ALGOLIA_API}/search`, storyComments),
+ );
+ vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => {
+ if (Number(id) === 12345) return mockStoryItem;
+ return firebaseItems.find(item => item.id === Number(id)) ?? null;
+ });
+ }
+
+ it("puts the replies in it without waiting for the story's comments", async () => {
+ mockComment(
+ [reply(2001, 1001, 900), reply(2002, 1001, 800)],
+ [{ id: 1001, type: 'comment', by: 'patio11', time: now - 1800, parent: 12345, kids: [2002, 2001] }],
+ () => new Promise(() => { /* never loads */ }),
+ );
+
+ const { result } = renderHook(() => useCommentDetail(1001));
+
+ await waitFor(() => {
+ expect(result.current.replies.map(c => c.id)).toEqual([2002, 2001]);
+ });
+ expect(result.current.moreRepliesLoading).toBe(true);
+ });
+
+ it("puts nested replies in it once the story's comments load", async () => {
+ mockComment(
+ [reply(2001, 1001, 900, [reply(3001, 2001, 700), reply(3002, 2001, 600)])],
+ [{ id: 2001, type: 'comment', by: 'user2001', time: now - 900, parent: 1001, kids: [3002, 3001] }],
+ () => HttpResponse.json({ hits: [], nbHits: 0, nbPages: 0 }),
+ );
+
+ const { result } = renderHook(() => useCommentDetail(1001));
+
+ await waitFor(() => {
+ expect(result.current.loading).toBe(false);
+ expect(result.current.moreRepliesLoading).toBe(false);
+ });
+ expect(result.current.replies[0].children.map(c => c.id)).toEqual([3002, 3001]);
+ });
+ });
+
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 })),
diff --git a/src/hooks/useCommentDetail.ts b/src/hooks/useCommentDetail.ts
index 77e8564..7aa7cca 100644
--- a/src/hooks/useCommentDetail.ts
+++ b/src/hooks/useCommentDetail.ts
@@ -6,6 +6,11 @@ function countComments(comments: Comment[]): number {
return comments.reduce((count, comment) => count + 1 + countComments(comment.children), 0);
}
+function orderByKids(replies: Comment[], kids: number[]): Comment[] {
+ const rank = new Map(kids.map((id, i) => [id, i]));
+ return [...replies].sort((a, b) => (rank.get(a.id) ?? kids.length) - (rank.get(b.id) ?? kids.length));
+}
+
interface CommentData {
id: number;
author: string;
@@ -86,13 +91,26 @@ export function useCommentDetail(
setMoreRepliesLoading(!!item.story_id);
setLoading(false);
+ // The item tree has replies in creation order. HN's order for the ones
+ // shown comes from the comment's Firebase item, sooner than the story's
+ // comments below, which order the rest.
+ if ((item.children?.length ?? 0) > 1) {
+ void fetchFirebaseItem(item.id, signal).then(
+ ({ kids }) => {
+ if (!signal.aborted && kids) setReplies(shown => orderByKids(shown, kids));
+ },
+ () => { /* creation order stays */ },
+ );
+ }
+
// 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.
+ // the replies under them. Those fill in, and nested replies take HN's
+ // order, 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));
+ setReplies(shown => (countComments(all) >= countComments(shown) ? all : shown));
setMoreRepliesLoading(false);
},
() => {
From 6fa64d1fcf7a6f7920d281f76c84477645bc8054 Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Sun, 22 Nov 2026 02:15:18 +0200
Subject: [PATCH 3/6] fix: keep parentheses in an auto-linked URL
A plain-text URL in a comment, such as
https://en.wikipedia.org/wiki/Foil_(narrative), was linked only up to
the "(". The auto-linker now keeps balanced parentheses in a URL and
still leaves out a closing one that wraps the whole URL, as in
"(see https://...)". An unbalanced "(" inside a URL still ends the link.
---
src/utils/sanitize.test.ts | 11 +++++++++++
src/utils/sanitize.ts | 5 +++--
2 files changed, 14 insertions(+), 2 deletions(-)
diff --git a/src/utils/sanitize.test.ts b/src/utils/sanitize.test.ts
index 39e9113..939f878 100644
--- a/src/utils/sanitize.test.ts
+++ b/src/utils/sanitize.test.ts
@@ -284,6 +284,17 @@ describe('sanitizeHtml', () => {
expect(result).toContain('href="https://example.com"');
});
+ it('keeps balanced parentheses in an auto-linked URL', () => {
+ const result = sanitizeHtml('See https://en.wikipedia.org/wiki/Foil_(narrative) for more');
+ expect(result).toContain('href="https://en.wikipedia.org/wiki/Foil_(narrative)"');
+ });
+
+ it('excludes the parenthesis around a URL that has its own pair', () => {
+ const result = sanitizeHtml('(see https://en.wikipedia.org/wiki/Foil_(narrative)).');
+ expect(result).toContain('href="https://en.wikipedia.org/wiki/Foil_(narrative)"');
+ expect(result).toContain('Foil_(narrative)).');
+ });
+
it('excludes trailing semicolon from auto-linked URL', () => {
const result = sanitizeHtml('url: https://example.com;');
expect(result).toContain('href="https://example.com"');
diff --git a/src/utils/sanitize.ts b/src/utils/sanitize.ts
index d959293..4f93abe 100644
--- a/src/utils/sanitize.ts
+++ b/src/utils/sanitize.ts
@@ -307,11 +307,12 @@ DOMPurify.addHook('afterSanitizeAttributes', (node) => {
// Match URLs and emails in a single pass (module-level to avoid
// recompilation). The URL branch ends with a character-class that
// excludes common trailing punctuation so "Visit https://x.com."
-// links only "https://x.com".
+// links only "https://x.com". Parentheses count only in balanced pairs,
+// so "(see https://x.com/Foo_(bar))" links "https://x.com/Foo_(bar)".
// The email branch requires alphanumeric segments separated by
// dots/special chars — rejecting leading/trailing/consecutive dots
// and bare-special-char local parts (e.g. `.@`, `..@`, `%@`).
-const LINKABLE = /(https?:\/\/[^\s<>]*[^\s<>.,;:!?'")\]}>]|[a-zA-Z0-9]+(?:[._%+-][a-zA-Z0-9]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,})/g;
+const LINKABLE = /(https?:\/\/(?:[^\s<>()]|\([^\s<>()]*\))*(?:[^\s<>.,;:!?'"()\]}>]|\([^\s<>()]*\))|[a-zA-Z0-9]+(?:[._%+-][a-zA-Z0-9]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,})/g;
function autoLinkUrls(html: string): string {
if (typeof document === 'undefined') return html;
From 5143b3b82e2754de7277fbbecefe8ca9e95a5dfa Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Sun, 22 Nov 2026 02:15:18 +0200
Subject: [PATCH 4/6] fix: link a flagged comment with no replies to its story
A flagged or deleted comment that Algolia 404s is read from Firebase,
which has no story id. It took the story from its first reply, so with
no replies, as for #/item/234621, its page lost the story link and
title. It now walks up the comment's Firebase parent chain to the story,
up to 100 levels, and goes without the link only if a read fails.
---
src/api/hn.ts | 14 +++++++++++++-
src/hooks/useCommentDetail.test.ts | 19 +++++++++++++++++++
2 files changed, 32 insertions(+), 1 deletion(-)
diff --git a/src/api/hn.ts b/src/api/hn.ts
index d657d0a..b624a1e 100644
--- a/src/api/hn.ts
+++ b/src/api/hn.ts
@@ -749,11 +749,23 @@ export async function fetchCommentItem(id: number | string, signal?: AbortSignal
text: firebaseCommentText(item) ?? null,
created_at_i: item.time ?? 0,
parent_id: item.parent ?? null,
- story_id: replies[0]?.story_id ?? null,
+ story_id: replies[0]?.story_id ?? await findStoryId(item.parent, signal),
children: replies.map(reply => ({ ...reply, parent_id: item.id })),
};
}
+// The story a comment is on, up its parent chain: Firebase keeps flagged and
+// deleted comments, which Algolia 404s. Null when a read fails.
+async function findStoryId(parentId: number | undefined, signal?: AbortSignal): Promise {
+ for (let id = parentId, hops = 0; id != null && hops < 100; hops++) {
+ const parent = await fetchFirebaseItem(id, signal).catch(() => null);
+ if (!parent) return null;
+ if (parent.type !== 'comment') return parent.id;
+ id = parent.parent;
+ }
+ return null;
+}
+
// 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.
diff --git a/src/hooks/useCommentDetail.test.ts b/src/hooks/useCommentDetail.test.ts
index 4978bfd..05fb9c6 100644
--- a/src/hooks/useCommentDetail.test.ts
+++ b/src/hooks/useCommentDetail.test.ts
@@ -121,6 +121,25 @@ describe('useCommentDetail', () => {
expect(result.current.comment).toBeNull();
});
+ it('finds the story of a flagged comment with no replies up its parent chain', async () => {
+ const now = Math.floor(Date.now() / 1000);
+ const items: FirebaseItem[] = [
+ mockStoryItem,
+ { id: 1001, type: 'comment', by: 'patio11', text: 'Root', time: now - 1800, parent: 12345, kids: [2001] },
+ { id: 2001, type: 'comment', by: 'tptacek', text: 'Reply', time: now - 900, parent: 1001, kids: [4001] },
+ { id: 4001, type: 'comment', by: 'eve', text: 'Killed text', dead: true, time: now - 300, parent: 2001 },
+ ];
+ vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => items.find(item => item.id === Number(id)) ?? null);
+
+ const { result } = renderHook(() => useCommentDetail(4001));
+
+ await waitFor(() => {
+ expect(result.current.itemTitle).toBe('Rust Is the Future of JavaScript Infrastructure');
+ });
+ expect(result.current.itemId).toBe(12345);
+ expect(result.current.comment).toMatchObject({ id: 4001, parentId: 2001 });
+ });
+
describe("HN's order, which Algolia's item tree doesn't keep", () => {
const now = Math.floor(Date.now() / 1000);
const reply = (id: number, parentId: number, age: number, children: object[] = []) =>
From 7cbb95ac8a5713bb195d55133126128004aa24e5 Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Sun, 22 Nov 2026 02:48:15 +0200
Subject: [PATCH 5/6] fix: open a phone's feed on its current first story, not
an old cached one
On a phone, a feed opens from the stories cached on the last visit and
then refreshes them. The refresh keeps every story the reader has
reached, including the first one on screen, so an app launched from a
cache hours old stayed on a story that may no longer lead the feed. The
logo then opened the feed again from the refreshed cache and showed a
different first story.
Opening a feed now uses its cache only if it is under five minutes old.
An older cache waits for the refresh behind the loading skeleton, and is
shown if the refresh fails or the app is offline, where the refresh never
settles. A story URL shows that story either way, as before.
The e2e test for a refresh that lands after a swipe now seeds a
minute-old cache, so the feed still opens from it.
---
e2e/mobile-swipe.spec.ts | 7 ++--
src/components/SwipeStoryViewer.test.tsx | 52 ++++++++++++++++++++++--
src/components/SwipeStoryViewer.tsx | 18 +++++++-
3 files changed, 68 insertions(+), 9 deletions(-)
diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts
index 9a1a24a..b9a4c88 100644
--- a/e2e/mobile-swipe.spec.ts
+++ b/e2e/mobile-swipe.spec.ts
@@ -431,15 +431,16 @@ test.describe('Mobile Swipe Viewer', () => {
});
test('a feed refresh that lands after a swipe keeps the story on screen', async ({ page }) => {
- // An hour-old cached Top feed in the reverse of the live order, and Firebase
- // reads that take 1.5s, so the refresh lands after the swipe.
+ // A minute-old cached Top feed in the reverse of the live order, which opens
+ // at once and still refreshes, and Firebase reads that take 1.5s, so the
+ // refresh lands after the swipe.
await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ delayMs: 1500 }));
await page.addInitScript((ids) => {
const stories = [...ids].reverse().map((id) => ({
id, type: 'story', title: `Cached story ${id}`, url: `https://example.com/${id}`,
points: 1, author: 'someone', createdAt: Date.now() - 3_600_000, commentCount: 0,
}));
- localStorage.setItem('feed:top', JSON.stringify({ stories, timestamp: Date.now() - 3_600_000 }));
+ localStorage.setItem('feed:top', JSON.stringify({ stories, timestamp: Date.now() - 60_000 }));
}, mockTopItemIds);
await page.goto('/#/');
diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx
index eaa8779..8b95e7a 100644
--- a/src/components/SwipeStoryViewer.test.tsx
+++ b/src/components/SwipeStoryViewer.test.tsx
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { act, screen, within } from '@testing-library/react';
+import { act, screen, waitFor, within } from '@testing-library/react';
import { render } from '../test/test-utils';
-import { SwipeStoryViewerCore } from './SwipeStoryViewer';
+import { SwipeStoryViewer, SwipeStoryViewerCore } from './SwipeStoryViewer';
import { createStoryItem } from '../test/factories';
import {
clearViewed,
@@ -12,7 +12,7 @@ import {
VIEWED_DETAIL_TIMES_KEY,
} from '../utils/viewedItems';
import { saveSwipePosition, readSwipePosition } from '../utils/swipePosition';
-import { fetchItemOnly } from '../api/hn';
+import { fetchItemOnly, fetchTopStories } from '../api/hn';
import type * as HnApi from '../api/hn';
import type { LocationState } from '../types';
@@ -30,8 +30,11 @@ vi.mock('./FullScreenItem', () => ({
vi.mock('../api/hn', async (importOriginal) => ({
...(await importOriginal()),
fetchItemOnly: vi.fn(() => new Promise(() => { /* never resolves */ })),
+ fetchTopStories: vi.fn(),
}));
+vi.mock('../hooks/usePrefetchSections', () => ({ usePrefetchSections: vi.fn() }));
+
// Swipes commit synchronously under reduced motion, without the Web Animations
// API that jsdom lacks.
vi.mock('../utils/prefersReducedMotion', () => ({ prefersReducedMotion: () => true }));
@@ -749,4 +752,45 @@ describe('SwipeStoryViewerCore — viewed marks on landing', () => {
expect(markedIds()).toEqual([1]);
});
-});
\ No newline at end of file
+});
+
+describe('SwipeStoryViewer — opening a feed from an old cache', () => {
+ // An hour-old cache, whose first story is second on HN now.
+ const cachedIds = Array.from({ length: 12 }, (_, i) => i + 1);
+
+ beforeEach(() => {
+ localStorage.setItem('feed:top', JSON.stringify({
+ stories: cachedIds.map(id => createStoryItem({ id })),
+ timestamp: Date.now() - 3_600_000,
+ }));
+ });
+
+ it('waits for the refresh instead of keeping the cached first story', async () => {
+ vi.mocked(fetchTopStories).mockResolvedValue([13, ...cachedIds].map(id => createStoryItem({ id })));
+ render();
+
+ expect(screen.getByTestId('fsi-skeleton')).toBeInTheDocument();
+ expect(screen.queryByTestId('fsi')).not.toBeInTheDocument();
+ await waitFor(() => expect(activePanel()).toHaveAttribute('data-item-id', '13'));
+ });
+
+ it('shows the cache when the refresh fails', async () => {
+ vi.mocked(fetchTopStories).mockRejectedValue(new Error('Failed to fetch'));
+ render();
+
+ await waitFor(() => expect(activePanel()).toHaveAttribute('data-item-id', '1'));
+ });
+
+ it('shows the cache once the app goes offline, where the refresh never settles', () => {
+ vi.mocked(fetchTopStories).mockReturnValue(new Promise(() => { /* never resolves */ }));
+ render();
+ expect(screen.getByTestId('fsi-skeleton')).toBeInTheDocument();
+ expect(screen.queryByTestId('fsi')).not.toBeInTheDocument();
+
+ act(() => {
+ window.dispatchEvent(new Event('offline'));
+ });
+
+ expect(activePanel()).toHaveAttribute('data-item-id', '1');
+ });
+});
diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx
index 4d630b4..c58ad99 100644
--- a/src/components/SwipeStoryViewer.tsx
+++ b/src/components/SwipeStoryViewer.tsx
@@ -10,6 +10,7 @@ import { useAutoRetry } from '../hooks/useAutoRetry';
import { fetchItemOnly, NotFoundError } from '../api/hn';
import { getFilteredViewedIds, getSessionViewedIds } from '../utils/viewedItems';
import { readSwipePosition, saveSwipePosition, clearSwipePosition } from '../utils/swipePosition';
+import { isCacheFresh } from '../utils/feedCache';
import { useViewDwell } from '../hooks/useViewDwell';
import { FEED_TYPE_TITLES } from '../config/feedTypes';
import { FullScreenItem, FullScreenItemSkeletonPanel } from './FullScreenItem';
@@ -738,9 +739,22 @@ interface SwipeStoryViewerProps {
initialItemId?: string;
}
+const NO_STORIES: StoryItem[] = [];
+
/** Feed-backed swipe viewer wrapping SwipeStoryViewerCore. */
export function SwipeStoryViewer({ type, initialItemId }: SwipeStoryViewerProps) {
const { stories, loading, error, hasMore, loadMore, isFromCache, isFromSession, keepOnRevalidate } = useInfiniteStories(type);
+ const { isOnline } = useNetworkStatus();
+
+ // The refresh below keeps the story on screen, so a feed opened from a cache
+ // over five minutes old would stay on its old first story, which the logo
+ // then replaces. Opening a feed waits for the refresh instead, and shows the
+ // cache if the refresh fails or the app is offline, where it never settles.
+ // A story URL shows that story either way.
+ const [hidesStaleCache, setHidesStaleCache] = useState(
+ () => initialItemId == null && isFromCache && !isCacheFresh(type),
+ );
+ if (hidesStaleCache && (!isFromCache || !!error || !isOnline)) setHidesStaleCache(false);
// Prefetch other sections in background for instant tab switching
usePrefetchSections(type);
@@ -759,8 +773,8 @@ export function SwipeStoryViewer({ type, initialItemId }: SwipeStoryViewerProps)
return (
Date: Sun, 22 Nov 2026 03:26:47 +0200
Subject: [PATCH 6/6] fix: show a phone's cached feed after three seconds on a
stalled connection
A feed opened from a cache over five minutes old waits for the refresh
behind the loading skeleton. Firebase waits for a connection with no
timeout, and the connection check counts its own timeout as unknown, so on
a stalled connection, or with only Firebase blocked, the skeleton stayed
for good. The cached stories now show after three seconds, as they did at
once before the wait.
---
src/components/SwipeStoryViewer.test.tsx | 21 +++++++++++++++++++++
src/components/SwipeStoryViewer.tsx | 11 +++++++++--
2 files changed, 30 insertions(+), 2 deletions(-)
diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx
index 8b95e7a..10fac93 100644
--- a/src/components/SwipeStoryViewer.test.tsx
+++ b/src/components/SwipeStoryViewer.test.tsx
@@ -765,6 +765,10 @@ describe('SwipeStoryViewer — opening a feed from an old cache', () => {
}));
});
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
it('waits for the refresh instead of keeping the cached first story', async () => {
vi.mocked(fetchTopStories).mockResolvedValue([13, ...cachedIds].map(id => createStoryItem({ id })));
render();
@@ -793,4 +797,21 @@ describe('SwipeStoryViewer — opening a feed from an old cache', () => {
expect(activePanel()).toHaveAttribute('data-item-id', '1');
});
+
+ it('shows the cache after three seconds when the refresh stalls online', () => {
+ vi.useFakeTimers();
+ vi.mocked(fetchTopStories).mockReturnValue(new Promise(() => { /* never resolves */ }));
+ render();
+
+ act(() => {
+ vi.advanceTimersByTime(2_999);
+ });
+ expect(screen.getByTestId('fsi-skeleton')).toBeInTheDocument();
+ expect(screen.queryByTestId('fsi')).not.toBeInTheDocument();
+
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(activePanel()).toHaveAttribute('data-item-id', '1');
+ });
});
diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx
index c58ad99..b899fea 100644
--- a/src/components/SwipeStoryViewer.tsx
+++ b/src/components/SwipeStoryViewer.tsx
@@ -740,6 +740,7 @@ interface SwipeStoryViewerProps {
}
const NO_STORIES: StoryItem[] = [];
+const STALE_CACHE_WAIT_MS = 3000;
/** Feed-backed swipe viewer wrapping SwipeStoryViewerCore. */
export function SwipeStoryViewer({ type, initialItemId }: SwipeStoryViewerProps) {
@@ -749,12 +750,18 @@ export function SwipeStoryViewer({ type, initialItemId }: SwipeStoryViewerProps)
// The refresh below keeps the story on screen, so a feed opened from a cache
// over five minutes old would stay on its old first story, which the logo
// then replaces. Opening a feed waits for the refresh instead, and shows the
- // cache if the refresh fails or the app is offline, where it never settles.
- // A story URL shows that story either way.
+ // cache if the refresh fails, the app is offline, or three seconds pass, as
+ // on a stalled connection, where Firebase waits with no timeout. A story URL
+ // shows that story either way.
const [hidesStaleCache, setHidesStaleCache] = useState(
() => initialItemId == null && isFromCache && !isCacheFresh(type),
);
if (hidesStaleCache && (!isFromCache || !!error || !isOnline)) setHidesStaleCache(false);
+ useEffect(() => {
+ if (!hidesStaleCache) return;
+ const timer = setTimeout(() => setHidesStaleCache(false), STALE_CACHE_WAIT_MS);
+ return () => clearTimeout(timer);
+ }, [hidesStaleCache]);
// Prefetch other sections in background for instant tab switching
usePrefetchSections(type);