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
5 changes: 4 additions & 1 deletion src/components/AuthorByline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import { metaPillClass } from '../lib/classes';

/**
* OP badge wrapper — badge as sibling keeps link's accessible name clean.
* Screen readers get "Original poster" as text: `aria-label` isn't allowed
* on a plain span, so the visible "OP" is hidden from them instead.
*/
export function OpWrap({ children }: { children: ReactNode }) {
return (
<span className="inline-flex items-center gap-1.5">
{children}
<span className="op-badge" data-is-op="true" aria-label="Original poster">
<span className="op-badge" data-is-op="true" aria-hidden="true">
OP
</span>
<span className="sr-only">Original poster</span>
</span>
);
}
Expand Down
10 changes: 5 additions & 5 deletions src/components/Comment.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,15 @@ describe('Comment', () => {
it('renders an OP badge when storyAuthor matches comment.author', () => {
render(<Comment comment={mockComment} storyAuthor="testuser" />);

// aria-label="Original poster" for screen readers, visible "OP" for sighted users.
expect(screen.getByLabelText('Original poster')).toBeInTheDocument();
expect(screen.getByText('OP')).toBeInTheDocument();
// Screen readers get "Original poster" as text; the visible "OP" is hidden from them.
expect(screen.getByText('Original poster')).toBeInTheDocument();
expect(screen.getByText('OP')).toHaveAttribute('aria-hidden', 'true');
});

it('does not render an OP badge when storyAuthor differs from comment.author', () => {
render(<Comment comment={mockComment} storyAuthor="someone-else" />);

expect(screen.queryByLabelText('Original poster')).not.toBeInTheDocument();
expect(screen.queryByText('Original poster')).not.toBeInTheDocument();
expect(screen.queryByText('OP')).not.toBeInTheDocument();
});

Expand All @@ -150,7 +150,7 @@ describe('Comment', () => {
});
render(<Comment comment={comment} storyAuthor={storyAuthor} />);

expect(screen.queryByLabelText('Original poster')).not.toBeInTheDocument();
expect(screen.queryByText('Original poster')).not.toBeInTheDocument();
},
);

Expand Down
6 changes: 3 additions & 3 deletions src/components/CommentArticle.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -225,14 +225,14 @@ describe('CommentArticle', () => {
it('renders an OP badge when storyAuthor matches comment.author', () => {
renderArticle({ storyAuthor: 'patio11' });

expect(screen.getByLabelText('Original poster')).toBeInTheDocument();
expect(screen.getByText('OP')).toBeInTheDocument();
expect(screen.getByText('Original poster')).toBeInTheDocument();
expect(screen.getByText('OP')).toHaveAttribute('aria-hidden', 'true');
});

it('does not render an OP badge when storyAuthor differs from comment.author', () => {
renderArticle({ storyAuthor: 'someone-else' });

expect(screen.queryByLabelText('Original poster')).not.toBeInTheDocument();
expect(screen.queryByText('Original poster')).not.toBeInTheDocument();
expect(screen.queryByText('OP')).not.toBeInTheDocument();
});

Expand Down
3 changes: 2 additions & 1 deletion src/components/StoryCard.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,8 @@ describe('StoryCard', () => {

it("keeps the opened story's prefetch running after the list unmounts and cancels the rest", async () => {
const prefetch = vi.spyOn(hn, 'prefetchItemComments').mockReturnValue(new Promise(() => { /* in flight */ }));
const other = createStoryItem({ id: 222 });
// A fixed count: a random one like 142 would also match /42 comments/.
const other = createStoryItem({ id: 222, commentCount: 7 });
render(
<Routes>
<Route path="/" element={<><StoryCard story={mockStory} /><StoryCard story={other} index={1} /></>} />
Expand Down
11 changes: 11 additions & 0 deletions src/components/SwipeStoryViewer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
VIEWED_DETAIL_TIMES_KEY,
} from '../utils/viewedItems';
import { saveSwipePosition, readSwipePosition } from '../utils/swipePosition';
import { saveListSessionState } from '../utils/itemCache';
import { fetchItemOnly, fetchTopStories } from '../api/hn';
import type * as HnApi from '../api/hn';
import type { LocationState } from '../types';
Expand Down Expand Up @@ -833,6 +834,16 @@ describe('SwipeStoryViewer — opening a feed from an old cache', () => {
await waitFor(() => expect(activePanel()).toHaveAttribute('data-item-id', '1'));
});

it('refreshes a feed whose list was saved before its refresh landed', async () => {
saveListSessionState('top', {
scrollY: 0, storyIds: cachedIds, position: 0, seenIds: [], hasMore: true, phase: 'firebase', stale: true,
});
vi.mocked(fetchTopStories).mockResolvedValue([13, ...cachedIds].map(id => createStoryItem({ id })));
render(<SwipeStoryViewer type="top" />);

await waitFor(() => expect(activePanel()).toHaveAttribute('data-item-id', '13'));
});

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" />);
Expand Down
2 changes: 1 addition & 1 deletion src/components/SwipeStoryViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -757,7 +757,7 @@ export function SwipeStoryViewer({ type, initialItemId }: SwipeStoryViewerProps)
// reader has swiped far: the stories they've reached, the one on screen
// included, stay, and the rest are replaced.
useEffect(() => {
if (isFromSession) return;
if (isFromSession && !isFromCache) return;
if (isFromCache && !loading && !error) {
void loadMore().catch(() => { /* error state set internally */ });
}
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useInfiniteStories.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,11 @@ describe('useInfiniteStories', () => {
setCachedFeed('top', Array.from({ length: 20 }, (_, i) => createStoryItem({ id: i + 1 })));
const first = renderHook(() => useInfiniteStories('top'));
// Opening a story while offline, or before the refresh comes back.
act(() => first.result.current.saveSessionState(0));
act(() => first.result.current.saveSessionState(700));
first.unmount();

const { result } = renderHook(() => useInfiniteStories('top'));
expect(result.current.isFromCache).toBe(true);
expect(result.current).toMatchObject({ isFromSession: true, isFromCache: true, initialScrollY: 700 });
await act(() => result.current.loadMore());

const ids = result.current.stories.map(s => s.id);
Expand Down
16 changes: 7 additions & 9 deletions src/hooks/useInfiniteStories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ function getInitialState(type: FeedType): InitialState {
if (stories.length >= sessionState.storyIds.length * 0.8) {
return {
stories,
isFromCache: false, // Don't revalidate - we're coming back
// Coming back skips the refresh, unless the list was left before its
// refresh landed: then it's still the cache, with the cursor at 0.
isFromCache: sessionState.stale === true,
isFromSession: true,
sessionState, // Pass along for scroll restoration
};
Expand Down Expand Up @@ -261,21 +263,17 @@ export function useInfiniteStories(type: FeedType = 'top') {
const saveSessionState = useCallback((scrollY = window.scrollY) => {
if (stories.length === 0) return;

// A cached list that was never refreshed has no cursor or seenIds to go
// with it: restored, it would skip the refresh and its next page would
// repeat the front page. Coming back refreshes it like a fresh visit.
if (hasStaleCacheRef.current) {
clearListSessionState(type);
return;
}

// A cached list that was never refreshed is saved as stale: coming back
// restores its scroll but still refreshes it, so its next page can't
// repeat the front page.
saveListSessionState(type, {
scrollY,
storyIds: stories.map(s => s.id),
position: positionRef.current,
seenIds: [...seenIdsRef.current],
hasMore,
phase: phaseRef.current,
stale: hasStaleCacheRef.current,
});

// Also update the stories cache with current full list (for session
Expand Down
16 changes: 16 additions & 0 deletions src/pages/StoryList.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
import { Routes, Route, useNavigate } from 'react-router';
import { render, screen, waitFor, act, fireEvent } from '../test/test-utils';
import { MobileStoryRoute } from '../App';
import { StoryList } from './StoryList';
import { hnSdk } from '../api/hnSdk';
import { __resetFetchCachesForTests } from '../api/hn';
import { saveListSessionState, getListSessionState } from '../utils/itemCache';
Expand Down Expand Up @@ -61,4 +62,19 @@ describe('StoryList on the feed routes', () => {
expect(screen.getAllByTestId('story-card')).toHaveLength(50);
expect(getListSessionState('best')?.storyIds).toHaveLength(50);
});

it('restores the scroll of a feed left before its refresh landed, and refreshes it', async () => {
const cached = ids.slice(0, 30).map(id => createStoryItem({ id, title: `Cached ${id}` }));
setCachedFeed('best', cached);
saveListSessionState('best', {
scrollY: 700, storyIds: cached.map(s => s.id), position: 0, seenIds: [], hasMore: true, stale: true,
});
const scrollTo = vi.spyOn(window, 'scrollTo').mockReturnValue(undefined);

render(<StoryList type="best" />);

await waitFor(() => expect(screen.getByRole('link', { name: 'Story 1000' })).toBeInTheDocument());
expect(screen.queryByRole('link', { name: 'Cached 1000' })).not.toBeInTheDocument();
expect(scrollTo).toHaveBeenCalledWith(0, 700);
});
});
2 changes: 1 addition & 1 deletion src/pages/StoryList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function StoryList({ type }: { type: FeedType }) {
}, [isFromSession, initialScrollY, stories.length]);

useEffect(() => {
if (isFromSession) return; // Don't refetch on back navigation.
if (isFromSession && !isFromCache) return; // Don't refetch on back navigation.

// The `!error` guard prevents an infinite retry loop: without it,
// loadMore() sets loading→true then error→msg then loading→false,
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@ export interface ListSessionState {
seenIds: Set<number>;
hasMore: boolean;
phase?: 'firebase' | 'algolia';
/** Saved before the cached list it holds was ever refreshed. */
stale?: boolean;
}

export interface PrefetchResult {
Expand Down
5 changes: 4 additions & 1 deletion src/utils/itemCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ interface SessionState {
seenIds: Iterable<number>;
hasMore: boolean;
phase?: 'firebase' | 'algolia';
stale?: boolean;
}

export function saveListSessionState(feedType: FeedType, state: SessionState): void {
Expand All @@ -159,6 +160,7 @@ export function saveListSessionState(feedType: FeedType, state: SessionState): v
seenIds: Array.from(state.seenIds),
hasMore: state.hasMore,
phase: state.phase,
stale: state.stale,
timestamp: Date.now(),
};
sessionStorage.setItem(key, JSON.stringify(data));
Expand All @@ -174,7 +176,7 @@ export function getListSessionState(feedType: FeedType): ListSessionState | null

const data = JSON.parse(cached) as {
scrollY?: number; storyIds?: number[]; position?: number;
seenIds?: number[]; hasMore?: boolean; phase?: string; timestamp: number;
seenIds?: number[]; hasMore?: boolean; phase?: string; stale?: boolean; timestamp: number;
};

// Session state expires after 30 minutes
Expand All @@ -191,6 +193,7 @@ export function getListSessionState(feedType: FeedType): ListSessionState | null
seenIds: new Set(data.seenIds ?? []),
hasMore: data.hasMore ?? true,
phase: (data.phase === 'firebase' || data.phase === 'algolia') ? data.phase : undefined,
stale: data.stale === true,
};
} catch {
return null;
Expand Down