From d4be78c46e8b4da8ff477c6c60f333049e07d7d4 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:19:11 +0200 Subject: [PATCH] fix: restore a feed's scroll when its refresh hadn't landed, and give the OP badge a screen-reader name - Feed: a cached list left before its refresh landed is saved as stale. Coming back restores its scroll and still runs the refresh, on desktop and in the mobile viewer. - OP badge: the visible "OP" is aria-hidden, with a screen-reader-only "Original poster" next to it, instead of aria-label on a plain span, which axe flags (aria-prohibited-attr). - Test: pin the second card's comment count in a StoryCard prefetch test. A random one like 142 also matched /42 comments/, failing about 1 run in 100. --- src/components/AuthorByline.tsx | 5 ++++- src/components/Comment.test.tsx | 10 +++++----- src/components/CommentArticle.test.tsx | 6 +++--- src/components/StoryCard.test.tsx | 3 ++- src/components/SwipeStoryViewer.test.tsx | 11 +++++++++++ src/components/SwipeStoryViewer.tsx | 2 +- src/hooks/useInfiniteStories.test.ts | 4 ++-- src/hooks/useInfiniteStories.ts | 16 +++++++--------- src/pages/StoryList.test.tsx | 16 ++++++++++++++++ src/pages/StoryList.tsx | 2 +- src/types.ts | 2 ++ src/utils/itemCache.ts | 5 ++++- 12 files changed, 58 insertions(+), 24 deletions(-) diff --git a/src/components/AuthorByline.tsx b/src/components/AuthorByline.tsx index 3d333e9..7d51968 100644 --- a/src/components/AuthorByline.tsx +++ b/src/components/AuthorByline.tsx @@ -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 ( {children} - + + Original poster ); } diff --git a/src/components/Comment.test.tsx b/src/components/Comment.test.tsx index 08f21ca..0dd894f 100644 --- a/src/components/Comment.test.tsx +++ b/src/components/Comment.test.tsx @@ -122,15 +122,15 @@ describe('Comment', () => { it('renders an OP badge when storyAuthor matches comment.author', () => { render(); - // 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(); - expect(screen.queryByLabelText('Original poster')).not.toBeInTheDocument(); + expect(screen.queryByText('Original poster')).not.toBeInTheDocument(); expect(screen.queryByText('OP')).not.toBeInTheDocument(); }); @@ -150,7 +150,7 @@ describe('Comment', () => { }); render(); - expect(screen.queryByLabelText('Original poster')).not.toBeInTheDocument(); + expect(screen.queryByText('Original poster')).not.toBeInTheDocument(); }, ); diff --git a/src/components/CommentArticle.test.tsx b/src/components/CommentArticle.test.tsx index c06adfa..3d818f8 100644 --- a/src/components/CommentArticle.test.tsx +++ b/src/components/CommentArticle.test.tsx @@ -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(); }); diff --git a/src/components/StoryCard.test.tsx b/src/components/StoryCard.test.tsx index 30c2db2..35b7a40 100644 --- a/src/components/StoryCard.test.tsx +++ b/src/components/StoryCard.test.tsx @@ -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( } /> diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx index e6bfc6f..fe5b2e2 100644 --- a/src/components/SwipeStoryViewer.test.tsx +++ b/src/components/SwipeStoryViewer.test.tsx @@ -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'; @@ -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(); + + 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(); diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx index 3389568..9c39e0c 100644 --- a/src/components/SwipeStoryViewer.tsx +++ b/src/components/SwipeStoryViewer.tsx @@ -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 */ }); } diff --git a/src/hooks/useInfiniteStories.test.ts b/src/hooks/useInfiniteStories.test.ts index e847cad..32a55e9 100644 --- a/src/hooks/useInfiniteStories.test.ts +++ b/src/hooks/useInfiniteStories.test.ts @@ -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); diff --git a/src/hooks/useInfiniteStories.ts b/src/hooks/useInfiniteStories.ts index ff1ac31..f00c2e0 100644 --- a/src/hooks/useInfiniteStories.ts +++ b/src/hooks/useInfiniteStories.ts @@ -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 }; @@ -261,14 +263,9 @@ 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), @@ -276,6 +273,7 @@ export function useInfiniteStories(type: FeedType = 'top') { seenIds: [...seenIdsRef.current], hasMore, phase: phaseRef.current, + stale: hasStaleCacheRef.current, }); // Also update the stories cache with current full list (for session diff --git a/src/pages/StoryList.test.tsx b/src/pages/StoryList.test.tsx index 066aaf0..af654db 100644 --- a/src/pages/StoryList.test.tsx +++ b/src/pages/StoryList.test.tsx @@ -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'; @@ -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(); + + await waitFor(() => expect(screen.getByRole('link', { name: 'Story 1000' })).toBeInTheDocument()); + expect(screen.queryByRole('link', { name: 'Cached 1000' })).not.toBeInTheDocument(); + expect(scrollTo).toHaveBeenCalledWith(0, 700); + }); }); diff --git a/src/pages/StoryList.tsx b/src/pages/StoryList.tsx index 318d62b..94ff940 100644 --- a/src/pages/StoryList.tsx +++ b/src/pages/StoryList.tsx @@ -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, diff --git a/src/types.ts b/src/types.ts index a0a6c5a..8849414 100644 --- a/src/types.ts +++ b/src/types.ts @@ -154,6 +154,8 @@ export interface ListSessionState { seenIds: Set; hasMore: boolean; phase?: 'firebase' | 'algolia'; + /** Saved before the cached list it holds was ever refreshed. */ + stale?: boolean; } export interface PrefetchResult { diff --git a/src/utils/itemCache.ts b/src/utils/itemCache.ts index 377e1cf..95f8cef 100644 --- a/src/utils/itemCache.ts +++ b/src/utils/itemCache.ts @@ -147,6 +147,7 @@ interface SessionState { seenIds: Iterable; hasMore: boolean; phase?: 'firebase' | 'algolia'; + stale?: boolean; } export function saveListSessionState(feedType: FeedType, state: SessionState): void { @@ -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)); @@ -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 @@ -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;