From 55f3f749fea433f692274587be680006bc1be19b Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:28:55 +0100 Subject: [PATCH 1/3] fix: stop the feed loading page after page in a background tab The list loaded the next page whenever its end-of-list marker was reported in view and nothing was loading. That report only changes when the browser's intersection observer runs, and it doesn't while the page isn't drawn. Network requests still finish, so in a background tab each page that landed turned `loading` back off and the list loaded again. In Chromium, scrolling to the bottom of the Top feed and switching tabs while the next page loaded went on to fetch 22 more pages in 40 seconds, 20 to 638 cards, with the scroll position unchanged. It stops only at the feed's 365-day limit, or the end of a domain's or user's results, or when the tab comes back. With the tab in front, one scroll to the bottom loaded two pages, as the check ran before the browser reported the marker's new position. The list now measures the marker again before each load and skips it when the marker is more than the preload margin below the viewport. A background tab loads only the page already in flight, and one scroll to the bottom loads one page. The check uses the layout viewport, which the observer measures against, through the root element's `clientHeight`. On a zoomed-in iPad, which shows this list when a trackpad or mouse is connected, `innerHeight` is only the part on screen: the check would skip a load the observer had asked for, and the list would stop loading. --- src/components/InfiniteStoryListPage.test.tsx | 110 +++++++++++++++++- src/components/InfiniteStoryListPage.tsx | 25 +++- 2 files changed, 127 insertions(+), 8 deletions(-) diff --git a/src/components/InfiniteStoryListPage.test.tsx b/src/components/InfiniteStoryListPage.test.tsx index 2f323c2..02adea9 100644 --- a/src/components/InfiniteStoryListPage.test.tsx +++ b/src/components/InfiniteStoryListPage.test.tsx @@ -1,5 +1,6 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { screen, fireEvent } from '@testing-library/react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { screen, fireEvent, act } from '@testing-library/react'; +import { useCallback, useState } from 'react'; import { Routes, Route } from 'react-router'; import { render } from '../test/test-utils'; import { createStoryItem } from '../test/factories'; @@ -241,6 +242,111 @@ describe('InfiniteStoryListPage', () => { }); }); + describe('load-more trigger', () => { + // The shared mock never reports anything in view. This one reports the + // end of the list in view once and never again, as in a background tab, + // whose observer doesn't run. + class InViewOnceObserver { + readonly thresholds = [0]; + readonly root = null; + readonly rootMargin = ''; + readonly scrollMargin = ''; + constructor(private readonly callback: IntersectionObserverCallback) {} + observe(target: Element) { + if (target.tagName === 'ARTICLE') return; // story cards + setTimeout(() => this.callback( + [{ target, isIntersecting: true, intersectionRatio: 1 } as unknown as IntersectionObserverEntry], + this as unknown as IntersectionObserver, + ), 0); + } + unobserve() { /* noop */ } + disconnect() { /* noop */ } + takeRecords() { return []; } + } + + const VIEWPORT_HEIGHT = 800; + const SharedObserver = globalThis.IntersectionObserver; + beforeEach(() => { + globalThis.IntersectionObserver = InViewOnceObserver; + vi.stubGlobal('innerHeight', VIEWPORT_HEIGHT); + vi.spyOn(document.documentElement, 'clientHeight', 'get').mockReturnValue(VIEWPORT_HEIGHT); + }); + afterEach(() => { + globalThis.IntersectionObserver = SharedObserver; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + const rectAt = (top: number) => + ({ x: 0, y: top, top, left: 0, right: 0, bottom: top, width: 0, height: 0, toJSON: () => ({}) }) as DOMRect; + + // Each page is one story, and the third page is the last. + function Feed({ onLoadMore, onPageLanded }: { onLoadMore: () => void; onPageLanded?: () => void }) { + const [stories, setStories] = useState(() => [createStoryItem({ id: 1, title: 'Story 1' })]); + const [loading, setLoading] = useState(false); + const loadMore = useCallback(async () => { + onLoadMore(); + setLoading(true); + await new Promise(resolve => setTimeout(resolve, 10)); + onPageLanded?.(); + setStories(prev => [...prev, createStoryItem({ id: prev.length + 1, title: `Story ${prev.length + 1}` })]); + setLoading(false); + }, [onLoadMore, onPageLanded]); + + return ( + + ); + } + + function renderFeed(props: { onLoadMore: () => void; onPageLanded?: () => void }) { + return render( + + } /> + , + ); + } + + it('keeps loading pages while the end of the list stays in view', async () => { + const onLoadMore = vi.fn(); + + renderFeed({ onLoadMore }); + + expect(await screen.findByRole('link', { name: 'Story 4' })).toBeInTheDocument(); + expect(onLoadMore).toHaveBeenCalledTimes(3); + }); + + it('stops once a page pushes the end of the list out of view, though the observer has not said so', async () => { + const onLoadMore = vi.fn(); + const getRect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect'); + + renderFeed({ + onLoadMore, + onPageLanded: () => getRect.mockReturnValue(rectAt(VIEWPORT_HEIGHT + 1000)), + }); + + expect(await screen.findByRole('link', { name: 'Story 2' })).toBeInTheDocument(); + await act(() => new Promise(resolve => setTimeout(resolve, 50))); + expect(onLoadMore).toHaveBeenCalledTimes(1); + expect(screen.queryByRole('link', { name: 'Story 3' })).not.toBeInTheDocument(); + }); + + it('keeps loading on an iPad zoomed in to the end of the list', async () => { + // Zoomed in 2×, iPad Safari's innerHeight is the half of the layout + // viewport on screen, here the bottom half, where the end of the list is. + const onLoadMore = vi.fn(); + vi.stubGlobal('innerHeight', VIEWPORT_HEIGHT / 2); + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(rectAt(VIEWPORT_HEIGHT - 100)); + + renderFeed({ onLoadMore }); + + expect(await screen.findByRole('link', { name: 'Story 4' })).toBeInTheDocument(); + expect(onLoadMore).toHaveBeenCalledTimes(3); + }); + }); + describe('storyCardExtras forwarding', () => { it('forwards fromUser into the story card byline so links carry the origin', () => { const stories = [ diff --git a/src/components/InfiniteStoryListPage.tsx b/src/components/InfiniteStoryListPage.tsx index b6c45ee..323eec3 100644 --- a/src/components/InfiniteStoryListPage.tsx +++ b/src/components/InfiniteStoryListPage.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect } from 'react'; +import { useCallback, useEffect, useRef } from 'react'; import { useInView } from 'react-intersection-observer'; import { StoryCard } from './StoryCard'; import { Spinner } from './Spinner'; @@ -44,6 +44,8 @@ interface InfiniteStoryListPageProps { failTitle?: string; } +const PRELOAD_MARGIN_PX = 200; + /** * Shared infinite-scroll story list. Owns cascade slots, * load-more trigger, auto-retry, and PageStage. @@ -61,8 +63,13 @@ export function InfiniteStoryListPage({ const { ref, inView } = useInView({ threshold: 0, - rootMargin: '200px', + rootMargin: `${PRELOAD_MARGIN_PX}px`, }); + const sentinelRef = useRef(null); + const setSentinel = useCallback((node: HTMLDivElement | null) => { + sentinelRef.current = node; + ref(node); + }, [ref]); const { isOnline } = useNetworkStatus(); const { isRetrying, resetRetry } = useAutoRetry({ @@ -72,9 +79,15 @@ export function InfiniteStoryListPage({ }); useEffect(() => { - if (inView && !loading && hasMore && !error) { - void loadMore().catch(() => { /* error state set internally */ }); - } + if (!inView || loading || !hasMore || error) return; + // `inView` only changes when the observer reports, and it doesn't while + // the page isn't drawn (a background tab): after a page lands it can + // still be true with the end of the list far below. The observer measures + // against the layout viewport, `clientHeight`: on a zoomed-in iPad, + // `innerHeight` is only the part on screen. + const top = sentinelRef.current?.getBoundingClientRect().top; + if (top !== undefined && top > document.documentElement.clientHeight + PRELOAD_MARGIN_PX) return; + void loadMore().catch(() => { /* error state set internally */ }); }, [inView, loading, hasMore, error, loadMore]); const retryLoadMore = useCallback(() => { @@ -138,7 +151,7 @@ export function InfiniteStoryListPage({ {hasMore && stories.length > 0 && ( -
+
{loading && }
)} From 590ed74b6258a1cec38d3a9799783f78fb469d1e Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:28:55 +0100 Subject: [PATCH 2/3] fix: show a deleted comment's replies on a phone The phone's full-screen comment showed "Comment deleted", with nothing else, for any comment with no author and no text, even one with replies. The desktop page shows the same comment under a [deleted] byline, with its parent and story links and its replies. Tapping "parent" on reply 50343707 on a phone led to such a dead end for comment 50343637. The phone now shows the dead end only when the comment has no replies and none are still loading. Otherwise it renders the comment as the desktop page does. --- src/components/FullScreenComment.test.tsx | 16 ++++++++++++++++ src/components/FullScreenComment.tsx | 4 +++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/components/FullScreenComment.test.tsx b/src/components/FullScreenComment.test.tsx index 51fa5f7..df83d7d 100644 --- a/src/components/FullScreenComment.test.tsx +++ b/src/components/FullScreenComment.test.tsx @@ -172,6 +172,22 @@ describe('FullScreenComment', () => { expect(await screen.findByText('Comment deleted')).toBeInTheDocument(); expect(screen.queryByText('Failed to load comment')).not.toBeInTheDocument(); }); + + it('shows a deleted comment with replies as [deleted], with its replies', async () => { + mockMissingFromAlgolia( + 8888, + { id: 8888, type: 'comment', deleted: true, parent: 12345, kids: [8889], time: now - 600 }, + [{ id: 8889, type: 'comment', author: 'dang', text: 'Still worth reading.', created_at_i: now - 300, parent_id: 8888, story_id: 12345, children: [] }], + ); + + render(); + + expect(await screen.findByText('[deleted]')).toBeInTheDocument(); + expect(screen.getByText('dang')).toBeInTheDocument(); + expect(screen.getByText('Still worth reading.')).toBeInTheDocument(); + expect(await screen.findByRole('link', { name: 'Rust Is the Future of JavaScript Infrastructure' })).toHaveAttribute('href', '/item/12345'); + expect(screen.queryByText('Comment deleted')).not.toBeInTheDocument(); + }); }); it('shows "No replies yet" for comment with no children', async () => { diff --git a/src/components/FullScreenComment.tsx b/src/components/FullScreenComment.tsx index ef26331..b85f9dd 100644 --- a/src/components/FullScreenComment.tsx +++ b/src/components/FullScreenComment.tsx @@ -74,7 +74,9 @@ export function FullScreenComment({ commentId, onAuthorLoaded }: FullScreenComme // CRITICAL `!loading` gate: during cold load `comment` is null but // we want PageStage to show the skeleton, not flash deleted-state. - if (!loading && (!comment || (!comment.author && !comment.text))) { + // A deleted comment with replies still shows them, under a [deleted] byline. + const isDeletedLeaf = !!comment && !comment.author && !comment.text && replies.length === 0 && !moreRepliesLoading; + if (!loading && (!comment || isDeletedLeaf)) { return (
From c4d2a0f6f3d128f43b9b85cc24424c5a12c4f689 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:28:55 +0100 Subject: [PATCH 3/3] perf: read an item's cached thread once, when its view mounts useItemWithComments read the item cache in its body, which parses the cached thread from localStorage on every render, though the result only seeds the initial state. Over five swipes on a phone-speed CPU, those reads parsed 3.3 million characters, about 18ms. It now reads the cache once, in a state initializer. --- src/hooks/useItemWithComments.test.tsx | 16 ++++++++++++++++ src/hooks/useItemWithComments.ts | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/hooks/useItemWithComments.test.tsx b/src/hooks/useItemWithComments.test.tsx index e1be881..d153623 100644 --- a/src/hooks/useItemWithComments.test.tsx +++ b/src/hooks/useItemWithComments.test.tsx @@ -82,6 +82,22 @@ describe('useItemWithComments', () => { expect(result.current.comments).toEqual(testComments); }); + it('reads the cache when it mounts, not on every render', () => { + setCachedItem(12345, testItem, testComments, 3); + const cached = localStorage.getItem(`${ITEM_CACHE_KEY_PREFIX}12345`); + const parse = vi.spyOn(JSON, 'parse'); + const cacheReads = () => parse.mock.calls.filter(([text]) => text === cached).length; + + const { rerender } = renderHook(() => useItemWithComments(12345)); + const readsOnMount = cacheReads(); + rerender(); + rerender(); + rerender(); + + expect(readsOnMount).toBeGreaterThan(0); + expect(cacheReads()).toBe(readsOnMount); + }); + it('accepts initialItem prop to skip item fetch', async () => { const { result } = renderHook(() => useItemWithComments(12345, { initialItem: testItem }) diff --git a/src/hooks/useItemWithComments.ts b/src/hooks/useItemWithComments.ts index b32d4b7..f45380d 100644 --- a/src/hooks/useItemWithComments.ts +++ b/src/hooks/useItemWithComments.ts @@ -57,7 +57,7 @@ function withFetchedFields(item: Item | null | undefined, fetched: Item): Item | } export function useItemWithComments(itemId: number | string, { initialItem = null, skipOrderingCompletion = false, isPriority = true, deferComments = false }: UseItemWithCommentsOptions = {}): UseItemWithCommentsResult { - const initialCache = getCachedItem(itemId); + const [initialCache] = useState(() => getCachedItem(itemId)); // Lazy initialization from cache or initialItem for instant render const [item, setItem] = useState(() => withText(initialItem, initialCache?.item) ?? initialCache?.item ?? null);