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: 1 addition & 1 deletion e2e/fixtures/mock-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
24 changes: 13 additions & 11 deletions e2e/mobile-swipe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('/#/');
Expand Down Expand Up @@ -938,16 +939,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 }) => {
Expand Down
14 changes: 14 additions & 0 deletions src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ vi.mock('./components/SwipeUserSubmissionsViewer', () => ({
<div data-testid="user-viewer" data-username={username} data-item={initialItemId ?? ''} />
),
}));
vi.mock('./pages/ItemDetail', () => ({
ItemDetail: () => <div data-testid="item-detail" />,
}));

// 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
Expand Down Expand Up @@ -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', () => {
Expand Down
22 changes: 12 additions & 10 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 <ItemDetail key={id} />;
if (resolvedType === 'story') return renderSwipeViewer({ from: 'top' }, id, feedEntries);
return <MobileItemResolverSkeleton />;
}

Expand Down Expand Up @@ -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<string | null>(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(() => {
Expand All @@ -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() {
Expand Down
16 changes: 14 additions & 2 deletions src/api/hn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
32 changes: 27 additions & 5 deletions src/api/hn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number | null> {
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.
Expand Down Expand Up @@ -789,8 +801,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<Comment[]> {
if (item.story_id == null) return normalizeAlgoliaItemChildren(item.children ?? []);
Expand All @@ -800,15 +813,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[] {
Expand Down
73 changes: 69 additions & 4 deletions src/components/SwipeStoryViewer.test.tsx
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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';

Expand All @@ -30,8 +30,11 @@ vi.mock('./FullScreenItem', () => ({
vi.mock('../api/hn', async (importOriginal) => ({
...(await importOriginal<typeof HnApi>()),
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 }));
Expand Down Expand Up @@ -749,4 +752,66 @@ describe('SwipeStoryViewerCore — viewed marks on landing', () => {

expect(markedIds()).toEqual([1]);
});
});
});

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,
}));
});

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(<SwipeStoryViewer type="top" />);

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(<SwipeStoryViewer type="top" />);

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(<SwipeStoryViewer type="top" />);
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');
});

it('shows the cache after three seconds when the refresh stalls online', () => {
vi.useFakeTimers();
vi.mocked(fetchTopStories).mockReturnValue(new Promise(() => { /* never resolves */ }));
render(<SwipeStoryViewer type="top" />);

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');
});
});
25 changes: 23 additions & 2 deletions src/components/SwipeStoryViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -738,9 +739,29 @@ interface SwipeStoryViewerProps {
initialItemId?: string;
}

const NO_STORIES: StoryItem[] = [];
const STALE_CACHE_WAIT_MS = 3000;

/** 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, 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);
Expand All @@ -759,8 +780,8 @@ export function SwipeStoryViewer({ type, initialItemId }: SwipeStoryViewerProps)

return (
<SwipeStoryViewerCore
stories={stories}
loading={loading}
stories={hidesStaleCache ? NO_STORIES : stories}
loading={loading || hidesStaleCache}
error={error}
hasMore={hasMore}
loadMore={loadMore}
Expand Down
Loading