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 (
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 && }
)}
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);