From db04e8fc8355af2235f6ffc9d1980ccff917893d Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:08:41 +0200 Subject: [PATCH 1/9] fix: keep the swipe position on Back and reach the end-of-feed panel In-app navigation (tapping the author) unmounted the mobile viewer without saving its place, and the remount on Back only had the feed's first cached page, so a story past it reopened at index 0 with its neighbors gone. Save the swipe snapshot when the viewer unmounts, as pagehide already does. The loading/error panel after the last story wasn't counted as a swipe target, so the gesture could never land on it and the Try Again button stayed hidden. Count it, fall back to the last panel when it goes away, and center the error on an inner box since .active sets display:block. --- e2e/domain-filter.spec.ts | 41 ++++++++ e2e/fixtures/api-mocks.ts | 15 ++- e2e/mobile-swipe.spec.ts | 70 ++++++++++++- src/components/SwipeStoryViewer.test.tsx | 121 ++++++++++++++++++++++- src/components/SwipeStoryViewer.tsx | 99 ++++++++++++------- 5 files changed, 305 insertions(+), 41 deletions(-) diff --git a/e2e/domain-filter.spec.ts b/e2e/domain-filter.spec.ts index 52e318a..4ceedb1 100644 --- a/e2e/domain-filter.spec.ts +++ b/e2e/domain-filter.spec.ts @@ -455,6 +455,47 @@ test.describe('Domain Filter - Mobile Swipe', () => { timeout: 10000, }); }); + + test('can swipe to the end-of-feed error panel and retry from it', async ({ page }) => { + test.setTimeout(60000); + + // Page 0 (5 stories) loads; page 1 fails until the test lets it through. + let failNextPage = true; + await page.route(`${ALGOLIA_API}/search_by_date*`, async (route) => { + const pageNum = new URL(route.request().url()).searchParams.get('page'); + if (failNextPage && pageNum === '1') { + await route.fulfill({ status: 503, json: { message: 'Service unavailable' } }); + } else { + await route.fallback(); + } + }); + + await page.goto('/#/from/example.com'); + const container = page.getByTestId('swipe-container'); + await waitForSwipeReady(page, 5); + + // Auto-retry exhausts its backoff (2s+4s+8s) before the panel turns into an error. + const errorPanel = container.locator('[data-testid="swipe-panel"]', { hasText: 'Failed to load item' }); + await expect(errorPanel).toHaveCount(1, { timeout: 30000 }); + + // Panels are hidden until activated, so Try Again only shows if a swipe + // can land on the panel after the last story. + const width = await container.evaluate((el) => el.getBoundingClientRect().width); + await smoothScrollAndAwaitSettled(container, width * 5); + await waitForScrollAtIndex(page, 5); + const retryButton = errorPanel.getByRole('button', { name: /try again/i }); + await expect(retryButton).toBeVisible(); + + failNextPage = false; + await retryButton.click(); + + // The next page's first story takes the error panel's place. + await expectActiveSwipePanelText(page, 'Advanced CSS Grid Techniques for Modern Layouts', { + minPanels: 7, + timeout: 10000, + }); + await expect(page).toHaveURL(/\/item\/77700/, { timeout: 5000 }); + }); }); test.describe('Domain Filter - Algolia Error Handling', () => { diff --git a/e2e/fixtures/api-mocks.ts b/e2e/fixtures/api-mocks.ts index 886d88a..77f4e71 100644 --- a/e2e/fixtures/api-mocks.ts +++ b/e2e/fixtures/api-mocks.ts @@ -171,11 +171,17 @@ function buildItemsMap(): Record { function resolveFirebasePath( path: string, items: Record, - opts?: { userResolver?: (username: string) => object | null }, + opts?: { + userResolver?: (username: string) => object | null; + lists?: Record; + }, ): unknown { // Strip leading slash — the SDK sends `/v0/...` but our constants use `v0/...` const p = path.replace(/^\//, ''); + const listOverride = opts?.lists?.[p]; + if (listOverride) return listOverride; + if (p === 'v0/topstories') return mockTopItemIds; if (p === 'v0/beststories') return mockBestItemIds; if (p === 'v0/newstories') return mockNewItemIds; @@ -242,6 +248,8 @@ export function createFirebaseWsHandler(opts?: { delayMs?: number; itemOverrides?: Record; errorItemIds?: number[]; + /** Story lists to serve instead of the defaults, keyed by path (`v0/topstories`). */ + lists?: Record; }) { const items = { ...buildItemsMap(), ...(opts?.itemOverrides ?? {}) }; @@ -286,7 +294,10 @@ export function createFirebaseWsHandler(opts?: { return; } - const data = resolveFirebasePath(body.p, items, { userResolver: opts?.userResolver }); + const data = resolveFirebasePath(body.p, items, { + userResolver: opts?.userResolver, + lists: opts?.lists, + }); const response = JSON.stringify({ t: 'd', d: { r: reqId, b: { s: 'ok', d: data } }, diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts index bd790a7..d3c5559 100644 --- a/e2e/mobile-swipe.spec.ts +++ b/e2e/mobile-swipe.spec.ts @@ -1,5 +1,10 @@ import { test, expect } from '@playwright/test'; -import { setupApiMocks } from './fixtures/api-mocks'; +import { + setupApiMocks, + createFirebaseWsHandler, + FIREBASE_WS_PATTERN, +} from './fixtures/api-mocks'; +import { ALGOLIA_API } from './fixtures/mock-data'; import { expectActiveSwipePanelText, getActiveSwipePanel, @@ -772,3 +777,66 @@ test.describe('Mobile Direct Item Access', () => { ), { timeout: 5000 }).toBe(1); }); }); + +test.describe('Mobile Swipe Viewer - Back past the cached page', () => { + test.use({ + viewport: { width: 375, height: 667 }, + hasTouch: true, + }); + + // A full first page. The feed cache keeps only this page, so the viewer that + // mounts on Back can't find the Algolia stories that load after it. + const topIds = Array.from({ length: 20 }, (_, i) => 30001 + i); + + test.beforeEach(async ({ page }) => { + await setupApiMocks(page); + await page.routeWebSocket( + FIREBASE_WS_PATTERN, + createFirebaseWsHandler({ lists: { 'v0/topstories': topIds } }), + ); + await page.addInitScript(() => { + localStorage.clear(); + sessionStorage.clear(); + }); + }); + + test('returns to the same story and its neighbors after visiting the author', async ({ page }) => { + test.setTimeout(60_000); + + await page.goto('/#/'); + const container = page.getByTestId('swipe-container'); + await waitForSwipeReady(page, 20); + const panelWidth = await container.evaluate((el) => el.getBoundingClientRect().width); + + // The next page (yesterday's front page, sorted by points: 55552, 55551, + // 55553) loads once you're within 5 stories of the end; the swipe helper + // only targets panels that already exist. + await smoothScrollAndAwaitSettled(container, panelWidth * 16); + await waitForSwipeReady(page, 23); + await smoothScrollAndAwaitSettled(container, panelWidth * 21); + await waitForScrollAtIndex(page, 21); + await expect(page).toHaveURL(/\/item\/55551/, { timeout: 5000 }); + + await getActiveSwipePanel(page).locator('a[href^="#/user/"]').first().click(); + await expect(page).toHaveURL(/\/user\//, { timeout: 5000 }); + + // Day pages can't load again, so after Back the stories past the cached + // page can only come from what the viewer kept when it unmounted. + await page.route(`${ALGOLIA_API}/search*`, async (route) => { + const tags = new URL(route.request().url()).searchParams.get('tags'); + if (tags === 'story') { + await route.abort(); + } else { + await route.fallback(); + } + }); + + await page.goBack(); + await expect(page).toHaveURL(/\/item\/55551/, { timeout: 5000 }); + await waitForSwipeReady(page, 23); + await waitForScrollAtIndex(page, 21); + await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', '55551'); + await expect(container.locator('[data-testid="swipe-panel"]').nth(20)) + .toHaveAttribute('data-item-id', '55552'); + }); +}); diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx index 161d180..c2719c8 100644 --- a/src/components/SwipeStoryViewer.test.tsx +++ b/src/components/SwipeStoryViewer.test.tsx @@ -1,5 +1,5 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { screen } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, screen, within } from '@testing-library/react'; import { render } from '../test/test-utils'; import { SwipeStoryViewerCore } from './SwipeStoryViewer'; import { createStoryItem } from '../test/factories'; @@ -13,6 +13,7 @@ import { import { saveSwipePosition, readSwipePosition } from '../utils/swipePosition'; import { fetchItemOnly } from '../api/hn'; import type * as HnApi from '../api/hn'; +import type { LocationState } from '../types'; // The panel wrapper (with data-item-id) is rendered by SwipeStoryViewerCore // itself, so stub the heavy detail child to keep these tests focused on the @@ -30,8 +31,33 @@ vi.mock('../api/hn', async (importOriginal) => ({ fetchItemOnly: vi.fn(() => new Promise(() => { /* never resolves */ })), })); +// Swipes commit synchronously under reduced motion, without the Web Animations +// API that jsdom lacks. +vi.mock('../utils/prefersReducedMotion', () => ({ prefersReducedMotion: () => true })); + Object.defineProperty(window, 'innerWidth', { value: 375, writable: true }); +/** One leftward swipe across most of the panel: moves to the next panel. */ +function swipeToNext() { + const container = screen.getByTestId('swipe-container'); + const fire = (type: string, clientX: number) => { + const touch = { identifier: 1, target: container, clientX, clientY: 300 }; + const event = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperty(event, 'touches', { value: type === 'touchend' ? [] : [touch] }); + Object.defineProperty(event, 'changedTouches', { value: [touch] }); + act(() => { + container.dispatchEvent(event); + }); + }; + fire('touchstart', 300); + fire('touchmove', 60); + fire('touchend', 60); +} + +function activePanel(): Element | null { + return screen.getByTestId('swipe-container').querySelector(':scope > .active'); +} + beforeEach(() => { Element.prototype.scrollTo = vi.fn(); window.scrollTo = vi.fn(); @@ -429,4 +455,95 @@ describe('SwipeStoryViewerCore — swipe-position restore', () => { expect(saved?.storyId).toBe(1); expect(saved?.viewer).toEqual({ from: 'top' }); }); + + it('persists a snapshot of the current story when the viewer unmounts', () => { + const stories = [createStoryItem({ id: 1 }), createStoryItem({ id: 2 }), createStoryItem({ id: 3 })]; + + const { unmount } = render( + , + ); + swipeToNext(); + expect(readSwipePosition()).toBeNull(); + + unmount(); + + const saved = readSwipePosition(); + expect(saved?.viewer).toEqual({ from: 'top' }); + expect(saved?.storyId).toBe(2); + expect(saved?.index).toBe(1); + expect(saved?.stories.map((s) => s.id)).toEqual([1, 2, 3]); + }); + + it('comes back to the same story after an in-app round trip, even when the feed only has its first page', () => { + const firstPage = Array.from({ length: 3 }, (_, i) => createStoryItem({ id: 10 + i })); + const secondPage = Array.from({ length: 3 }, (_, i) => createStoryItem({ id: 20 + i })); + + const { unmount } = render( + , + ); + for (let i = 0; i < 4; i++) swipeToNext(); + expect(activePanel()?.getAttribute('data-item-id')).toBe('21'); + unmount(); + + // Back remounts the viewer at the story's URL with only the cached first page. + render( + , + ); + + expect(renderedPanelIds()).toEqual(['10', '11', '12', '20', '21', '22']); + expect(activePanel()?.getAttribute('data-item-id')).toBe('21'); + expect(fetchItemOnly).not.toHaveBeenCalled(); + }); +}); + +describe('SwipeStoryViewerCore — end-of-feed panel', () => { + const stories = [createStoryItem({ id: 1 }), createStoryItem({ id: 2 })]; + const backState: LocationState = { from: 'top' }; + const baseProps = { + stories, + hasMore: true, + loadMore: vi.fn().mockResolvedValue(undefined), + backState, + }; + + afterEach(() => { + vi.useRealTimers(); + }); + + it('lets a swipe land on the loading panel after the last story', () => { + render(); + + swipeToNext(); + swipeToNext(); + + expect(activePanel()).toBe(screen.getByTestId('swipe-panel-loading')); + }); + + it('lets a swipe land on the error panel, where Try Again is', async () => { + vi.useFakeTimers(); + render(); + // Auto-retry runs its backoff before the trailing panel turns into the error. + for (const ms of [2000, 4000, 8000]) { + await act(() => vi.advanceTimersByTimeAsync(ms)); + } + + swipeToNext(); + swipeToNext(); + + const panel = activePanel() as HTMLElement; + expect(panel).toBe(screen.getByTestId('swipe-container').lastElementChild); + expect(within(panel).getByRole('button', { name: 'Try Again' })).toBeInTheDocument(); + }); + + it('falls back to the last story when the trailing panel goes away', () => { + const { rerender } = render(); + swipeToNext(); + swipeToNext(); + + // The load finished without new stories and the feed ended. + rerender(); + + expect(screen.queryByTestId('swipe-panel-loading')).not.toBeInTheDocument(); + expect(activePanel()?.getAttribute('data-item-id')).toBe('2'); + }); }); \ No newline at end of file diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx index 370841e..1be21c8 100644 --- a/src/components/SwipeStoryViewer.tsx +++ b/src/components/SwipeStoryViewer.tsx @@ -1,4 +1,4 @@ -import { useState, useRef, useEffect, useLayoutEffect, useMemo } from 'react'; +import { useState, useRef, useEffect, useLayoutEffect, useMemo, useCallback } from 'react'; import { useNavigate, useLocation } from 'react-router'; import { useInfiniteStories } from '../hooks/useInfiniteStories'; import { useSwipeScroll } from '../hooks/useSwipeScroll'; @@ -188,6 +188,21 @@ export function SwipeStoryViewerCore({ const anchorResolved = !anchorStoryId || mergedStories.some(s => s.id === anchorStoryId); + const { isOnline } = useNetworkStatus(); + const { isRetrying, giveUp, resetRetry } = useAutoRetry({ + error, + retryFn: loadMore, + isOnline, + enabled: !injectedError, + }); + + // The loading/error panel after the last story counts as a swipe target: + // panels stay display:none until activated, so one the gesture can't reach + // would hide the skeleton and the Try Again button for good. + const showLoadingPanel = isOnline && mergedStories.length > 0 && (loading || isRetrying); + const showErrorPanel = isOnline && mergedStories.length > 0 && !!error && !loading && !isRetrying; + const panelCount = mergedStories.length + (showLoadingPanel || showErrorPanel ? 1 : 0); + const { containerRef, currentIndex, @@ -195,23 +210,23 @@ export function SwipeStoryViewerCore({ scrollToIndex, isScrollingProgrammaticallyRef, } = useSwipeScroll({ - itemCount: mergedStories.length, + itemCount: panelCount, enabled: mergedStories.length > 0 && anchorResolved, }); + // The trailing panel can go away while it's showing (a load that brought no + // new stories, going offline); fall back to the last panel left. + useLayoutEffect(() => { + if (panelCount > 0 && currentIndex >= panelCount) { + scrollToIndex(panelCount - 1); + } + }, [panelCount, currentIndex, scrollToIndex]); + // Get current story for document title (updates as user swipes) const currentStory = mergedStories[currentIndex]; const isNonStoryError = injectedError === 'job' || injectedError === 'comment'; const isInjectedNotFound = injectedError && (isNonStoryError || isInjectedItemNotFound); - const isAtEndError = error && !loading && mergedStories.length > 0 && currentIndex === mergedStories.length - 1; - - const { isOnline } = useNetworkStatus(); - const { isRetrying, giveUp, resetRetry } = useAutoRetry({ - error, - retryFn: loadMore, - isOnline, - enabled: !injectedError, - }); + const isAtEndError = error && !loading && mergedStories.length > 0 && currentIndex >= mergedStories.length - 1; const documentTitle = injectedError ? (isInjectedNotFound ? (isNonStoryError ? 'Item not available' : 'Item not found') : 'Failed to load item') @@ -329,22 +344,31 @@ export function SwipeStoryViewerCore({ mergedStoriesRef.current = mergedStories; backStateRef.current = backState; }); + + // Persist a snapshot of the current story + neighborhood for restore. + const persistSnapshot = useCallback(() => { + const list = mergedStoriesRef.current; + // On the trailing loading/error panel, the last story is where you are. + const index = Math.min(currentIndexRef.current, list.length - 1); + const cur = list[index]; + if (!cur) return; + saveSwipePosition({ + viewer: backStateRef.current, + storyId: cur.id, + index, + scrollY: window.scrollY, + stories: list, + }); + }, [currentIndexRef]); + + // In-app navigation (tapping the author, say) unmounts the viewer, and for + // the main feeds the remount on Back gets only the first cached page, which can + // lack the story you were on and everything around it. Saving here lets that + // remount restore like a reload does. A layout cleanup runs before the next + // route's DOM goes in, so window.scrollY is still this panel's. + useLayoutEffect(() => () => persistSnapshot(), [persistSnapshot]); useEffect(() => { - // Persist a snapshot of the current story + neighborhood for reload restore. - const persistSnapshot = () => { - const list = mergedStoriesRef.current; - const cur = list[currentIndexRef.current]; - if (!cur) return; - saveSwipePosition({ - viewer: backStateRef.current, - storyId: cur.id, - index: currentIndexRef.current, - scrollY: window.scrollY, - stories: list, - }); - }; - // Save position + scrollY when page is about to be hidden/cached const handlePageHide = () => { savedIndexOnHideRef.current = currentIndexRef.current; @@ -392,7 +416,7 @@ export function SwipeStoryViewerCore({ window.removeEventListener('pageshow', handlePageShow); document.removeEventListener('visibilitychange', handleVisibilityChange); }; - }, [currentIndexRef, scrollToIndex]); + }, [currentIndexRef, scrollToIndex, persistSnapshot]); // Handle initial scroll position when returning from external URL (no anchor) // This runs once when items load and we have an initialItemId but didn't anchor @@ -672,21 +696,24 @@ export function SwipeStoryViewerCore({ })} {/* Loading indicator — only when online */} - {isOnline && ((loading && mergedStories.length > 0) || (isRetrying && mergedStories.length > 0 && !loading)) && ( + {showLoadingPanel && (
)} - {/* Error panel at the end — only when online and retries exhausted */} - {isOnline && error && !loading && !isRetrying && mergedStories.length > 0 && ( -
- { resetRetry(); void loadMore().catch(() => { /* error state set internally */ }); } }} - /> + {/* Error panel at the end — only when online and retries exhausted. + `.active` sets display:block, so the centering lives on an inner box. */} + {showErrorPanel && ( +
+
+ { resetRetry(); void loadMore().catch(() => { /* error state set internally */ }); } }} + /> +
)}
From 36f8ff99cb8ef26d9b36f5f7f2092b5f1f367bc1 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:08:41 +0200 Subject: [PATCH 2/9] fix: start one feed request when loadMore runs twice in a commit Two effects calling loadMore in the same commit both saw loading === false, so a mobile cold start read the ranked list several times. Guard with a ref that flips synchronously. --- src/hooks/useInfiniteStories.test.ts | 21 +++++++++++++++++++++ src/hooks/useInfiniteStories.ts | 8 +++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/hooks/useInfiniteStories.test.ts b/src/hooks/useInfiniteStories.test.ts index 29e3452..4f3c59e 100644 --- a/src/hooks/useInfiniteStories.test.ts +++ b/src/hooks/useInfiniteStories.test.ts @@ -106,4 +106,25 @@ describe('useInfiniteStories', () => { expect(result.current.stories.length).toBeGreaterThanOrEqual(afterRevalidation); }); + + it('starts one request when loadMore is called twice before re-rendering', async () => { + const { result } = renderHook(() => useInfiniteStories('top')); + + // Same closure twice — what two effects in one commit both see. + const { loadMore } = result.current; + await act(() => Promise.all([loadMore(), loadMore()])); + + expect(hnSdk.readRankedIds).toHaveBeenCalledTimes(1); + expect(result.current.stories).toHaveLength(20); + expect(result.current.loading).toBe(false); + }); + + it('accepts a new loadMore once the previous one settles', async () => { + const { result } = renderHook(() => useInfiniteStories('best')); + + await act(() => result.current.loadMore()); + await act(() => result.current.loadMore()); + + expect(result.current.stories).toHaveLength(50); + }); }); diff --git a/src/hooks/useInfiniteStories.ts b/src/hooks/useInfiniteStories.ts index 2346d80..b38cba5 100644 --- a/src/hooks/useInfiniteStories.ts +++ b/src/hooks/useInfiniteStories.ts @@ -84,6 +84,9 @@ export function useInfiniteStories(type: FeedType = 'top') { new Set(initialState.sessionState?.seenIds) ); const versionRef = useRef(0); + // `loading` alone can't guard: two effects calling loadMore in the same + // commit both still see the old `loading === false`. + const inFlightRef = useRef(false); const hasStaleCacheRef = useRef(initialState.isFromCache); // For ask/show: tracks whether we've exhausted Firebase and moved to Algolia const phaseRef = useRef<'firebase' | 'algolia'>( @@ -96,7 +99,8 @@ export function useInfiniteStories(type: FeedType = 'top') { ); const loadMore = useCallback(async () => { - if (loading || !hasMore) return; + if (loading || !hasMore || inFlightRef.current) return; + inFlightRef.current = true; setLoading(true); setError(null); @@ -289,6 +293,7 @@ export function useInfiniteStories(type: FeedType = 'top') { } } finally { if (versionRef.current === currentVersion) { + inFlightRef.current = false; setLoading(false); } } @@ -296,6 +301,7 @@ export function useInfiniteStories(type: FeedType = 'top') { const reset = useCallback(() => { versionRef.current += 1; + inFlightRef.current = false; const initial = getInitialState(type); setStories(initial.stories); From a81636c6b73d93f450985ac62a0c1b92bfc5a49d Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:08:41 +0200 Subject: [PATCH 3/9] fix: page past filter-rejected domain pages on a cold start When the first Algolia page held only hits from other hosts, the desktop list showed "No submissions" because nothing asked for page 2 (there's no sentinel while the list is empty). loadMore now keeps paging within one call until a story lands, still capped at MAX_EMPTY_PAGES_COLD_START. --- src/hooks/useDomainInfiniteStories.test.ts | 83 +++++------ src/hooks/useDomainInfiniteStories.ts | 154 +++++++++++---------- 2 files changed, 112 insertions(+), 125 deletions(-) diff --git a/src/hooks/useDomainInfiniteStories.test.ts b/src/hooks/useDomainInfiniteStories.test.ts index ffa663c..d43ec55 100644 --- a/src/hooks/useDomainInfiniteStories.test.ts +++ b/src/hooks/useDomainInfiniteStories.test.ts @@ -722,39 +722,44 @@ describe('useDomainInfiniteStories', () => { }); describe('cold-start empty-page cap', () => { - // The mobile swipe view's prefetch effect re-calls loadMore every time - // `loading` flips while `mergedStories.length < 10`. On a noisy substring - // query (e.g. `/from/microsoft` returning hundreds of `*.com` URLs that - // all fail the host filter), this loops 5–20 sequential fetches before - // Algolia's `nbPages` is exhausted, producing a multi-second skeleton↔ - // empty-state flicker. The cap halts the loop after 3 consecutive empty - // pages while no story has been accepted yet. + // On a noisy substring query (e.g. `/from/microsoft` returning hundreds of + // `*.com` URLs that all fail the host filter), the first pages can hold no + // story at all. Until one lands, a single loadMore keeps paging — nothing + // else would ask for page 2, since the desktop list renders no sentinel + // while empty — and the cap ends that after 3 consecutive empty pages. - it('halts after 3 consecutive filter-rejected pages and caches the terminal state', async () => { + it('pages past a filter-rejected first page on its own', async () => { let call = 0; vi.spyOn(globalThis, 'fetch').mockImplementation(() => { const page = call++; return Promise.resolve( - new Response(JSON.stringify(noiseBody('target.com', 50, page, 10))), + new Response(JSON.stringify( + page === 0 ? noiseBody('target.com', 50, 0, 3) : body('target.com', [7, 8], page, 3), + )), ); }); const { result } = renderHook(() => useDomainInfiniteStories('target.com')); await waitFor(() => expect(result.current.loading).toBe(false)); - expect(result.current.stories).toEqual([]); - expect(result.current.hasMore).toBe(true); - expect(call).toBe(1); - - await act(async () => { - await result.current.loadMore(); - }); + expect(result.current.stories.map((s) => s.id)).toEqual([7, 8]); expect(result.current.hasMore).toBe(true); expect(call).toBe(2); + expect(__getDomainCacheForTests().get('target.com')?.page).toBe(2); + }); - await act(async () => { - await result.current.loadMore(); + it('halts after 3 consecutive filter-rejected pages and caches the terminal state', async () => { + let call = 0; + vi.spyOn(globalThis, 'fetch').mockImplementation(() => { + const page = call++; + return Promise.resolve( + new Response(JSON.stringify(noiseBody('target.com', 50, page, 10))), + ); }); + + const { result } = renderHook(() => useDomainInfiniteStories('target.com')); + + await waitFor(() => expect(result.current.loading).toBe(false)); expect(result.current.hasMore).toBe(false); expect(result.current.stories).toEqual([]); expect(call).toBe(3); @@ -824,18 +829,9 @@ describe('useDomainInfiniteStories', () => { const { result } = renderHook(() => useDomainInfiniteStories('target.com')); await waitFor(() => expect(result.current.loading).toBe(false)); - expect(result.current.hasMore).toBe(true); - - await act(async () => { - await result.current.loadMore(); - }); - expect(result.current.hasMore).toBe(true); - - await act(async () => { - await result.current.loadMore(); - }); expect(result.current.stories.map((s) => s.id)).toEqual([99]); expect(result.current.hasMore).toBe(true); + expect(call).toBe(3); // Three more noise pages — would trip the cap if the counter hadn't // been reset AND we hadn't entered Regime B. @@ -848,12 +844,12 @@ describe('useDomainInfiniteStories', () => { expect(call).toBe(6); }); - it('resets the streak when domain changes mid-flight', async () => { - let call = 0; + it('resets the streak when the domain changes', async () => { + const calls = { foo: 0, bar: 0 }; vi.spyOn(globalThis, 'fetch').mockImplementation((input) => { - const page = call++; const url = fetchInputToUrl(input); const targetDomain = url.includes('query=foo') ? 'foo' : 'bar'; + const page = calls[targetDomain]++; return Promise.resolve( new Response(JSON.stringify(noiseBody(targetDomain, 50, page, 10))), ); @@ -864,33 +860,18 @@ describe('useDomainInfiniteStories', () => { { initialProps: { domain: 'foo' } }, ); - // foo: 2 consecutive noise pages → streak=2 - await waitFor(() => expect(result.current.loading).toBe(false)); - await act(async () => { - await result.current.loadMore(); - }); - expect(result.current.hasMore).toBe(true); + // foo: 3 noise pages → streak=3, cap reached + await waitFor(() => expect(result.current.hasMore).toBe(false)); + expect(calls.foo).toBe(3); // Switch to bar — domain reset block must zero the streak. If it // doesn't, the (stale) counter would tip at bar's first noise page // and the cap would fire after 1 fetch on the new domain. rerender({ domain: 'bar' }); - await waitFor(() => expect(result.current.stories).toEqual([])); + await waitFor(() => expect(calls.bar).toBeGreaterThan(0)); await waitFor(() => expect(result.current.loading).toBe(false)); - expect(result.current.hasMore).toBe(true); - - // bar: 2 more noise pages — streak should rebuild from 1, not 3 - await act(async () => { - await result.current.loadMore(); - }); - expect(result.current.hasMore).toBe(true); - - // bar's 3rd noise page now trips the (freshly-built) cap, proving the - // counter started over after the domain switch. - await act(async () => { - await result.current.loadMore(); - }); expect(result.current.hasMore).toBe(false); + expect(calls.bar).toBe(3); }); }); diff --git a/src/hooks/useDomainInfiniteStories.ts b/src/hooks/useDomainInfiniteStories.ts index 772ce20..f01dc4f 100644 --- a/src/hooks/useDomainInfiniteStories.ts +++ b/src/hooks/useDomainInfiniteStories.ts @@ -4,13 +4,15 @@ import { normalizeAlgoliaHit } from '../api/hn'; import type { StoryItem, AlgoliaSearchResponse } from '../types'; const HITS_PER_PAGE = 50; -// On a cold start (no story has been accepted yet), stop after this many +// On a cold start (no story has been accepted yet), `loadMore` keeps paging +// within one call until a page yields a story, and gives up after this many // consecutive pages whose hits all fail the host filter. Algolia's URL search // is tokenized and substring-prefix-greedy, so a query like `/from/microsoft` // surfaces hundreds of `*.com` URLs containing "microsoft" in the path — -// none of which match the strict host filter. Without a cap, the swipe view's -// prefetch effect re-calls `loadMore` every time `loading` flips, producing a -// 4–10s skeleton↔empty-state flicker before Algolia's `nbPages` is exhausted. +// none of which match the strict host filter. Paging inside the call matters +// because nothing else asks for page 2: the desktop list has no sentinel to +// scroll while it's empty, so a first page of noise read as "no submissions" +// even when the next page had them. The cap bounds noisy queries. // Only applies while `storiesRef.current.length === 0`; once any real hit // lands, deep pagination is unbounded so sparse-but-real domains aren't trimmed. const MAX_EMPTY_PAGES_COLD_START = 3; @@ -121,83 +123,87 @@ export function useDomainInfiniteStories(rawDomain: string) { const currentVersion = versionRef.current; try { - const pageToFetch = nextPageRef.current; - const url = `${ALGOLIA_API}/search_by_date?tags=story&query=${encodeURIComponent(domain)}&restrictSearchableAttributes=url&hitsPerPage=${HITS_PER_PAGE}&page=${pageToFetch}`; - const response = await fetch(url); + let uniqueStories: StoryItem[]; + let newHasMore: boolean; + // Cold start pages on until a story lands: see MAX_EMPTY_PAGES_COLD_START. + do { + const pageToFetch = nextPageRef.current; + const url = `${ALGOLIA_API}/search_by_date?tags=story&query=${encodeURIComponent(domain)}&restrictSearchableAttributes=url&hitsPerPage=${HITS_PER_PAGE}&page=${pageToFetch}`; + const response = await fetch(url); - if (!response.ok) { - throw new Error(`Failed to fetch stories: ${response.status}`); - } + if (!response.ok) { + throw new Error(`Failed to fetch stories: ${response.status}`); + } - if (versionRef.current !== currentVersion) return; + if (versionRef.current !== currentVersion) return; - const data = (await response.json()) as AlgoliaSearchResponse; + const data = (await response.json()) as AlgoliaSearchResponse; - // Second staleness check: `await response.json()` yields; the domain - // can change (and bump versionRef) during parse. Without this, the - // closure-captured `domain` would cause `domainCache.set(domain, ...)` - // to clobber the old domain's entry with partial data, and the - // appended stories would land on the new domain's state. - if (versionRef.current !== currentVersion) return; + // Second staleness check: `await response.json()` yields; the domain + // can change (and bump versionRef) during parse. Without this, the + // closure-captured `domain` would cause `domainCache.set(domain, ...)` + // to clobber the old domain's entry with partial data, and the + // appended stories would land on the new domain's state. + if (versionRef.current !== currentVersion) return; - // `domain` is a hostname (e.g. "github.com") OR a hostname+path - // (e.g. "github.com/microsoft"). Algolia's URL search can surface hits - // where the domain appears elsewhere in the URL (other host, path - // segment, query string), so verify locally. The match must require a - // `/` boundary after the domain — a bare `startsWith(domain)` would let - // `github.com.evil.com` surface under `/from/github.com`. - // - // Only http(s) URLs are accepted: defense-in-depth against - // `javascript:`/`data:`/`file:` URLs, which `new URL` happily parses - // with a `hostname` that would otherwise pass the host check (e.g. - // `javascript://github.com/%0Aalert(1)` parses with hostname=github.com). - const domainSlashPrefix = `${domain}/`; - const hostDotSuffix = `.${domain}`; - const domainStories: StoryItem[] = data.hits - .filter((hit) => { - if (!hit.url) return false; - try { - const parsed = new URL(hit.url); - if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false; - // hostname is already lowercase per WHATWG; pathname preserves - // case, so lowercase the full string for case-insensitive match - // against the (already-lowercased) `domain`. Trailing DNS dot is - // stripped for the same reason as the domain prop. - const hostname = parsed.hostname.replace(/^www\./, '').replace(/\.$/, ''); - const fullPath = (hostname + parsed.pathname).toLowerCase(); - return ( - fullPath === domain || - fullPath.startsWith(domainSlashPrefix) || - hostname.endsWith(hostDotSuffix) - ); - } catch { - return false; - } - }) - .map(normalizeAlgoliaHit); + // `domain` is a hostname (e.g. "github.com") OR a hostname+path + // (e.g. "github.com/microsoft"). Algolia's URL search can surface hits + // where the domain appears elsewhere in the URL (other host, path + // segment, query string), so verify locally. The match must require a + // `/` boundary after the domain — a bare `startsWith(domain)` would let + // `github.com.evil.com` surface under `/from/github.com`. + // + // Only http(s) URLs are accepted: defense-in-depth against + // `javascript:`/`data:`/`file:` URLs, which `new URL` happily parses + // with a `hostname` that would otherwise pass the host check (e.g. + // `javascript://github.com/%0Aalert(1)` parses with hostname=github.com). + const domainSlashPrefix = `${domain}/`; + const hostDotSuffix = `.${domain}`; + const domainStories: StoryItem[] = data.hits + .filter((hit) => { + if (!hit.url) return false; + try { + const parsed = new URL(hit.url); + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false; + // hostname is already lowercase per WHATWG; pathname preserves + // case, so lowercase the full string for case-insensitive match + // against the (already-lowercased) `domain`. Trailing DNS dot is + // stripped for the same reason as the domain prop. + const hostname = parsed.hostname.replace(/^www\./, '').replace(/\.$/, ''); + const fullPath = (hostname + parsed.pathname).toLowerCase(); + return ( + fullPath === domain || + fullPath.startsWith(domainSlashPrefix) || + hostname.endsWith(hostDotSuffix) + ); + } catch { + return false; + } + }) + .map(normalizeAlgoliaHit); - // Dedup across pages (Algolia can return overlaps on paginated search_by_date) - const uniqueStories = domainStories.filter((s) => { - if (seenIdsRef.current.has(s.id)) return false; - seenIdsRef.current.add(s.id); - return true; - }); + // Dedup across pages (Algolia can return overlaps on paginated search_by_date) + uniqueStories = domainStories.filter((s) => { + if (seenIdsRef.current.has(s.id)) return false; + seenIdsRef.current.add(s.id); + return true; + }); - const newPage = data.page + 1; - nextPageRef.current = newPage; + nextPageRef.current = data.page + 1; - // Cold-start cap: see MAX_EMPTY_PAGES_COLD_START. Snapshot before the - // storiesRef update below so the check reflects "had we shown anything - // before this fetch?", not "are we showing anything after it?". - const isColdStart = storiesRef.current.length === 0; - if (uniqueStories.length === 0 && isColdStart) { - emptyPageStreakRef.current += 1; - } else { - emptyPageStreakRef.current = 0; - } - const algoliaHasMore = data.page < data.nbPages - 1; - const capReached = emptyPageStreakRef.current >= MAX_EMPTY_PAGES_COLD_START; - const newHasMore = algoliaHasMore && !capReached; + // Cold-start cap. Snapshot before the storiesRef update below so the + // check reflects "had we shown anything before this fetch?", not "are + // we showing anything after it?". + const isColdStart = storiesRef.current.length === 0; + if (uniqueStories.length === 0 && isColdStart) { + emptyPageStreakRef.current += 1; + } else { + emptyPageStreakRef.current = 0; + } + const algoliaHasMore = data.page < data.nbPages - 1; + const capReached = emptyPageStreakRef.current >= MAX_EMPTY_PAGES_COLD_START; + newHasMore = algoliaHasMore && !capReached; + } while (uniqueStories.length === 0 && storiesRef.current.length === 0 && newHasMore); setHasMore(newHasMore); // Compute the next list outside any functional updater so setStories stays @@ -208,7 +214,7 @@ export function useDomainInfiniteStories(rawDomain: string) { storiesRef.current = updated; domainCache.set(domain, { stories: updated, - page: newPage, + page: nextPageRef.current, hasMore: newHasMore, seenIds: new Set(seenIdsRef.current), }); From dc5b07fe50ca65e7a48bb73774b536a4d08550b0 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:08:41 +0200 Subject: [PATCH 4/9] fix: drop the whoishiring threads from the Ask and Best feeds They're type='story', so the job filter misses them. New, the Ask day pages and the front-page day pages already excluded them. Show stays unfiltered, Firebase and Algolia alike, because a Show HN title that mentions hiring is a real project. --- src/api/hn.test.ts | 40 ++++++++++++++++++++++++++++++++++++++++ src/api/hn.ts | 34 +++++++++++++++++++++++++++------- 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts index 04c95da..8c47a6e 100644 --- a/src/api/hn.test.ts +++ b/src/api/hn.test.ts @@ -517,6 +517,18 @@ describe('hn API utilities', () => { expect(result2.stories.length).toBe(5); expect(result2.hasMore).toBe(false); }); + + it('keeps Show HN projects whose titles mention hiring', async () => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => + Number(id) === 99998 + ? { ...mockShowItems[99998], title: 'Show HN: A "Who is hiring" thread search' } + : mockShowItems[Number(id)] ?? null + ); + + const result = await fetchShowStories(0); + + expect(result.stories.map(s => s.id)).toEqual([99999, 99998, 99997]); + }); }); describe('fetchAskStories', () => { @@ -599,6 +611,21 @@ describe('hn API utilities', () => { expect(result2.stories.length).toBe(5); expect(result2.hasMore).toBe(false); }); + + it('filters out the monthly whoishiring threads', async () => { + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue([88888, 88910, 88911, 88887]); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + const hiring: Record = { + 88910: { id: 88910, title: 'Ask HN: Who is hiring? (October 2026)', text: 'Post jobs', by: 'whoishiring', score: 300, time: Math.floor(Date.now() / 1000), descendants: 400, type: 'story' }, + 88911: { id: 88911, title: 'Ask HN: Who wants to be hired? (October 2026)', text: 'Post resumes', by: 'whoishiring', score: 120, time: Math.floor(Date.now() / 1000), descendants: 200, type: 'story' }, + }; + return hiring[Number(id)] ?? mockAskItems[Number(id)] ?? null; + }); + + const result = await fetchAskStories(0); + + expect(result.stories.map(s => s.id)).toEqual([88888, 88887]); + }); }); describe('fetchNewStories', () => { @@ -803,6 +830,19 @@ describe('hn API utilities', () => { expect(result.stories).toEqual([]); expect(result.hasMore).toBe(false); }); + + it('filters out the monthly whoishiring threads', async () => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + const base = { id: Number(id), by: 'testuser', score: 50, time: Math.floor(Date.now() / 1000) - 7200, descendants: 5, type: 'story' as const }; + if (Number(id) === 12346) return { ...base, title: 'Ask HN: Who is hiring? (October 2026)', by: 'whoishiring' }; + if (Number(id) === 12348) return { ...base, title: 'Ask HN: Who wants to be hired? (October 2026)', by: 'whoishiring' }; + return { ...base, title: `Item ${id}` }; + }); + + const result = await fetchBestStories(0, 30); + + expect(result.stories.map(s => s.id)).toEqual([12345, 12347, 12349]); + }); }); describe('fetchFirebaseItem', () => { diff --git a/src/api/hn.ts b/src/api/hn.ts index 687eb1b..3677320 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -172,8 +172,16 @@ export async function fetchBestStories(offset = 0, limit = 30) { pageIds.map((id: number) => hnSdk.readItem(id).catch(() => null)) ); + // The whoishiring threads are type='story', not 'job', so the job filter + // alone lets them through when they rank among the best. const stories = fetched - .filter((fb): fb is FirebaseItem => fb != null && !fb.deleted && !fb.dead && fb.type !== 'job') + .filter((fb): fb is FirebaseItem => + fb != null && + !fb.deleted && + !fb.dead && + fb.type !== 'job' && + !isHiringThread(fb.title) + ) .map(fb => normalizeFirebaseToStoryItem(fb)); return { @@ -184,9 +192,8 @@ export async function fetchBestStories(offset = 0, limit = 30) { } // Newest feed: reverse-chronological submissions from HN `newstories` (≤500, -// HN's hard cap). Mirrors fetchBestStories' offset pagination but additionally -// filters the whoishiring bot's monthly threads (they are type='story', not -// 'job', so the job filter alone misses them). Reuses HIRING_EXCLUDE_TITLES. +// HN's hard cap). Mirrors fetchBestStories' offset pagination, including the +// whoishiring filter. export async function fetchNewStories(offset = 0, limit = 30) { const now = Date.now(); @@ -211,7 +218,7 @@ export async function fetchNewStories(offset = 0, limit = 30) { !fb.deleted && !fb.dead && fb.type !== 'job' && - !HIRING_EXCLUDE_TITLES.some(t => (fb.title ?? '').toLowerCase().includes(t)) + !isHiringThread(fb.title) ) .map(fb => normalizeFirebaseToStoryItem(fb)); @@ -242,6 +249,7 @@ async function fetchRankedStories( type: 'show' | 'ask', offset = 0, limit = 20, + excludeTitles?: string[], ) { const now = Date.now(); if (!cache.ids || (now - cache.timestamp) >= CACHE_TTL) { @@ -261,7 +269,12 @@ async function fetchRankedStories( ); const stories = items - .filter((fb): fb is FirebaseItem => fb != null && !fb.deleted && !fb.dead) + .filter((fb): fb is FirebaseItem => + fb != null && + !fb.deleted && + !fb.dead && + !excludeTitles?.some(t => (fb.title ?? '').toLowerCase().includes(t)) + ) .map(fb => ({ ...normalizeFirebaseToStoryItem(fb), type: type })); return { @@ -275,8 +288,10 @@ export function fetchShowStories(offset = 0) { return fetchRankedStories('showstories', showStoriesCache, 'show', offset); } +// Ask excludes the whoishiring threads, matching fetchAskStoriesForDay. Show is +// left unfiltered: a Show HN title mentioning hiring is a real project. export function fetchAskStories(offset = 0) { - return fetchRankedStories('askstories', askStoriesCache, 'ask', offset); + return fetchRankedStories('askstories', askStoriesCache, 'ask', offset, 20, HIRING_EXCLUDE_TITLES); } /** @@ -315,6 +330,11 @@ const HIRING_EXCLUDE_TITLES = [ 'who wants to be hired', ]; +function isHiringThread(title: string | undefined): boolean { + const lower = (title ?? '').toLowerCase(); + return HIRING_EXCLUDE_TITLES.some(t => lower.includes(t)); +} + export function fetchAskStoriesForDay(daysAgo: number): Promise { return fetchTaggedStoriesForDay('ask_hn', daysAgo, HIRING_EXCLUDE_TITLES); } From 44ad8def0e693dabc5dedf0cca90476337250795 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:08:41 +0200 Subject: [PATCH 5/9] fix: don't crash when the browser blocks site storage localStorage throws a SecurityError when site data is blocked, and ThemeProvider renders above the ErrorBoundary, so the whole app went blank. Fall back to the system theme and keep a chosen mode for the visit. --- src/context/ThemeContext.tsx | 11 +++++++++-- src/hooks/useTheme.test.tsx | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/context/ThemeContext.tsx b/src/context/ThemeContext.tsx index 0bb57e9..184bdb7 100644 --- a/src/context/ThemeContext.tsx +++ b/src/context/ThemeContext.tsx @@ -13,8 +13,13 @@ function getSystemTheme(): Theme { return window.matchMedia(DARK_QUERY).matches ? 'dark' : 'light'; } +// Storage access throws when the browser blocks site data; that must not take +// the app down, since ThemeProvider renders above the ErrorBoundary. function readStoredMode(): ThemeMode { - const stored = localStorage.getItem(MODE_KEY); + let stored: string | null = null; + try { + stored = localStorage.getItem(MODE_KEY); + } catch { /* storage unavailable — follow the device */ } if (stored === 'light' || stored === 'dark' || stored === 'system') { return stored; } @@ -67,7 +72,9 @@ export function ThemeProvider({ children }: { children: ReactNode }) { // Persist only on an explicit choice. Mounting never writes, so a fresh user // stays "follow the device" until they opt out. const setMode = (next: ThemeMode) => { - localStorage.setItem(MODE_KEY, next); + try { + localStorage.setItem(MODE_KEY, next); + } catch { /* not persisted — still applies for this visit */ } setModeState(next); }; diff --git a/src/hooks/useTheme.test.tsx b/src/hooks/useTheme.test.tsx index 6da0b6d..20f3e61 100644 --- a/src/hooks/useTheme.test.tsx +++ b/src/hooks/useTheme.test.tsx @@ -80,6 +80,38 @@ describe('useTheme', () => { expect(result.current.mode).toBe('system'); expect(result.current.theme).toBe('light'); }); + + describe('when the browser blocks storage', () => { + // Blocking site data makes the `localStorage` getter itself throw. + let restoreStorage: () => void; + + beforeEach(() => { + const descriptor = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')!; + Object.defineProperty(globalThis, 'localStorage', { + configurable: true, + get() { throw new DOMException('Access is denied for this document.', 'SecurityError'); }, + }); + restoreStorage = () => Object.defineProperty(globalThis, 'localStorage', descriptor); + }); + + afterEach(() => restoreStorage()); + + it('mounts in system mode instead of throwing', () => { + const { result } = renderHook(() => useTheme(), { wrapper }); + + expect(result.current.mode).toBe('system'); + expect(result.current.theme).toBe('light'); + }); + + it('still applies a selected mode for the current visit', () => { + const { result } = renderHook(() => useTheme(), { wrapper }); + + act(() => result.current.setMode('dark')); + + expect(result.current.mode).toBe('dark'); + expect(result.current.theme).toBe('dark'); + }); + }); }); // Controllable matchMedia so we can simulate the OS flipping color schemes at From 60eb45a2ae959a20924c10e907bd91882ec72f54 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:08:41 +0200 Subject: [PATCH 6/9] fix: open HN /newest links in the app /newest is an in-app route but wasn't in FEED_LABELS, so links to it left for news.ycombinator.com. --- src/utils/sanitize.test.ts | 22 +++++++++++++++++++--- src/utils/sanitize.ts | 1 + 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/utils/sanitize.test.ts b/src/utils/sanitize.test.ts index 3b7b9ab..187baf8 100644 --- a/src/utils/sanitize.test.ts +++ b/src/utils/sanitize.test.ts @@ -537,6 +537,11 @@ describe('sanitizeHtml', () => { expect(result).toContain('href="#/best"'); }); + it('rewrites /newest', () => { + const result = sanitizeHtml('link'); + expect(result).toContain('href="#/newest"'); + }); + it('drops query string on feed rewrite', () => { const result = sanitizeHtml('link'); expect(result).toContain('href="#/show"'); @@ -575,6 +580,11 @@ describe('sanitizeHtml', () => { expect(result).toContain('href="#/show"'); }); + it('rewrites self /#/newest', () => { + const result = sanitizeHtml('link'); + expect(result).toContain('href="#/newest"'); + }); + it('rewrites self /#/user/', () => { const result = sanitizeHtml('link'); expect(result).toContain('href="#/user/pg"'); @@ -683,6 +693,12 @@ describe('sanitizeHtml', () => { expect(result).toContain('>/best'); }); + it('replaces auto-linkified HN /newest with /newest', () => { + const url = 'https://news.ycombinator.com/newest'; + const result = sanitizeHtml(`${url}`); + expect(result).toContain('>/newest'); + }); + it('replaces auto-linkified self hash item URL with item:', () => { const url = 'https://hackertok.github.io/#/item/47816960'; const result = sanitizeHtml(`${url}`); @@ -803,9 +819,9 @@ describe('sanitizeHtml', () => { }); describe('negative cases', () => { - it('leaves news.ycombinator.com/newest unchanged', () => { - const result = sanitizeHtml('link'); - expect(result).toContain('href="https://news.ycombinator.com/newest"'); + it('leaves HN pages without an in-app route (e.g. /jobs) unchanged', () => { + const result = sanitizeHtml('link'); + expect(result).toContain('href="https://news.ycombinator.com/jobs"'); }); it('leaves unrelated hosts unchanged', () => { diff --git a/src/utils/sanitize.ts b/src/utils/sanitize.ts index 34fa88c..13acc88 100644 --- a/src/utils/sanitize.ts +++ b/src/utils/sanitize.ts @@ -44,6 +44,7 @@ const FEED_LABELS = new Map([ ['/show', '/show'], ['/ask', '/ask'], ['/best', '/best'], + ['/newest', '/newest'], ]); // Canonical self-host; `window.location.hostname` also treated as self at runtime. From c17e46a72ab2e0297ab9446b6f863fad69be719d Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:08:42 +0200 Subject: [PATCH 7/9] fix: stop tabs overwriting each other's viewed stories Each write stores the tab's whole in-memory copy, so a stale copy erased what another tab had recorded. Drop the copies on a storage event so the next read or write starts from storage. --- src/utils/viewedItems.test.ts | 56 +++++++++++++++++++++++++++++++++++ src/utils/viewedItems.ts | 16 ++++++++++ 2 files changed, 72 insertions(+) diff --git a/src/utils/viewedItems.test.ts b/src/utils/viewedItems.test.ts index 91c8cec..020d355 100644 --- a/src/utils/viewedItems.test.ts +++ b/src/utils/viewedItems.test.ts @@ -428,6 +428,62 @@ describe('viewedItems - Time-based functions', () => { }); }); +describe('viewedItems - writes from another tab', () => { + beforeEach(() => { + clearViewed(); + clearViewedTimes(); + }); + + // Another tab writes straight to localStorage; the browser then fires + // `storage` in this tab only. + function writeFromOtherTab(key: string, value: unknown) { + localStorage.setItem(key, JSON.stringify(value)); + window.dispatchEvent(new StorageEvent('storage', { key })); + } + + it('keeps the other tab\'s detail views when this tab writes next', () => { + markViewedWithTime(111, 'detail'); + const stored = JSON.parse(localStorage.getItem(VIEWED_DETAIL_TIMES_KEY)!) as Record; + writeFromOtherTab(VIEWED_DETAIL_TIMES_KEY, { ...stored, 222: Date.now() + 3_600_000 }); + + markViewedWithTime(333, 'detail'); + + const ids = Object.keys(JSON.parse(localStorage.getItem(VIEWED_DETAIL_TIMES_KEY)!) as object); + expect(ids.sort()).toEqual(['111', '222', '333']); + expect(getFilteredViewedIds()).toEqual(new Set([111, 222, 333])); + }); + + it('keeps the other tab\'s title clicks when this tab writes next', () => { + markViewedWithTime(111, 'title'); + const stored = JSON.parse(localStorage.getItem(VIEWED_TITLE_TIMES_KEY)!) as Record; + writeFromOtherTab(VIEWED_TITLE_TIMES_KEY, { ...stored, 222: Date.now() + 3_600_000 }); + + markViewedWithTime(333, 'title'); + + const ids = Object.keys(JSON.parse(localStorage.getItem(VIEWED_TITLE_TIMES_KEY)!) as object); + expect(ids.sort()).toEqual(['111', '222', '333']); + }); + + it('picks up the other tab\'s permanent views and keeps them on the next write', () => { + markViewed(111); + writeFromOtherTab(VIEWED_KEY, [111, 222]); + + expect(isViewed(222)).toBe(true); + + markViewed(333); + expect(JSON.parse(localStorage.getItem(VIEWED_KEY)!)).toEqual([111, 222, 333]); + }); + + it('drops the in-memory copies when another tab clears storage', () => { + markViewedWithTime(111, 'title'); + localStorage.clear(); + window.dispatchEvent(new StorageEvent('storage', { key: null })); + + expect(isViewed(111)).toBe(false); + expect(getFilteredViewedIds().size).toBe(0); + }); +}); + describe('viewedItems - Session storage functions', () => { beforeEach(() => { clearViewed(); diff --git a/src/utils/viewedItems.ts b/src/utils/viewedItems.ts index 657ecd9..55d3a8b 100644 --- a/src/utils/viewedItems.ts +++ b/src/utils/viewedItems.ts @@ -147,6 +147,22 @@ function createTimeMap(storageKey: string) { const titleTimeMap = createTimeMap(VIEWED_TITLE_TIMES_KEY); const detailTimeMap = createTimeMap(VIEWED_DETAIL_TIMES_KEY); +// Every write stores this tab's whole in-memory copy, so a copy that predates +// another tab's write would erase it. `storage` fires only in the other tabs; +// dropping the copies there makes their next read or write start from storage. +// A null key means another tab cleared all of localStorage. +if (typeof window !== 'undefined') { + window.addEventListener('storage', (event) => { + const { key } = event; + if (key === null || key === VIEWED_TITLE_TIMES_KEY) titleTimeMap.reset(); + if (key === null || key === VIEWED_DETAIL_TIMES_KEY) detailTimeMap.reset(); + if (key === null || key === VIEWED_KEY) { + viewedSet = null; + notifyListeners(); + } + }); +} + /** Get IDs that should be filtered (hidden) in swipe mode — entries not yet expired. */ export function getFilteredViewedIds(): Set { const now = Date.now(); From 553d9295cc544ba0e256b0ba24c3a89b225226c5 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 4 Oct 2026 23:11:13 +0200 Subject: [PATCH 8/9] fix: don't throw from the theme script when site storage is blocked The inline script in index.html read localStorage unguarded. With storage blocked it threw before applying the dark class, so a dark-OS user got a light background until React's ThemeProvider caught up, plus an uncaught error. It now falls back to the OS scheme, like ThemeProvider does. --- e2e/theme-toggle.spec.ts | 20 ++++++++++++++++++++ index.html | 6 +++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/e2e/theme-toggle.spec.ts b/e2e/theme-toggle.spec.ts index a559545..5d7bfc9 100644 --- a/e2e/theme-toggle.spec.ts +++ b/e2e/theme-toggle.spec.ts @@ -95,6 +95,26 @@ test.describe('Theme - System mode', () => { await expect(html).not.toHaveClass(/dark/); }); + test('follows the OS dark preference without an error when site storage is blocked', async ({ page }) => { + await page.emulateMedia({ colorScheme: 'dark' }); + await setupApiMocks(page); + await page.addInitScript(() => { + const deny = () => { + throw new DOMException('Access is denied for this document.', 'SecurityError'); + }; + Object.defineProperty(window, 'localStorage', { configurable: true, get: deny }); + Object.defineProperty(window, 'sessionStorage', { configurable: true, get: deny }); + }); + const errors: string[] = []; + page.on('pageerror', (error) => errors.push(error.message)); + + await page.goto('/#/'); + + await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expect(page.locator('html')).toHaveClass(/dark/); + expect(errors).toEqual([]); + }); + // Issue 2: while following the system, flipping the OS theme flips the app. test('system mode follows the OS theme when it changes after load', async ({ page }) => { await page.emulateMedia({ colorScheme: 'light' }); diff --git a/index.html b/index.html index a41b8f4..1169fe8 100644 --- a/index.html +++ b/index.html @@ -85,7 +85,11 @@ // Mirrors ThemeProvider: 'light'/'dark' are explicit pins; 'system' (and // any missing value) follows the OS color scheme. (function() { - var mode = localStorage.getItem('setting:theme'); + // Reading storage throws when the browser blocks site data; follow the OS then. + var mode = null; + try { + mode = localStorage.getItem('setting:theme'); + } catch (e) {} var prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; var isDark = mode === 'dark' || (mode !== 'light' && prefersDark); if (isDark) { From 430305dac7d2b375da1fd2b0f87862bb1f7baaff Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 4 Oct 2026 23:11:13 +0200 Subject: [PATCH 9/9] fix: keep each feed's swipe position when switching feeds The saved position had a single slot, so opening Best (or a domain or user's submissions) replaced the Top feed's position and Back to Top lost your place. Positions are now kept per viewer, newest first, capped at 8. Opening a feed from its tab drops that feed's old position so the tab still starts at the top. --- e2e/mobile-swipe.spec.ts | 40 ++++-- src/App.test.tsx | 9 ++ src/App.tsx | 6 +- src/components/SwipeStoryViewer.test.tsx | 36 ++++++ src/components/SwipeStoryViewer.tsx | 28 ++--- src/utils/swipePosition.test.ts | 69 +++++++++++ src/utils/swipePosition.ts | 147 ++++++++++++++++------- 7 files changed, 261 insertions(+), 74 deletions(-) diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts index d3c5559..3e932f1 100644 --- a/e2e/mobile-swipe.spec.ts +++ b/e2e/mobile-swipe.spec.ts @@ -1,4 +1,4 @@ -import { test, expect } from '@playwright/test'; +import { test, expect, type Page } from '@playwright/test'; import { setupApiMocks, createFirebaseWsHandler, @@ -800,9 +800,8 @@ test.describe('Mobile Swipe Viewer - Back past the cached page', () => { }); }); - test('returns to the same story and its neighbors after visiting the author', async ({ page }) => { - test.setTimeout(60_000); - + /** Swipes to index 21, the second story of the page loaded after the first. */ + async function swipePastFirstPage(page: Page) { await page.goto('/#/'); const container = page.getByTestId('swipe-container'); await waitForSwipeReady(page, 20); @@ -816,12 +815,11 @@ test.describe('Mobile Swipe Viewer - Back past the cached page', () => { await smoothScrollAndAwaitSettled(container, panelWidth * 21); await waitForScrollAtIndex(page, 21); await expect(page).toHaveURL(/\/item\/55551/, { timeout: 5000 }); + } - await getActiveSwipePanel(page).locator('a[href^="#/user/"]').first().click(); - await expect(page).toHaveURL(/\/user\//, { timeout: 5000 }); - - // Day pages can't load again, so after Back the stories past the cached - // page can only come from what the viewer kept when it unmounted. + /** Goes Back with day pages blocked, so stories past the cached page can only + * come from what the viewer kept when it unmounted. */ + async function goBackToStory21(page: Page) { await page.route(`${ALGOLIA_API}/search*`, async (route) => { const tags = new URL(route.request().url()).searchParams.get('tags'); if (tags === 'story') { @@ -836,7 +834,29 @@ test.describe('Mobile Swipe Viewer - Back past the cached page', () => { await waitForSwipeReady(page, 23); await waitForScrollAtIndex(page, 21); await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', '55551'); - await expect(container.locator('[data-testid="swipe-panel"]').nth(20)) + await expect(page.getByTestId('swipe-container').locator('[data-testid="swipe-panel"]').nth(20)) .toHaveAttribute('data-item-id', '55552'); + } + + test('returns to the same story and its neighbors after visiting the author', async ({ page }) => { + test.setTimeout(60_000); + await swipePastFirstPage(page); + + await getActiveSwipePanel(page).locator('a[href^="#/user/"]').first().click(); + await expect(page).toHaveURL(/\/user\//, { timeout: 5000 }); + + await goBackToStory21(page); + }); + + test('returns to the same story after switching to Best', async ({ page }) => { + test.setTimeout(60_000); + await swipePastFirstPage(page); + + await page.getByRole('link', { name: 'best', exact: true }).click({ force: true }); + // Best's own viewer mounts on its first story and saves a position too. + await expect(page).toHaveURL(/\/item\/33001/, { timeout: 5000 }); + await expect(getActiveSwipePanel(page)).toHaveAttribute('data-item-id', '33001'); + + await goBackToStory21(page); }); }); diff --git a/src/App.test.tsx b/src/App.test.tsx index 18f9095..8d9a3ab 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -96,6 +96,15 @@ describe('MobileItemDetailWrapper — viewer recovery (stateless reload)', () => expect(screen.queryByTestId('user-viewer')).toBeNull(); }); + it('recovers the viewer whose snapshot is on this story when another viewer saved later', () => { + seedSnapshot({ from: 'best' }, 123); + seedSnapshot({ from: 'top' }, 456); + + renderWrapper(123); + + expect(screen.getByTestId('feed-viewer')).toHaveAttribute('data-type', 'best'); + }); + it('falls back to the resolver when the snapshot id does not match the route', () => { seedSnapshot({ from: 'best' }, 999); // snapshot is for a different story diff --git a/src/App.tsx b/src/App.tsx index 119af0c..71a57d5 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -92,9 +92,9 @@ export function MobileItemDetailWrapper() { const { id } = useParams(); const canSwipe = useCanSwipe(); const location = useLocation(); - // Snapshot 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()); + // 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) })); if (canSwipe) { const state = location.state as LocationState | null; diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx index c2719c8..8ace2c1 100644 --- a/src/components/SwipeStoryViewer.test.tsx +++ b/src/components/SwipeStoryViewer.test.tsx @@ -494,6 +494,42 @@ describe('SwipeStoryViewerCore — swipe-position restore', () => { expect(activePanel()?.getAttribute('data-item-id')).toBe('21'); expect(fetchItemOnly).not.toHaveBeenCalled(); }); + + it('keeps the position when another feed is opened in between (switching to Best, then Back)', () => { + const firstPage = Array.from({ length: 3 }, (_, i) => createStoryItem({ id: 10 + i })); + const secondPage = Array.from({ length: 3 }, (_, i) => createStoryItem({ id: 20 + i })); + + const top = render( + , + ); + for (let i = 0; i < 4; i++) swipeToNext(); + top.unmount(); + + // Best opens fresh, then its viewer unmounts too and saves its own position. + const bestStories = [createStoryItem({ id: 50 }), createStoryItem({ id: 51 })]; + const best = render( + , + ); + best.unmount(); + + render( + , + ); + + expect(renderedPanelIds()).toEqual(['10', '11', '12', '20', '21', '22']); + expect(activePanel()?.getAttribute('data-item-id')).toBe('21'); + }); + + it("drops a feed's old position when the feed is opened from its tab", () => { + const stories = [createStoryItem({ id: 1 }), createStoryItem({ id: 2 })]; + saveSwipePosition({ viewer: { from: 'best' }, storyId: 1, index: 0, scrollY: 300, stories }); + saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories }); + + render(); + + expect(readSwipePosition({ viewer: { from: 'best' } })).toBeNull(); + expect(readSwipePosition({ viewer: { from: 'top' } })?.storyId).toBe(2); + }); }); describe('SwipeStoryViewerCore — end-of-feed panel', () => { diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx index 1be21c8..7947f50 100644 --- a/src/components/SwipeStoryViewer.tsx +++ b/src/components/SwipeStoryViewer.tsx @@ -16,15 +16,6 @@ import { FullScreenItem, FullScreenItemSkeletonPanel } from './FullScreenItem'; import { StateView } from './StateView'; import type { StoryItem, FeedType, LocationState } from '../types'; -/** Two LocationStates refer to the same viewer when they share a feed/domain/user. */ -function sameViewer(a: LocationState, b: LocationState): boolean { - return ( - (a.from ?? null) === (b.from ?? null) && - (a.fromDomain ?? null) === (b.fromDomain ?? null) && - (a.fromUser ?? null) === (b.fromUser ?? null) - ); -} - interface SwipeStoryViewerCoreProps { /** Story data from the consumer's data source (feed, domain, etc.) */ stories: StoryItem[]; @@ -77,13 +68,8 @@ export function SwipeStoryViewerCore({ // effect rewrites /item/:id), so re-validating per render would drop the snapshot // mid-session and collapse the list back to live `stories`. const [restoreSnapshot] = useState(() => { - const snap = readSwipePosition(); - return snap && - snap.stories.length > 0 && - snap.storyId === initialItemIdNum && - sameViewer(snap.viewer, backState) - ? snap - : null; + const snap = readSwipePosition({ viewer: backState }); + return snap && snap.stories.length > 0 && snap.storyId === initialItemIdNum ? snap : null; }); const isRestoringPosition = restoreSnapshot !== null; const restoredStories = restoreSnapshot?.stories ?? null; @@ -367,6 +353,14 @@ export function SwipeStoryViewerCore({ // remount restore like a reload does. A layout cleanup runs before the next // route's DOM goes in, so window.scrollY is still this panel's. useLayoutEffect(() => () => persistSnapshot(), [persistSnapshot]); + + // Opening a feed from its tab (no story in the URL) starts it over. Drop the + // feed's old position now: the viewer that mounts once the URL moves to the + // first story would otherwise restore it if it was saved on that story. + const opensFresh = initialItemId == null; + useLayoutEffect(() => { + if (opensFresh) clearSwipePosition(backState); + }, [opensFresh, backState]); useEffect(() => { // Save position + scrollY when page is about to be hidden/cached @@ -505,7 +499,7 @@ export function SwipeStoryViewerCore({ if (restoreSnapshot.scrollY > 0) { window.scrollTo(0, restoreSnapshot.scrollY); } - clearSwipePosition(); + clearSwipePosition(restoreSnapshot.viewer); } } }, [mergedStories, initialItemId, initialItemIdNum, anchorStoryId, scrollToIndex, currentIndexRef, restoreSnapshot]); diff --git a/src/utils/swipePosition.test.ts b/src/utils/swipePosition.test.ts index 3fa3498..076f9d3 100644 --- a/src/utils/swipePosition.test.ts +++ b/src/utils/swipePosition.test.ts @@ -5,6 +5,7 @@ import { clearSwipePosition, SWIPE_POSITION_KEY, SWIPE_POSITION_AHEAD, + SWIPE_POSITION_MAX_VIEWERS, } from './swipePosition'; import { createStoryItem } from '../test/factories'; import type { StoryItem } from '../types'; @@ -173,6 +174,63 @@ describe('swipePosition', () => { }); }); + describe('one position per viewer', () => { + it("keeps a viewer's position when another viewer saves", () => { + saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories }); + saveSwipePosition({ viewer: { from: 'best' }, storyId: 3, index: 2, scrollY: 0, stories }); + + expect(readSwipePosition({ viewer: { from: 'top' } })?.storyId).toBe(2); + expect(readSwipePosition({ viewer: { from: 'best' } })?.storyId).toBe(3); + }); + + it("replaces the viewer's own older position", () => { + saveSwipePosition({ viewer: { fromDomain: 'a.com' }, storyId: 1, index: 0, scrollY: 0, stories }); + saveSwipePosition({ viewer: { fromDomain: 'a.com' }, storyId: 3, index: 2, scrollY: 0, stories }); + + expect(readSwipePosition({ viewer: { fromDomain: 'a.com' } })?.storyId).toBe(3); + expect(readSwipePosition({ storyId: 1 })).toBeNull(); + }); + + it('returns the newest snapshot when no viewer is given, or the newest on a story', () => { + saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories }); + saveSwipePosition({ viewer: { from: 'best' }, storyId: 2, index: 1, scrollY: 0, stories }); + saveSwipePosition({ viewer: { fromUser: 'pg' }, storyId: 3, index: 2, scrollY: 0, stories }); + + expect(readSwipePosition()?.viewer).toEqual({ fromUser: 'pg' }); + expect(readSwipePosition({ storyId: 2 })?.viewer).toEqual({ from: 'best' }); + expect(readSwipePosition({ viewer: { from: 'top' }, storyId: 3 })).toBeNull(); + }); + + it(`keeps only the ${SWIPE_POSITION_MAX_VIEWERS} newest viewers`, () => { + for (let i = 0; i <= SWIPE_POSITION_MAX_VIEWERS; i++) { + saveSwipePosition({ viewer: { fromUser: `u${i}` }, storyId: 2, index: 1, scrollY: 0, stories }); + } + + expect(readSwipePosition({ viewer: { fromUser: 'u0' } })).toBeNull(); + expect(readSwipePosition({ viewer: { fromUser: 'u1' } })).not.toBeNull(); + expect(readSwipePosition({ viewer: { fromUser: `u${SWIPE_POSITION_MAX_VIEWERS}` } })).not.toBeNull(); + }); + + it('expires each position on its own', () => { + saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories }); + vi.advanceTimersByTime(20 * 60 * 1000); + saveSwipePosition({ viewer: { from: 'best' }, storyId: 3, index: 2, scrollY: 0, stories }); + vi.advanceTimersByTime(11 * 60 * 1000); + + expect(readSwipePosition({ viewer: { from: 'top' } })).toBeNull(); + expect(readSwipePosition({ viewer: { from: 'best' } })?.storyId).toBe(3); + }); + + it('reads a single record saved in the earlier one-slot format', () => { + sessionStorage.setItem( + SWIPE_POSITION_KEY, + JSON.stringify({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories, savedAt: Date.now() }), + ); + + expect(readSwipePosition({ viewer: { from: 'top' } })?.storyId).toBe(2); + }); + }); + describe('clearSwipePosition', () => { it('removes a stored snapshot', () => { saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories }); @@ -180,8 +238,19 @@ describe('swipePosition', () => { expect(readSwipePosition()).toBeNull(); }); + it("removes only the given viewer's snapshot", () => { + saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories }); + saveSwipePosition({ viewer: { from: 'best' }, storyId: 3, index: 2, scrollY: 0, stories }); + + clearSwipePosition({ from: 'top' }); + + expect(readSwipePosition({ viewer: { from: 'top' } })).toBeNull(); + expect(readSwipePosition({ viewer: { from: 'best' } })?.storyId).toBe(3); + }); + it('does not throw when nothing is stored', () => { expect(() => clearSwipePosition()).not.toThrow(); + expect(() => clearSwipePosition({ from: 'top' })).not.toThrow(); }); }); }); diff --git a/src/utils/swipePosition.ts b/src/utils/swipePosition.ts index 5e02e48..7f09477 100644 --- a/src/utils/swipePosition.ts +++ b/src/utils/swipePosition.ts @@ -1,9 +1,10 @@ -import type { StoryItem, SwipePosition } from '../types'; +import type { LocationState, StoryItem, SwipePosition } from '../types'; /** - * Durable per-tab swipe-position snapshot (sessionStorage). Survives a full reload + * Durable per-tab swipe-position snapshots (sessionStorage). Survive a full reload * (bfcache miss) so the viewer can re-find the user's story + neighbors instead of - * collapsing to index 0. One key — we only need "the position you just left." + * collapsing to index 0. One record per viewer (feed, domain, or user), newest + * first, so leaving one feed for another doesn't replace the first feed's position. */ export const SWIPE_POSITION_KEY = '__swipe_pos'; @@ -17,6 +18,18 @@ const SWIPE_POSITION_TTL_MS = 30 * 60 * 1000; // look-ahead suffices; loadMore refills as the user swipes forward. export const SWIPE_POSITION_AHEAD = 10; +// Bounds storage when many domains/users get visited in one session. +export const SWIPE_POSITION_MAX_VIEWERS = 8; + +/** Two LocationStates refer to the same viewer when they share a feed/domain/user. */ +export function sameViewer(a: LocationState, b: LocationState): boolean { + return ( + (a.from ?? null) === (b.from ?? null) && + (a.fromDomain ?? null) === (b.fromDomain ?? null) && + (a.fromUser ?? null) === (b.fromUser ?? null) + ); +} + /** Lean projection: omits `text` (the heavy Ask/Show HTML body); FullScreenItem re-fetches. */ function projectStory(s: StoryItem): StoryItem { return { @@ -31,11 +44,71 @@ function projectStory(s: StoryItem): StoryItem { }; } +function parseRecord(value: unknown): SwipePosition | null { + const parsed = value as Partial | null; + if ( + !parsed || + typeof parsed !== 'object' || + typeof parsed.savedAt !== 'number' || + typeof parsed.storyId !== 'number' || + !parsed.viewer || + typeof parsed.viewer !== 'object' || + !Array.isArray(parsed.stories) + ) { + return null; + } + return { + viewer: parsed.viewer, + storyId: parsed.storyId, + index: typeof parsed.index === 'number' ? parsed.index : 0, + scrollY: typeof parsed.scrollY === 'number' ? parsed.scrollY : 0, + stories: parsed.stories, + savedAt: parsed.savedAt, + }; +} + +function writeRecords(records: SwipePosition[]): void { + if (records.length === 0) { + sessionStorage.removeItem(SWIPE_POSITION_KEY); + } else { + sessionStorage.setItem(SWIPE_POSITION_KEY, JSON.stringify(records)); + } +} + +/** Valid, unexpired records, newest first. Drops the rest from storage. */ +function readRecords(): SwipePosition[] { + let entries: unknown[]; + try { + const raw = sessionStorage.getItem(SWIPE_POSITION_KEY); + if (!raw) return []; + const parsed: unknown = JSON.parse(raw); + // A single record is the format written before positions were kept per viewer. + entries = Array.isArray(parsed) ? parsed : [parsed]; + } catch { + return []; + } + + const now = Date.now(); + const records = entries + .map(parseRecord) + .filter((r): r is SwipePosition => r !== null && now - r.savedAt <= SWIPE_POSITION_TTL_MS); + + if (records.length !== entries.length) { + try { + writeRecords(records); + } catch { + /* best-effort */ + } + } + return records; +} + /** - * Persist the current position: stores the scrollback from the front (index 0) - * through a small look-ahead past `index`, so `stories[index].id === storyId` holds - * and a reload rebuilds the list in feed order. Best-effort (quota / serialization - * failures are swallowed). + * Persist the current position for `record.viewer`, replacing that viewer's + * previous one: stores the scrollback from the front (index 0) through a small + * look-ahead past `index`, so `stories[index].id === storyId` holds and a reload + * rebuilds the list in feed order. Best-effort (quota / serialization failures + * are swallowed). */ export function saveSwipePosition(record: Omit): void { try { @@ -51,51 +124,37 @@ export function saveSwipePosition(record: Omit): void stories: windowed, savedAt: Date.now(), }; - sessionStorage.setItem(SWIPE_POSITION_KEY, JSON.stringify(payload)); + const others = readRecords().filter(r => !sameViewer(r.viewer, record.viewer)); + writeRecords([payload, ...others].slice(0, SWIPE_POSITION_MAX_VIEWERS)); } catch { /* quota / serialization — non-critical */ } } -/** Read the snapshot, or null if absent/corrupt/expired (expired entries are removed). */ -export function readSwipePosition(): SwipePosition | null { - try { - const raw = sessionStorage.getItem(SWIPE_POSITION_KEY); - if (!raw) return null; - - const parsed = JSON.parse(raw) as Partial; - if ( - !parsed || - typeof parsed.savedAt !== 'number' || - typeof parsed.storyId !== 'number' || - !parsed.viewer || - typeof parsed.viewer !== 'object' || - !Array.isArray(parsed.stories) - ) { - return null; - } - - if (Date.now() - parsed.savedAt > SWIPE_POSITION_TTL_MS) { - sessionStorage.removeItem(SWIPE_POSITION_KEY); - return null; - } - - return { - viewer: parsed.viewer, - storyId: parsed.storyId, - index: typeof parsed.index === 'number' ? parsed.index : 0, - scrollY: typeof parsed.scrollY === 'number' ? parsed.scrollY : 0, - stories: parsed.stories, - savedAt: parsed.savedAt, - }; - } catch { - return null; - } +/** + * The newest snapshot matching every given field (any snapshot when none are + * given), or null if there is none. Corrupt and expired entries are removed. + */ +export function readSwipePosition( + match: { viewer?: LocationState; storyId?: number } = {}, +): SwipePosition | null { + return ( + readRecords().find( + r => + (match.viewer === undefined || sameViewer(r.viewer, match.viewer)) && + (match.storyId === undefined || r.storyId === match.storyId), + ) ?? null + ); } -export function clearSwipePosition(): void { +/** Remove `viewer`'s snapshot, or every snapshot when no viewer is given. */ +export function clearSwipePosition(viewer?: LocationState): void { try { - sessionStorage.removeItem(SWIPE_POSITION_KEY); + if (viewer === undefined) { + sessionStorage.removeItem(SWIPE_POSITION_KEY); + } else { + writeRecords(readRecords().filter(r => !sameViewer(r.viewer, viewer))); + } } catch { /* best-effort */ }