Skip to content
51 changes: 50 additions & 1 deletion e2e/mobile-swipe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
createFirebaseWsHandler,
FIREBASE_WS_PATTERN,
} from './fixtures/api-mocks';
import { ALGOLIA_API } from './fixtures/mock-data';
import { ALGOLIA_API, mockTopItemIds } from './fixtures/mock-data';
import {
expectActiveSwipePanelText,
getActiveSwipePanel,
Expand Down Expand Up @@ -393,6 +393,25 @@ test.describe('Mobile Swipe Viewer', () => {
await expect(page).toHaveURL(/\/item\/12345/, { timeout: 5000 });
});

test('switching feeds while the first one is still loading shows only the new feed', async ({ page }) => {
// Every Firebase read takes 1.5s, so Top's first page is still loading at the click.
await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ delayMs: 1500 }));
await page.goto('/#/');
await expect(page.getByTestId('swipe-container')).toBeVisible();
await expect(page.locator('[data-item-id]')).toHaveCount(0);

await page.getByRole('link', { name: 'best', exact: true }).click({ force: true });

await expect(page).toHaveURL(/\/item\/33001/, { timeout: 15000 });
await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', '33001');
await waitForSwipeReady(page, 3);
const ids = await page.locator('[data-item-id]').evaluateAll(
(els) => els.map((el) => Number(el.getAttribute('data-item-id'))),
);
expect(ids).toEqual(expect.arrayContaining([33001, 33002, 33003]));
expect(ids.filter((id) => mockTopItemIds.includes(id))).toEqual([]);
});

test('swipe uses replace — back navigates to previous section, not previous item', async ({ page }) => {
// Swipe-driven URL changes use replaceState (not pushState), so back
// exits the swipe viewer rather than stepping through items.
Expand Down Expand Up @@ -477,6 +496,14 @@ test.describe('Mobile Direct Item Access', () => {
await expect(page.getByText(/not found/i)).toBeVisible();
});

test('shows not found for an item id that is not a number', async ({ page }) => {
await page.goto('/#/item/abc');

await expect(page.getByRole('heading', { name: 'Item not found' })).toBeVisible();
await expect(page).toHaveTitle(/Item not found.*HackerTok/);
await expect(page.locator('[data-item-id]')).toHaveCount(0);
});

test('restores swipe position when navigating back from not-found item', async ({ page }) => {
// Regression: swiping away from index 0, then navigating to a non-existent item,
// then pressing back should restore the scroll position (not reset to index 0).
Expand Down Expand Up @@ -663,6 +690,28 @@ test.describe('Mobile Direct Item Access', () => {
await expect(page.getByText(/curious what side projects everyone is working on/i)).toBeVisible();
});

test('keeps the Ask HN body after visiting the author and going Back, and after a reload', async ({ page }) => {
// The saved swipe position stores stories without their body, and the
// restored copy is what the panel renders.
await page.goto('/#/ask');
await expect(page).toHaveURL(/\/item\/88888/);
const body = () => getActiveSwipePanel(page).getByText(/curious what side projects everyone is working on/i);
await expect(body()).toBeVisible();

await getActiveSwipePanel(page).locator('a[href^="#/user/"]').first().click();
await expect(page).toHaveURL(/\/user\//, { timeout: 5000 });

await page.goBack();
await expect(page).toHaveURL(/\/item\/88888/, { timeout: 5000 });
await expectActiveSwipePanelText(page, 'Ask HN: What are you working on?');
await expect(body()).toBeVisible();

await page.reload();
await expect(page).toHaveURL(/\/item\/88888/, { timeout: 5000 });
await expectActiveSwipePanelText(page, 'Ask HN: What are you working on?');
await expect(body()).toBeVisible();
});

test('navigating directly to a comment shows comment in swipe viewer', async ({ page }) => {
await page.goto('/#/item/1001');

Expand Down
38 changes: 38 additions & 0 deletions e2e/story-browsing.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,44 @@ test.describe('Item Browsing - Desktop Scroll Restoration', () => {
});
});

test.describe('Item Browsing - Desktop Back between feeds', () => {
test.use({ viewport: { width: 1280, height: 720 } });

test.beforeEach(async ({ page }) => {
await setupApiMocks(page);
});

test('does not repeat stories after going Back to a feed you opened a story from', async ({ page }, testInfo) => {
if (testInfo.project.name.startsWith('Mobile')) {
test.skip();
return;
}
const cards = page.locator('[data-testid="story-card"]');

await page.goto('/#/best');
await expect(cards).toHaveCount(3);

// Opening a story saves Best's session.
await page.locator('[data-story-id="33001"]').getByRole('link', { name: /comments/i }).click();
await expect(page).toHaveURL(/\/item\/33001/);
await page.goBack();
await expect(cards).toHaveCount(3);

await page.getByRole('link', { name: 'show', exact: true }).click();
await expect(page).toHaveURL(/\/show$/);
await expect(page.locator('[data-story-id="99999"]')).toBeVisible();

// The list stays mounted, so Back to Best resets it rather than remounting.
await page.goBack();
await expect(page).toHaveURL(/\/best$/);
// reset() drops the session and re-arms hasMore, so the end marker only
// returns once the load after it finishes.
await expect.poll(() => page.evaluate(() => sessionStorage.getItem('feed:session:best'))).toBeNull();
await expect(page.getByText("You've reached the end")).toBeVisible();
await expect(cards).toHaveCount(3);
});
});

/**
* Error handling tests use fixtureTest which provides errorMockedPage.
* This fixture sets up routes on browserContext BEFORE page creation,
Expand Down
55 changes: 46 additions & 9 deletions src/App.test.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen } from '@testing-library/react';
import { Routes, Route } from 'react-router';
import { screen, fireEvent } from '@testing-library/react';
import { Routes, Route, Link } from 'react-router';
import { render } from './test/test-utils';
import { MobileItemDetailWrapper } from './App';
import { MobileItemDetailWrapper, MobileStoryListWrapper } from './App';
import { saveSwipePosition } from './utils/swipePosition';
import { createStoryItem } from './test/factories';
import type { LocationState, StoryItem } from './types';
Expand All @@ -13,11 +13,16 @@ vi.mock('./hooks/useCanSwipe', () => ({ useCanSwipe: () => true }));

// Stub the heavy swipe viewers so we can assert *which* viewer the wrapper
// mounts (and with what props) without their data hooks / async state.
vi.mock('./components/SwipeStoryViewer', () => ({
SwipeStoryViewer: ({ type, initialItemId }: { type: string; initialItemId?: string }) => (
<div data-testid="feed-viewer" data-type={type} data-item={initialItemId ?? ''} />
),
}));
vi.mock('./components/SwipeStoryViewer', async () => {
const { useState } = await import('react');
return {
SwipeStoryViewer: function SwipeStoryViewer({ type, initialItemId }: { type: string; initialItemId?: string }) {
// Frozen at mount: a reused instance keeps the feed it was mounted for.
const [mountedType] = useState(type);
return <div data-testid="feed-viewer" data-type={type} data-mounted-type={mountedType} data-item={initialItemId ?? ''} />;
},
};
});
vi.mock('./components/SwipeDomainStoryViewer', () => ({
SwipeDomainStoryViewer: ({ domain, initialItemId }: { domain: string; initialItemId?: string }) => (
<div data-testid="domain-viewer" data-domain={domain} data-item={initialItemId ?? ''} />
Expand All @@ -37,7 +42,7 @@ vi.mock('./api/hn', async (importOriginal) => ({
fetchItemOnly: vi.fn(() => new Promise<never>(() => { /* never resolves */ })),
}));

function renderWrapper(id: number, state?: LocationState) {
function renderWrapper(id: number | string, state?: LocationState) {
return render(
<Routes>
<Route path="/item/:id" element={<MobileItemDetailWrapper />} />
Expand Down Expand Up @@ -134,3 +139,35 @@ describe('MobileItemDetailWrapper — viewer recovery (stateless reload)', () =>
expect(screen.queryByTestId('user-viewer')).toBeNull();
});
});

describe('MobileItemDetailWrapper — ids that are not numbers', () => {
it.each(['abc', '1.5', '-1'])('shows "Item not found" for /item/%s instead of a feed', (id) => {
renderWrapper(id, { from: 'top' });

expect(screen.getByRole('heading', { name: 'Item not found' })).toBeInTheDocument();
expect(screen.queryByTestId('feed-viewer')).toBeNull();
expect(screen.queryByTestId('swipe-container')).toBeNull();
expect(document.title).toMatch(/^Item not found/);
});
});

describe('MobileStoryListWrapper', () => {
it('mounts a new viewer when you switch feeds before the URL moves to a story', () => {
render(
<>
<Routes>
<Route path="/" element={<MobileStoryListWrapper type="top" />} />
<Route path="/best" element={<MobileStoryListWrapper type="best" />} />
</Routes>
<Link to="/best">best</Link>
</>,
);
expect(screen.getByTestId('feed-viewer')).toHaveAttribute('data-mounted-type', 'top');

fireEvent.click(screen.getByRole('link', { name: 'best' }));

const viewer = screen.getByTestId('feed-viewer');
expect(viewer).toHaveAttribute('data-type', 'best');
expect(viewer).toHaveAttribute('data-mounted-type', 'best');
});
});
30 changes: 25 additions & 5 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,16 @@ import { fetchItemOnly } from './api/hn';
import { readSwipePosition } from './utils/swipePosition';
import type { FeedType, LocationState } from './types';

function MobileStoryListWrapper({ type }: { type: FeedType }) {
// Exported for focused unit testing.
export function MobileStoryListWrapper({ type }: { type: FeedType }) {
const canSwipe = useCanSwipe();

if (canSwipe) {
return <SwipeStoryViewer type={type} />;
// key={type}: every feed route renders this wrapper, so a tab switch made
// before the viewer moves the URL to /item/:id (first load still running,
// or a failed one) would otherwise keep the previous feed's stories and
// let its in-flight page land in the new feed.
return <SwipeStoryViewer key={type} type={type} />;
}

return <StoryList type={type} />;
Expand Down Expand Up @@ -95,14 +100,20 @@ export function MobileItemDetailWrapper() {
// Newest snapshot taken on this story, read once (sticky for the wrapper's life);
// used only by Branch 4b to recover the viewer on a stateless reload.
const [recovered] = useState(() => readSwipePosition({ storyId: Number(id) }));

// HN ids are numeric. The swipe viewer can't fetch anything else, and its
// NaN id never matches the failed fetch, so it would show the Top feed.
if (!id || !/^\d+$/.test(id)) {
return <ItemNotFound />;
}

if (canSwipe) {
const state = location.state as LocationState | null;

// Branch 1: Known comment → SwipeCommentViewer immediately.
// Comments take priority over user/domain/from to match the header pill
// priority (comments > user > from).
if (state?.isComment && id) {
if (state?.isComment) {
return <SwipeCommentViewer initialCommentId={id} />;
}

Expand All @@ -117,18 +128,27 @@ export function MobileItemDetailWrapper() {
// from story viewers, so we skip the resolver's comment-vs-story fetch. Also
// fires for a fresh same-tab nav to a still-snapshotted id+viewer (intended:
// resume where you left off), not just back/reload.
if (recovered && id && recovered.storyId === Number(id)) {
if (recovered?.storyId === Number(id)) {
const viewer = renderSwipeViewer(recovered.viewer, id);
if (viewer) return viewer;
}

// Branch 5: Direct URL (no state) → resolve type first
return <MobileItemResolver id={id ?? ''} />;
return <MobileItemResolver id={id} />;
}

return <ItemDetail key={id} />;
}

function ItemNotFound() {
useDocumentTitle('Item not found');
return (
<div className="page-state-center-padded">
<StateView variant="not-found" action={{ label: 'Back to Home', to: '/' }} />
</div>
);
}

// Resolves item type for a direct URL hit on mobile (no `location.state`),
// then mounts the matching viewer.
function MobileItemResolver({ id }: { id: string }) {
Expand Down
18 changes: 13 additions & 5 deletions src/api/hn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -586,22 +586,30 @@ export async function prefetchItemComments(id: number | string, signal?: AbortSi
}

export async function fetchCommentsForItem(id: number | string, signal: AbortSignal | null = null): Promise<Comment[]> {
return (await fetchItemWithComments(id, signal)).comments;
}

/** The comment tree plus the item it hangs off, which the ordering reads anyway. */
export async function fetchItemWithComments(id: number | string, signal: AbortSignal | null = null): Promise<PrefetchResult> {
const itemId = Number(id);

if (signal?.aborted) {
throw new DOMException('Aborted', 'AbortError');
}

const [item, comments] = await Promise.all([
fetchFirebaseItem(itemId, signal ?? undefined),
fetchAllCommentsAlgolia(itemId, signal ?? undefined),
]);

if (signal?.aborted) {
throw new DOMException('Aborted', 'AbortError');
}

return buildOrderedCommentTree(comments, itemId, item?.kids, signal ?? undefined);

return {
item: normalizeFirebaseItem(item),
comments: await buildOrderedCommentTree(comments, itemId, item.kids, signal ?? undefined),
};
}

// Algolia /items/{id} returns the full nested children tree in one request.
Expand Down
22 changes: 22 additions & 0 deletions src/components/CommentArticle.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,28 @@ describe('CommentArticle', () => {
).toHaveAttribute('href', '/item/12345');
});

it('keeps the placeholder, not the "story" fallback, while the title is still loading', () => {
render(
<CommentArticle
comment={mockComment}
replies={[]}
itemId={12345}
itemTitle={null}
itemTitleLoading={true}
loading={false}
/>,
);

expect(screen.queryByText(/^story$/i)).not.toBeInTheDocument();
const article = screen.getByRole('article');
expect(article.querySelectorAll('.animate-pulse').length).toBeGreaterThan(0);
// The title fetch can hang until reconnect, so the way back to the
// story must not wait for it.
const link = screen.getByRole('link', { name: /^story$/i });
expect(link).toHaveAttribute('href', '/item/12345');
expect(link.querySelector('.animate-pulse')).not.toBeNull();
});

it('falls back to a generic "story" link when loading settles without a title', () => {
// Failure mode: parent fetch errored or returned a titleless item.
// Without the fallback, the skeleton would pulse forever and a
Expand Down
17 changes: 16 additions & 1 deletion src/components/CommentArticle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ interface CommentArticleProps {
replies: Comment[];
itemId: number | null;
itemTitle: string | null;
/** The thread title is still being fetched (after `loading` clears). */
itemTitleLoading?: boolean;
loading: boolean;
articleClassName?: string;
/** Story author for OP detection. */
Expand All @@ -32,6 +34,7 @@ export function CommentArticle({
replies,
itemId,
itemTitle,
itemTitleLoading = false,
loading,
articleClassName = 'mb-4',
storyAuthor = '',
Expand Down Expand Up @@ -76,7 +79,19 @@ export function CommentArticle({
<MessagesSquare aria-hidden className="size-3.5 shrink-0" />
<span className="truncate">{itemTitle}</span>
</Link>
) : itemId != null && !loading ? (
) : itemId != null && (loading || itemTitleLoading) ? (
// Title still on its way: already a link, because the title
// fetch has no timeout and can wait out a dropped connection.
<Link
to={`/item/${itemId}`}
state={{ isComment: false }}
className={metaPillClass}
aria-label="story"
>
<MessagesSquare aria-hidden className="size-3.5 shrink-0" />
<span className="inline-block h-3 w-48 bg-skeleton rounded animate-pulse align-middle" />
</Link>
) : itemId != null ? (
// Resolved-but-titleless fallback (parent fetch errored
// or returned without a title). Show a generic "story"
// link so the user still has a path back to the root
Expand Down
3 changes: 2 additions & 1 deletion src/components/CommentDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export function CommentDetailSkeleton() {
}

export function CommentDetail({ commentId, initialData }: CommentDetailProps) {
const { comment, replies, itemId, itemTitle, itemAuthor, loading, error, retry } = useCommentDetail(commentId, initialData);
const { comment, replies, itemId, itemTitle, itemTitleLoading, itemAuthor, loading, error, retry } = useCommentDetail(commentId, initialData);
const navigate = useNavigate();
const location = useLocation();
const locationState = location.state as LocationState | null;
Expand Down Expand Up @@ -99,6 +99,7 @@ export function CommentDetail({ commentId, initialData }: CommentDetailProps) {
replies={replies}
itemId={itemId}
itemTitle={itemTitle}
itemTitleLoading={itemTitleLoading}
loading={loading}
articleClassName="mb-6"
storyAuthor={itemAuthor ?? ''}
Expand Down
Loading
Loading