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
16 changes: 16 additions & 0 deletions src/components/FullScreenComment.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<FullScreenComment commentId={8888} />);

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 () => {
Expand Down
4 changes: 3 additions & 1 deletion src/components/FullScreenComment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<div className="full-screen-item flex items-center justify-center min-h-[50vh]">
<StateView variant="deleted" />
Expand Down
110 changes: 108 additions & 2 deletions src/components/InfiniteStoryListPage.test.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 (
<InfiniteStoryListPage
result={{ stories, loading, error: null, hasMore: stories.length < 4, loadMore }}
resetKey="test-key"
/>
);
}

function renderFeed(props: { onLoadMore: () => void; onPageLanded?: () => void }) {
return render(
<Routes>
<Route path="/" element={<Feed {...props} />} />
</Routes>,
);
}

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 = [
Expand Down
25 changes: 19 additions & 6 deletions src/components/InfiniteStoryListPage.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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.
Expand All @@ -61,8 +63,13 @@ export function InfiniteStoryListPage({

const { ref, inView } = useInView({
threshold: 0,
rootMargin: '200px',
rootMargin: `${PRELOAD_MARGIN_PX}px`,
});
const sentinelRef = useRef<HTMLDivElement | null>(null);
const setSentinel = useCallback((node: HTMLDivElement | null) => {
sentinelRef.current = node;
ref(node);
}, [ref]);

const { isOnline } = useNetworkStatus();
const { isRetrying, resetRetry } = useAutoRetry({
Expand All @@ -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(() => {
Expand Down Expand Up @@ -138,7 +151,7 @@ export function InfiniteStoryListPage({
</div>

{hasMore && stories.length > 0 && (
<div ref={ref} className="py-4">
<div ref={setSentinel} className="py-4">
{loading && <Spinner />}
</div>
)}
Expand Down
16 changes: 16 additions & 0 deletions src/hooks/useItemWithComments.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useItemWithComments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading