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
File renamed without changes.
11 changes: 11 additions & 0 deletions e2e/csp.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,15 @@ test.describe('Content-Security-Policy', () => {
});
expect(await readViolations(page)).toEqual([]);
});

test('covers the 404.html redirect shell', async ({ page, request }) => {
// Pages serves 404.html for every unknown path, so it is a second entry
// document and needs the same policy.
const html = await (await request.get('/404.html')).text();
expect(html).toMatch(/<meta http-equiv="Content-Security-Policy" content="[^"]*script-src 'self' 'sha256-/);

// The redirect is an inline script, so it runs only if its hash is allowed.
await page.goto('/404.html?ref=1');
await expect(page).toHaveURL(/\/#\/404\.html\?ref=1$/);
});
});
27 changes: 26 additions & 1 deletion e2e/item-detail.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { test, expect } from '@playwright/test';
import { setupApiMocks } from './fixtures/api-mocks';
import { createFirebaseWsHandler, FIREBASE_WS_PATTERN, setupApiMocks } from './fixtures/api-mocks';
import { expectLocatorCenteredBetweenChrome, setOfflineAndWaitForBar } from './fixtures/layout-helpers';

test.describe('Item Detail', () => {
test.beforeEach(async ({ page }) => {
Expand Down Expand Up @@ -265,3 +266,27 @@ test.describe('Item Detail - Desktop', () => {
await expect(page.getByText('SQLite Does Not Do Full FSYNC by Default').first()).toBeVisible();
});
});

test.describe('Item Detail - Poll option on a phone', () => {
test.use({ viewport: { width: 375, height: 667 }, hasTouch: true });

test.beforeEach(async ({ page }) => {
await setupApiMocks(page);
// Registered last, so it wins over setupApiMocks' handler.
await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({
itemOverrides: {
126810: { id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, poll: 126809, type: 'pollopt' },
},
}));
});

test('centers the notice between the header and the offline bar', async ({ page, context }) => {
await page.goto('/#/item/126810');
const heading = page.getByRole('heading', { name: "Poll options aren't supported" });
await expect(heading).toBeVisible({ timeout: 10_000 });

await setOfflineAndWaitForBar(page, context);

await expectLocatorCenteredBetweenChrome(heading.locator('xpath=..'));
});
});
6 changes: 6 additions & 0 deletions src/api/hn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -941,6 +941,12 @@ describe('hn API utilities', () => {

expect(result.type !== 'job' ? result.commentCount : 0).toBe(137);
});

it('keeps a poll option typed as one', async () => {
vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, type: 'pollopt' });

expect((await fetchItemOnly(126810)).type).toBe('pollopt');
});
});

describe('error handling', () => {
Expand Down
8 changes: 7 additions & 1 deletion src/api/hn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,10 @@ function normalizeFirebaseItem(fbItem: FirebaseItem): Item {

// Firebase doesn't distinguish ask/show — they're all type='story'.
// Only the Algolia path (via _tags) can set 'ask'/'show' sub-types.
// A poll reads as a story, without its options.
return {
...base,
type: 'story' as const,
type: fbItem.type === 'pollopt' ? 'pollopt' : 'story',
title: fbItem.title ?? '',
url: fbItem.url,
text: fbItem.text,
Expand Down Expand Up @@ -231,6 +232,11 @@ export async function fetchNewStories(offset = 0, limit = 30) {
};
}

/** A poll option has no title or comments, so its page shows a notice instead. */
export function isPollOption(item: Item): item is StoryItem & { type: 'pollopt' } {
return item.type === 'pollopt';
}

function normalizeFirebaseToStoryItem(fb: FirebaseItem): StoryItem {
return {
id: fb.id,
Expand Down
4 changes: 2 additions & 2 deletions src/components/FullScreenComment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function FullScreenComment({ commentId, onAuthorLoaded }: FullScreenComme

if (error && !isRetrying) {
return (
<div className="full-screen-item flex items-center justify-center min-h-[50vh]">
<div className="full-screen-state">
<StateView variant="error" title="Failed to load comment" description={error} action={{ label: 'Retry', onClick: () => void retry().catch(() => { /* error state set internally */ }) }} />
</div>
);
Expand All @@ -78,7 +78,7 @@ export function FullScreenComment({ commentId, onAuthorLoaded }: FullScreenComme
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]">
<div className="full-screen-state">
<StateView variant="deleted" />
</div>
);
Expand Down
8 changes: 8 additions & 0 deletions src/components/FullScreenItem.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,12 @@ describe('FullScreenItem', () => {
});
});
});

it('says a poll option is not supported instead of showing it', async () => {
vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, type: 'pollopt' });
render(<FullScreenItem itemId={126810} />);

expect(await screen.findByRole('heading', { name: "Poll options aren't supported" })).toBeInTheDocument();
expect(screen.queryByRole('heading', { level: 1 })).not.toBeInTheDocument();
});
});
14 changes: 12 additions & 2 deletions src/components/FullScreenItem.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { useItemWithComments } from '../hooks/useItemWithComments';
import { useNetworkStatus } from '../hooks/useNetworkStatus';
import { useAutoRetry } from '../hooks/useAutoRetry';
import { isPollOption } from '../api/hn';
import { CommentSkeletonTree } from '../components';
import { CommentsSection } from './CommentsSection';
import { FullScreenChrome } from './FullScreenChrome';
import { ItemArticle } from './ItemArticle';
import { PageStage } from './PageStage';
import { PollOptionNotSupported } from './PollOptionNotSupported';
import { StateView } from './StateView';
import type { StoryItem } from '../types';

Expand Down Expand Up @@ -71,7 +73,7 @@ export function FullScreenItem({ itemId, initialItem, isPriority = true, deferCo

if (error && !isRetrying) {
return (
<div className="full-screen-item flex items-center justify-center min-h-[50vh]">
<div className="full-screen-state">
<StateView
variant={isNotFound ? 'not-found' : 'error'}
title={isNotFound ? undefined : 'Failed to load item'}
Expand All @@ -88,12 +90,20 @@ export function FullScreenItem({ itemId, initialItem, isPriority = true, deferCo

if (!itemLoading && (!item || item.type === 'comment')) {
return (
<div className="full-screen-item flex items-center justify-center min-h-[50vh]">
<div className="full-screen-state">
<StateView variant="not-found" />
</div>
);
}

if (!itemLoading && item && isPollOption(item)) {
return (
<div className="full-screen-state">
<PollOptionNotSupported />
</div>
);
}

return (
<FullScreenChrome>
{/* `triggerWhen={isPriority}` holds the entrance animation
Expand Down
22 changes: 22 additions & 0 deletions src/components/PollOptionNotSupported.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { StateView } from './StateView';

interface PollOptionNotSupportedProps {
action?: { label: string; to?: string; onClick?: () => void };
className?: string;
}

/** The notice's heading, and the tab title while it shows. */
export const POLL_OPTION_TITLE = "Poll options aren't supported";

/** Shown in place of a poll option (see `isPollOption`). */
export function PollOptionNotSupported({ action, className }: PollOptionNotSupportedProps) {
return (
<StateView
variant="empty"
title={POLL_OPTION_TITLE}
description="This item is an option in a Hacker News poll. HackerTok shows polls, but not their options."
action={action}
className={className}
/>
);
}
6 changes: 3 additions & 3 deletions src/components/StateView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ function EmptyScene({ compact }: { compact?: boolean }) {
return (
<div className="sv-scene" style={{ width: 120, height: 120, position: 'relative', animation: 'sv-breathe 4s ease-in-out infinite' }}>
{/* Rising thought dots — start at box opening (y≈55) and float above */}
<div className="absolute rounded-full bg-accent" style={{ width: 4, height: 4, top: 53, left: 48, animation: 'sv-fade-up 3s ease-out infinite' }} />
<div className="absolute rounded-full bg-accent" style={{ width: 4, height: 4, top: 53, left: 56, animation: 'sv-fade-up 3s ease-out infinite 0.8s' }} />
<div className="absolute rounded-full bg-accent" style={{ width: 4, height: 4, top: 53, left: 64, animation: 'sv-fade-up 3s ease-out infinite 1.6s' }} />
<div className="absolute rounded-full bg-accent" style={{ width: 4, height: 4, top: 53, left: 50, animation: 'sv-fade-up 3s ease-out infinite' }} />
<div className="absolute rounded-full bg-accent" style={{ width: 4, height: 4, top: 53, left: 58, animation: 'sv-fade-up 3s ease-out infinite 0.8s' }} />
<div className="absolute rounded-full bg-accent" style={{ width: 4, height: 4, top: 53, left: 66, animation: 'sv-fade-up 3s ease-out infinite 1.6s' }} />
{/* Floating particles */}
<div className="absolute rounded-full bg-accent opacity-35" style={{ width: 5, height: 5, top: 5, right: 15, animation: 'sv-roam-2 9s ease-in-out infinite' }} />
<div className="absolute rounded-full bg-muted-foreground opacity-35" style={{ width: 3, height: 3, bottom: 10, left: 10, animation: 'sv-roam-1 7s ease-in-out infinite 1s' }} />
Expand Down
21 changes: 21 additions & 0 deletions src/components/SwipeStoryViewer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,27 @@ describe('SwipeStoryViewerCore', () => {

expect(title.closest('div')).toHaveClass('swipe-state-center');
});

it("titles the tab after the notice on a poll option's panel", async () => {
vi.mocked(fetchItemOnly).mockResolvedValueOnce(
createStoryItem({ id: 126810, type: 'pollopt', title: '', url: undefined, text: 'Yes, ban them' }),
);

render(
<SwipeStoryViewerCore
stories={[]}
loading={false}
error={null}
hasMore={false}
loadMore={vi.fn().mockResolvedValue(undefined)}
initialItemId="126810"
backState={{ from: 'top' }}
/>,
);

await waitFor(() => expect(activePanel()?.getAttribute('data-item-id')).toBe('126810'));
expect(document.title).toBe("Poll options aren't supported | HackerTok");
});
});

describe('SwipeStoryViewerCore — mount-snapshot filtering', () => {
Expand Down
6 changes: 4 additions & 2 deletions src/components/SwipeStoryViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@ import { usePrefetchSections } from '../hooks/usePrefetchSections';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useNetworkStatus } from '../hooks/useNetworkStatus';
import { useAutoRetry } from '../hooks/useAutoRetry';
import { fetchItemOnly, NotFoundError } from '../api/hn';
import { fetchItemOnly, isPollOption, 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';
import { POLL_OPTION_TITLE } from './PollOptionNotSupported';
import { StateView } from './StateView';
import type { StoryItem, FeedType, LocationState } from '../types';

Expand Down Expand Up @@ -222,6 +223,7 @@ export function SwipeStoryViewerCore({
? (isInjectedNotFound ? (isNonStoryError ? 'Item not available' : 'Item not found') : 'Failed to load item')
: (error && mergedStories.length === 0) ? 'Failed to load item'
: isOnline && isAtEndError && giveUp ? 'Failed to load item'
: currentStory && isPollOption(currentStory) ? POLL_OPTION_TITLE
: (currentStory?.title || titleFallback);
useDocumentTitle(documentTitle);

Expand Down Expand Up @@ -720,7 +722,7 @@ export function SwipeStoryViewerCore({
`.active` sets display:block, so the centering lives on an inner box. */}
{showErrorPanel && (
<div className="swipe-snap-panel" data-testid="swipe-panel">
<div className="full-screen-item flex items-center justify-center min-h-[50vh]">
<div className="full-screen-state">
<StateView
variant="error"
title="Failed to load item"
Expand Down
1 change: 1 addition & 0 deletions src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ export { ItemArticle } from './ItemArticle';
export { FullScreenComment, FullScreenCommentSkeleton, FullScreenCommentSkeletonPanel } from './FullScreenComment';
export { CommentsSection } from './CommentsSection';
export { StateView } from './StateView';
export { PollOptionNotSupported, POLL_OPTION_TITLE } from './PollOptionNotSupported';
export { NetworkStatusBar } from './NetworkStatusBar';
export { ShareButton } from './ShareButton';
10 changes: 10 additions & 0 deletions src/hooks/useInfiniteStories.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,16 @@ describe('useInfiniteStories', () => {
expect(ids).toHaveLength(50);
});

it('keeps a stale cache stale when saving the session', () => {
const hourAgo = Date.now() - 60 * 60 * 1000;
setCachedFeed('top', [1, 2, 3].map(id => createStoryItem({ id })), hourAgo);
const { result } = renderHook(() => useInfiniteStories('top'));

act(() => result.current.saveSessionState(0));

expect(getCachedFeed('top')).toMatchObject({ timestamp: hourAgo, isStale: true });
});

describe('revalidation', () => {
function seedStaleFeed(type: FeedType) {
// A cached order the live ranking (1, 2, 3, …) has moved on from.
Expand Down
15 changes: 11 additions & 4 deletions src/hooks/useInfiniteStories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,10 @@ export function useInfiniteStories(type: FeedType = 'top') {
hasStaleCacheRef.current = false;
}

positionRef.current = 1; // Next load will be yesterday
// Next load will be yesterday. By design, today's stories ranked
// past the top 20 are never shown: the feed is HN's front page,
// then each earlier (UTC) day's front page from Algolia.
positionRef.current = 1;
} else {
let attempts = 0;
const maxAttempts = 5; // Try up to 5 days if current day has no stories
Expand Down Expand Up @@ -371,9 +374,13 @@ export function useInfiniteStories(type: FeedType = 'top') {
phase: phaseRef.current,
});

// Also update the stories cache with current full list (for session reconstruction)
if (stories.length > 0) {
setCachedFeed(type, stories);
// Also update the stories cache with current full list (for session
// reconstruction). Keep the cached timestamp: the list is no newer than
// its last fetch, and re-stamping it would let a stale list pass as fresh.
// No cache entry means the list is over a day old, or storage failed.
const fetchedAt = getCachedFeed(type)?.timestamp;
if (stories.length > 0 && fetchedAt !== undefined) {
setCachedFeed(type, stories, fetchedAt);
}
}, [type, stories, hasMore]);

Expand Down
34 changes: 34 additions & 0 deletions src/hooks/useItemWithComments.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,18 @@ describe('useItemWithComments', () => {
expect(getCachedItem(12345)?.item).toEqual(testItem);
});

it('takes the poll option type from the revalidation over a copy cached as a story', async () => {
vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ id: 12345, text: 'Yes', by: 'pg', score: 30, time: mockFirebaseStory.time, type: 'pollopt' });
seedStaleCache();

const { result } = renderHook(() => useItemWithComments(12345));

await waitFor(() => {
expect(result.current.item?.type).toBe('pollopt');
});
expect(getCachedItem(12345)?.item.type).toBe('pollopt');
});

it('fetches when cache has no comments', async () => {
const CACHE_KEY = `${ITEM_CACHE_KEY_PREFIX}12345`;
const partialData = {
Expand Down Expand Up @@ -1031,6 +1043,28 @@ describe('useItemWithComments', () => {
});
});

describe('a poll option', () => {
it('fetches no comments, and releases priority once it loads', async () => {
const readItem = vi.spyOn(hnSdk, 'readItem').mockResolvedValue({
id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, type: 'pollopt',
});
let commentSearches = 0;
server.use(
http.get(`${ALGOLIA_API}/search`, () => {
commentSearches++;
return HttpResponse.json({ hits: [], nbPages: 0 });
}),
);

const { result } = renderHook(() => useItemWithComments(126810));

await waitFor(() => expect(result.current.item?.type).toBe('pollopt'));
expect(isPriorityFetchActive()).toBe(false);
expect(readItem).toHaveBeenCalledTimes(1);
expect(commentSearches).toBe(0);
});
});

describe('refresh loading states', () => {
it('sets itemLoading and commentsLoading to true during refresh', async () => {
const { result } = renderHook(() =>
Expand Down
Loading