From 55312ee22655f85e0e01616ce34214b5da1bc54a Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Mon, 8 Jun 2026 13:30:54 +0200 Subject: [PATCH] fix: restore mobile swipe position when returning from external links On a full reload (bfcache miss), the swipe index was lost and the story collapsed to index 0. Persist a durable per-tab snapshot (viewer, story id, scrollY, and a lean story list) to sessionStorage, then on mount re-find the story by id at its prior position with its neighbors. - Add swipePosition helper + SwipePosition type (30-min TTL, lean projection omitting text, snapshot taken from the feed front through a small look-ahead so a prepended restore preserves feed order) - Recover the originating viewer (feed/domain/user) on a stateless reload in MobileItemDetailWrapper - Seed the restored list into mergedStories and freeze the restore decision at mount so the list does not collapse on first swipe - Guard the injection fetch so a restored story is never re-fetched --- e2e/mobile-swipe.spec.ts | 93 +++++++ src/App.test.tsx | 127 +++++++++ src/App.tsx | 55 ++-- src/components/SwipeStoryViewer.test.tsx | 323 +++++++++++++++++++++++ src/components/SwipeStoryViewer.tsx | 131 +++++++-- src/types.ts | 13 + src/utils/swipePosition.test.ts | 187 +++++++++++++ src/utils/swipePosition.ts | 102 +++++++ 8 files changed, 992 insertions(+), 39 deletions(-) create mode 100644 src/App.test.tsx create mode 100644 src/utils/swipePosition.test.ts create mode 100644 src/utils/swipePosition.ts diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts index 2eb47c5..bd790a7 100644 --- a/e2e/mobile-swipe.spec.ts +++ b/e2e/mobile-swipe.spec.ts @@ -678,4 +678,97 @@ test.describe('Mobile Direct Item Access', () => { await expect(page.getByRole('link', { name: /back to home/i })).toBeVisible(); await expect(page).toHaveTitle(/Item not available.*HackerTok/); }); + + test('restores swipe position on the main feed after a full page reload', async ({ page }) => { + // The headline bfcache-miss scenario: swipe deep, then a FULL reload (in-memory + // feed state AND location.state are gone). The durable sessionStorage snapshot + // must restore the story at its prior index instead of collapsing it to 0. + // (Distinct from the goBack tests above, which keep the SPA — and its state — + // alive.) This describe's beforeEach does not clear storage, so the snapshot + // survives the reload. + await page.goto('/#/'); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); + + const container = page.getByTestId('swipe-container'); + await waitForSwipeReady(page, 6); + const panelWidth = await container.evaluate((el) => el.getBoundingClientRect().width); + + // Swipe to index 2 (item 12347 — "Why We Moved from React to htmx"). + await smoothScrollAndAwaitSettled(container, panelWidth); + await waitForScrollAtIndex(page, 1); + await smoothScrollAndAwaitSettled(container, panelWidth * 2); + await waitForScrollAtIndex(page, 2); + await expect(page).toHaveURL(/\/item\/12347/, { timeout: 5000 }); + + // Force the hide-time persist deterministically (pagehide's handler writes the + // snapshot unconditionally), and confirm it landed before reloading. + await page.evaluate(() => window.dispatchEvent(new Event('pagehide'))); + await expect + .poll(() => page.evaluate(() => sessionStorage.getItem('__swipe_pos'))) + .not.toBeNull(); + + await page.reload(); + + // After reload: no location.state, feed rebuilt from cache, snapshot restores + // index 2 — NOT index 0 (the bug). + await expect(page).toHaveURL(/\/item\/12347/, { timeout: 5000 }); + await waitForScrollAtIndex(page, 2); + await expectActiveSwipePanelText(page, 'Why We Moved from React to htmx', { minPanels: 3 }); + + await expect.poll(() => container.evaluate( + (el) => { + const panels = el.children; + for (let i = 0; i < panels.length; i++) { + if (panels[i].classList.contains('active')) return i; + } + return -1; + } + ), { timeout: 5000 }).toBe(2); + }); + + test('restores a domain feed after reload (recovers the whole feed, not one item)', async ({ page }) => { + // Domain feeds use a non-persisted in-memory cache, so a reload wipes the live + // list entirely. Without snapshot-driven viewer recovery the resolver would + // show only the single resolved item; Branch 4b must rebuild the domain viewer + // and restore the prior index with its neighbors. + await page.goto('/#/from/example.com'); + + const container = page.getByTestId('swipe-container'); + await expect(container).toBeVisible(); + // Mobile domain viewer replaces /#/from/:domain with /#/item/77777 (mockDomainItem). + await expect(page).toHaveURL(/\/item\/77777/, { timeout: 5000 }); + await waitForSwipeReady(page, 2); + + // Swipe to index 1 (first clone — objectID 77770). + const panelWidth = await container.evaluate((el) => el.getBoundingClientRect().width); + await smoothScrollAndAwaitSettled(container, panelWidth); + await waitForScrollAtIndex(page, 1); + await expect(page).toHaveURL(/\/item\/77770/, { timeout: 5000 }); + + await page.evaluate(() => window.dispatchEvent(new Event('pagehide'))); + await expect + .poll(() => page.evaluate(() => sessionStorage.getItem('__swipe_pos'))) + .not.toBeNull(); + + await page.reload(); + + // After reload the domain cache is empty and location.state is gone, but the + // snapshot recovers the domain viewer (Branch 4b) and restores index 1 with the + // full neighborhood (more than one panel — not collapsed to a single item). + await expect(page).toHaveURL(/\/item\/77770/, { timeout: 5000 }); + await waitForScrollAtIndex(page, 1); + + const panelCount = await page.locator('[data-testid="swipe-panel"]').count(); + expect(panelCount).toBeGreaterThan(1); + + await expect.poll(() => container.evaluate( + (el) => { + const panels = el.children; + for (let i = 0; i < panels.length; i++) { + if (panels[i].classList.contains('active')) return i; + } + return -1; + } + ), { timeout: 5000 }).toBe(1); + }); }); diff --git a/src/App.test.tsx b/src/App.test.tsx new file mode 100644 index 0000000..ac58c72 --- /dev/null +++ b/src/App.test.tsx @@ -0,0 +1,127 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { screen } from '@testing-library/react'; +import { Routes, Route } from 'react-router-dom'; +import { render } from './test/test-utils'; +import { MobileItemDetailWrapper } from './App'; +import { saveSwipePosition } from './utils/swipePosition'; +import { createStoryItem } from './test/factories'; +import type { LocationState, StoryItem } from './types'; +import type * as HnApi from './api/hn'; + +// Force the mobile branch of the wrapper. +vi.mock('./hooks/useIsMobile', () => ({ useIsMobile: () => true })); + +// Stub the heavy swipe viewers so we can assert *which* viewer the wrapper +// mounts (and with what props) without their data hooks / async state. +vi.mock('./components/SwipeStoryViewer', () => ({ + SwipeStoryViewer: ({ type, initialItemId }: { type: string; initialItemId?: string }) => ( +
+ ), +})); +vi.mock('./components/SwipeDomainStoryViewer', () => ({ + SwipeDomainStoryViewer: ({ domain, initialItemId }: { domain: string; initialItemId?: string }) => ( +
+ ), +})); +vi.mock('./components/SwipeUserSubmissionsViewer', () => ({ + SwipeUserSubmissionsViewer: ({ username, initialItemId }: { username: string; initialItemId?: string }) => ( +
+ ), +})); + +// The resolver fallback (Branch 5) calls fetchItemOnly; keep it pending so the +// resolver stays on its skeleton — a deterministic signal that we did NOT take +// the recovery branch, with no async state flip to await. +vi.mock('./api/hn', async (importOriginal) => ({ + ...(await importOriginal()), + fetchItemOnly: vi.fn(() => new Promise(() => { /* never resolves */ })), +})); + +function renderWrapper(id: number, state?: LocationState) { + return render( + + } /> + , + { initialEntries: [{ pathname: `/item/${id}`, state }] }, + ); +} + +function seedSnapshot(viewer: LocationState, storyId: number) { + const stories: StoryItem[] = [createStoryItem({ id: storyId })]; + saveSwipePosition({ viewer, storyId, index: 0, scrollY: 0, stories }); +} + +describe('MobileItemDetailWrapper — viewer recovery (stateless reload)', () => { + beforeEach(() => { + sessionStorage.clear(); + }); + + it('recovers the originating feed viewer from a matching snapshot (not the top resolver)', () => { + seedSnapshot({ from: 'best' }, 123); + + renderWrapper(123); + + const viewer = screen.getByTestId('feed-viewer'); + expect(viewer).toHaveAttribute('data-type', 'best'); + expect(viewer).toHaveAttribute('data-item', '123'); + }); + + it('recovers SwipeDomainStoryViewer from a fromDomain snapshot', () => { + seedSnapshot({ fromDomain: 'example.com' }, 123); + + renderWrapper(123); + + const viewer = screen.getByTestId('domain-viewer'); + expect(viewer).toHaveAttribute('data-domain', 'example.com'); + expect(viewer).toHaveAttribute('data-item', '123'); + }); + + it('recovers SwipeUserSubmissionsViewer from a fromUser snapshot', () => { + seedSnapshot({ fromUser: 'pg' }, 123); + + renderWrapper(123); + + const viewer = screen.getByTestId('user-viewer'); + expect(viewer).toHaveAttribute('data-username', 'pg'); + expect(viewer).toHaveAttribute('data-item', '123'); + }); + + it('falls back to the resolver when there is no snapshot', () => { + renderWrapper(123); + + // Resolver renders its own skeleton container while it classifies the item. + expect(screen.getByTestId('swipe-container')).toBeInTheDocument(); + expect(screen.queryByTestId('feed-viewer')).toBeNull(); + expect(screen.queryByTestId('domain-viewer')).toBeNull(); + expect(screen.queryByTestId('user-viewer')).toBeNull(); + }); + + 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 + + renderWrapper(123); + + expect(screen.getByTestId('swipe-container')).toBeInTheDocument(); + expect(screen.queryByTestId('feed-viewer')).toBeNull(); + }); + + it('prefers location.state over the snapshot (Branch 4 before 4b)', () => { + seedSnapshot({ from: 'best' }, 123); // snapshot says best... + + renderWrapper(123, { from: 'top' }); // ...but the live route state says top + + expect(screen.getByTestId('feed-viewer')).toHaveAttribute('data-type', 'top'); + }); + + it('falls through to the resolver when location.state names no viewer', () => { + // state is present (so the Branch 2–4 block runs) but carries no + // from/fromDomain/fromUser, so renderSwipeViewer returns null and the + // wrapper must fall through to the resolver rather than mounting a viewer. + renderWrapper(123, {}); + + expect(screen.getByTestId('swipe-container')).toBeInTheDocument(); + expect(screen.queryByTestId('feed-viewer')).toBeNull(); + expect(screen.queryByTestId('domain-viewer')).toBeNull(); + expect(screen.queryByTestId('user-viewer')).toBeNull(); + }); +}); diff --git a/src/App.tsx b/src/App.tsx index f1631bd..18040b6 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -18,6 +18,7 @@ import { SwipeUserSubmissionsViewer } from './components/SwipeUserSubmissionsVie import { SwipeCommentViewer } from './components/SwipeCommentViewer'; import { NetworkStatusProvider } from './context/NetworkStatusContext'; import { fetchItemOnly } from './api/hn'; +import { readSwipePosition } from './utils/swipePosition'; import type { FeedType, LocationState } from './types'; function MobileStoryListWrapper({ type }: { type: FeedType }) { @@ -67,12 +68,33 @@ function MobileUserSubmissionsWrapper() { return ; } +// Maps a viewer context to its swipe viewer (priority fromUser → fromDomain → from; +// written mutually exclusively). Shared by the location.state path (Branches 2–4) +// and snapshot recovery (4b); the `key` mirrors viewer identity so switching paths +// reuses the instance. `id` is the story id here (/item/:id), so it's initialItemId. +function renderSwipeViewer(viewer: LocationState, id: string | undefined): ReactNode { + if (viewer.fromUser) { + return ; + } + if (viewer.fromDomain) { + return ; + } + if (viewer.from) { + return ; + } + return null; +} + // Routes /item/:id to the correct mobile viewer based on `location.state` // (or the item type for direct URLs without state). -function MobileItemDetailWrapper() { +// Exported for focused unit testing of the viewer-recovery branch. +export function MobileItemDetailWrapper() { const { id } = useParams(); const isMobile = useIsMobile(); 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()); if (isMobile) { const state = location.state as LocationState | null; @@ -84,27 +106,20 @@ function MobileItemDetailWrapper() { return ; } - // Branch 2: Known user submissions → SwipeUserSubmissionsViewer. - // Ordered before fromDomain/from so /item/:id with fromUser anchors on - // the user's submissions list. Here `id` IS the story id (we're on - // /item/:id), so passing it as initialItemId is correct — distinct from - // MobileUserSubmissionsWrapper above where `id` is a username. - if (state?.fromUser) { - return ; - } - - // Branch 3: Known domain swipe → SwipeDomainStoryViewer. - // Ordered before the `from` branch so /item/:id with fromDomain picks up - // the domain viewer; `from`, `fromDomain`, and `fromUser` are written - // mutually exclusively by their respective viewers today. - if (state?.fromDomain) { - return ; + // Branches 2–4: viewer context from location.state (zero-latency path). + if (state) { + const viewer = renderSwipeViewer(state, id); + if (viewer) return viewer; } - // Branch 4: Known story feed → SwipeStoryViewer (existing zero-latency path) - if (state?.from) { - const type = state.from; - return ; + // Branch 4b: stateless reload — recover the viewer from the snapshot so + // non-`top` feeds (best/show/ask/domain/user) restore too. Snapshots come only + // from story viewers, so we skip the resolver's comment-vs-story fetch. Also + // fires for a fresh same-tab nav to a still-snapshotted id+viewer (intended: + // resume where you left off), not just back/reload. + if (recovered && id && recovered.storyId === Number(id)) { + const viewer = renderSwipeViewer(recovered.viewer, id); + if (viewer) return viewer; } // Branch 5: Direct URL (no state) → resolve type first diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx index 8ba5785..161d180 100644 --- a/src/components/SwipeStoryViewer.test.tsx +++ b/src/components/SwipeStoryViewer.test.tsx @@ -10,6 +10,9 @@ import { addToSessionViewed, VIEWED_DETAIL_TIMES_KEY, } from '../utils/viewedItems'; +import { saveSwipePosition, readSwipePosition } from '../utils/swipePosition'; +import { fetchItemOnly } from '../api/hn'; +import type * as HnApi from '../api/hn'; // 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 @@ -19,6 +22,14 @@ vi.mock('./FullScreenItem', () => ({ FullScreenItemSkeletonPanel: () =>
, })); +// Spy on the out-of-feed injection fetch so restore tests can assert it is NOT +// triggered for a story already held in the snapshot. A never-resolving promise +// keeps it inert if it were ever (incorrectly) called. +vi.mock('../api/hn', async (importOriginal) => ({ + ...(await importOriginal()), + fetchItemOnly: vi.fn(() => new Promise(() => { /* never resolves */ })), +})); + Object.defineProperty(window, 'innerWidth', { value: 375, writable: true }); beforeEach(() => { @@ -106,4 +117,316 @@ describe('SwipeStoryViewerCore — mount-snapshot filtering', () => { // An empty feed is never shown — the fallback restores the full list. expect(renderedPanelIds()).toEqual(['1', '2', '3']); }); +}); + +describe('SwipeStoryViewerCore — swipe-position restore', () => { + const baseProps = { + loading: false, + error: null, + hasMore: false, + loadMore: vi.fn().mockResolvedValue(undefined), + }; + + beforeEach(() => { + clearViewed(); + clearViewedTimes(); + clearSessionViewed(); + sessionStorage.clear(); + vi.clearAllMocks(); + }); + + function renderedPanelIds(): string[] { + return screen + .getAllByTestId('swipe-panel') + .map((el) => el.getAttribute('data-item-id') ?? ''); + } + + it('restores a deep story at its prior index with neighbors (not collapsed to index 0)', () => { + // Simulate a reload of a non-top feed: the live `stories` is empty (the + // in-memory cache is wiped) but the durable snapshot holds the neighborhood. + const restoredStories = Array.from({ length: 21 }, (_, i) => createStoryItem({ id: 100 + i })); + saveSwipePosition({ + viewer: { from: 'best' }, + storyId: 110, + index: 10, + scrollY: 0, + stories: restoredStories, + }); + + render( + , + ); + + const ids = renderedPanelIds(); + // The whole restored neighborhood is present, in its original order... + expect(ids).toEqual(restoredStories.map((s) => String(s.id))); + // ...with the landed story at its restored index, NOT forced to index 0. + expect(ids[10]).toBe('110'); + expect(ids[0]).toBe('100'); + }); + + it('restores a deep position in feed order (front stories stay at the front, not pushed behind)', () => { + // Regression for the reorder bug: the snapshot is saved from the FULL list the + // user swiped (front → anchor), and after a reload the live feed comes back + // restarting at the front. Prepending the snapshot must preserve feed order — the + // live front-stories are dups that drop out, so nothing gets shoved behind the + // anchor (previously a centered window stored only [anchor±R], pushing 0..anchor-R + // after it). + const fullList = Array.from({ length: 31 }, (_, i) => createStoryItem({ id: i })); + saveSwipePosition({ + viewer: { from: 'top' }, + storyId: 25, + index: 25, + scrollY: 0, + stories: fullList, + }); + + // After a reload the live feed restarts at page 0 (only the front of the list). + const liveFront = Array.from({ length: 20 }, (_, i) => createStoryItem({ id: i })); + + render( + , + ); + + const ids = renderedPanelIds().map(Number); + // Strictly ascending from the front — no front block reordered past the anchor. + expect(ids[0]).toBe(0); + expect(ids).toEqual([...ids].sort((a, b) => a - b)); + // The anchor sits at its true position, after the full front scrollback. + expect(ids[25]).toBe(25); + }); + + it('does not re-fetch a restored story (no injection fetch / error screen)', () => { + const restoredStories = Array.from({ length: 5 }, (_, i) => createStoryItem({ id: 200 + i })); + saveSwipePosition({ + viewer: { from: 'top' }, + storyId: 202, + index: 2, + scrollY: 0, + stories: restoredStories, + }); + + render( + , + ); + + // The story is served from the snapshot, so the out-of-feed fetch is skipped + // and the good list renders rather than the injected-error screen. + expect(fetchItemOnly).not.toHaveBeenCalled(); + expect(screen.getByTestId('swipe-container')).toBeInTheDocument(); + expect(renderedPanelIds()).toContain('202'); + }); + + it('ignores a snapshot saved by a different viewer (no false restore)', () => { + // Snapshot was written in the domain viewer, but we mount the top feed. + const restoredStories = Array.from({ length: 5 }, (_, i) => createStoryItem({ id: 300 + i })); + saveSwipePosition({ + viewer: { fromDomain: 'example.com' }, + storyId: 302, + index: 2, + scrollY: 0, + stories: restoredStories, + }); + + const liveStories = [ + createStoryItem({ id: 302, title: 'Live 302' }), + createStoryItem({ id: 9, title: 'Other' }), + ]; + + render( + , + ); + + // sameViewer fails (domain snapshot vs top feed) → not restoring → the + // restored-only neighbors (300, 301, 303, 304) must NOT be seeded. + const ids = renderedPanelIds(); + expect(ids).not.toContain('300'); + expect(ids).not.toContain('304'); + }); + + it('regression: a fresh direct link with no snapshot still anchors the story to index 0', () => { + // No snapshot in sessionStorage and no location.state → fresh shared link. + const stories = [ + createStoryItem({ id: 1, title: 'A' }), + createStoryItem({ id: 2, title: 'B' }), + createStoryItem({ id: 3, title: 'C' }), + createStoryItem({ id: 4, title: 'D' }), + ]; + + render( + , + ); + + // Story #3 is anchored to index 0 — today's behavior, unchanged. + expect(renderedPanelIds()[0]).toBe('3'); + }); + + it('persists a snapshot of the current story when the page hides', () => { + const stories = [ + createStoryItem({ id: 1, title: 'A' }), + createStoryItem({ id: 2, title: 'B' }), + createStoryItem({ id: 3, title: 'C' }), + ]; + + render( + , + ); + + // Nothing is written until the page is actually hidden. + expect(readSwipePosition()).toBeNull(); + + window.dispatchEvent(new Event('pagehide')); + + const saved = readSwipePosition(); + expect(saved).not.toBeNull(); + expect(saved!.viewer).toEqual({ from: 'top' }); + // currentIndex is 0 (no anchor), so the landed story is the first one. + expect(saved!.storyId).toBe(1); + expect(saved!.stories.map((s) => s.id)).toEqual([1, 2, 3]); + }); + + it('consumes (clears) the snapshot once the restore scroll is applied', () => { + const restoredStories = Array.from({ length: 5 }, (_, i) => createStoryItem({ id: 400 + i })); + saveSwipePosition({ + viewer: { from: 'top' }, + storyId: 402, + index: 2, + scrollY: 0, + stories: restoredStories, + }); + expect(readSwipePosition()).not.toBeNull(); + + render( + , + ); + + // scroll-init located the story and consumed the one-shot snapshot so a later + // unrelated reload can't replay it. + expect(readSwipePosition()).toBeNull(); + }); + + it('falls back to the saved index (and still consumes) when the story id is not locatable', () => { + // Drifted/corrupted snapshot: storyId is absent from the stored stories, so + // findIndex(storyId) would miss. Written directly to break the normally + // guaranteed storyId-in-stories invariant. + const restoredStories = [ + createStoryItem({ id: 500 }), + createStoryItem({ id: 501 }), + createStoryItem({ id: 502 }), + ]; + saveSwipePosition({ + viewer: { from: 'top' }, + storyId: 999, + index: 1, + scrollY: 0, + stories: restoredStories, + }); + + render( + , + ); + + // Without the index fallback findIndex(999) === -1 would skip the restore and + // leave the snapshot intact; the fallback resolves the index and clears it. + expect(readSwipePosition()).toBeNull(); + }); + + it('dedupes the restored window against an overlapping live feed (restored order first, no dup ids)', () => { + // Main-feed reload model: the live feed is rebuilt from the localStorage cache + // and overlaps the restored window. Restored stories must come first, live-only + // extras append after, and no id may appear twice (panels key on story.id, so a + // duplicate id breaks rendering). + const restoredStories = Array.from({ length: 5 }, (_, i) => createStoryItem({ id: 700 + i })); + saveSwipePosition({ + viewer: { from: 'top' }, + storyId: 702, + index: 2, + scrollY: 0, + stories: restoredStories, + }); + + // Live feed shares 700–702 (overlap) and adds one fresh id (800). + const liveStories = [ + createStoryItem({ id: 700 }), + createStoryItem({ id: 701 }), + createStoryItem({ id: 702 }), + createStoryItem({ id: 800 }), + ]; + + render( + , + ); + + const ids = renderedPanelIds(); + expect(ids).toEqual(['700', '701', '702', '703', '704', '800']); + expect(new Set(ids).size).toBe(ids.length); // no duplicates + expect(ids[2]).toBe('702'); // restored story stays at its prior index + }); + + it('keeps restored neighbors that are in the recently-viewed hide set', () => { + // Neighbors viewed in a prior (but still recent) session sit in the localStorage + // hide set without being in the session set. The restored-id exemption must keep + // them so the restored neighborhood does not collapse on reload. + const restoredStories = Array.from({ length: 5 }, (_, i) => createStoryItem({ id: 600 + i })); + saveSwipePosition({ + viewer: { from: 'top' }, + storyId: 602, + index: 2, + scrollY: 0, + stories: restoredStories, + }); + + // Mark two restored neighbors as recently-viewed (localStorage hide window), + // WITHOUT adding them to the session set — must be set before mount. + const future = Date.now() + 10 * 60 * 60 * 1000; + localStorage.setItem( + VIEWED_DETAIL_TIMES_KEY, + JSON.stringify({ '600': future, '601': future }), + ); + + render( + , + ); + + // Without the exemption, 600 & 601 would be filtered out; they must remain. + expect(renderedPanelIds()).toEqual(['600', '601', '602', '603', '604']); + }); + + it('restores the saved vertical scroll offset when consuming the snapshot', () => { + const restoredStories = Array.from({ length: 5 }, (_, i) => createStoryItem({ id: 900 + i })); + saveSwipePosition({ + viewer: { from: 'top' }, + storyId: 902, + index: 2, + scrollY: 240, + stories: restoredStories, + }); + + render( + , + ); + + expect(window.scrollTo).toHaveBeenCalledWith(0, 240); + }); + + it('persists a snapshot on visibilitychange → hidden', () => { + const stories = [createStoryItem({ id: 1 }), createStoryItem({ id: 2 })]; + + render( + , + ); + + expect(readSwipePosition()).toBeNull(); + + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' }); + try { + document.dispatchEvent(new Event('visibilitychange')); + } finally { + delete (document as { visibilityState?: unknown }).visibilityState; + } + + const saved = readSwipePosition(); + expect(saved?.storyId).toBe(1); + expect(saved?.viewer).toEqual({ from: 'top' }); + }); }); \ No newline at end of file diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx index 99adc32..e6d35aa 100644 --- a/src/components/SwipeStoryViewer.tsx +++ b/src/components/SwipeStoryViewer.tsx @@ -9,12 +9,22 @@ import { useNetworkStatus } from '../hooks/useNetworkStatus'; import { useAutoRetry } from '../hooks/useAutoRetry'; import { fetchItemOnly, NotFoundError } from '../api/hn'; import { getFilteredViewedIds, getSessionViewedIds } from '../utils/viewedItems'; +import { readSwipePosition, saveSwipePosition, clearSwipePosition } from '../utils/swipePosition'; import { useViewDwell } from '../hooks/useViewDwell'; import { FEED_TYPE_TITLES } from '../config/feedTypes'; 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[]; @@ -62,6 +72,22 @@ export function SwipeStoryViewerCore({ const locationState = location.state as LocationState | null; const initialItemIdNum = initialItemId != null ? Number(initialItemId) : undefined; + // Durable restore snapshot (sessionStorage) — survives a full reload (bfcache miss). + // FREEZE at mount: `initialItemIdNum` changes on the first swipe (the URL-update + // 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 isRestoringPosition = restoreSnapshot !== null; + const restoredStories = restoreSnapshot?.stories ?? null; + const [injectedStory, setInjectedStory] = useState(null); const [injectedLoading, setInjectedLoading] = useState(false); const [injectedError, setInjectedError] = useState(null); @@ -73,7 +99,10 @@ export function SwipeStoryViewerCore({ // Recognizes `from` (feed), `fromDomain` (domain), and `fromUser` (user // submissions) — any of those signals a history nav and suppresses anchoring. const [anchorStoryId, setAnchorStoryId] = useState(() => { - const isHistoryNav = !!(locationState?.from ?? locationState?.fromDomain ?? locationState?.fromUser); + // A matching snapshot counts as history nav: on a stateless reload `locationState` + // is null, so `isRestoringPosition` is what suppresses the index-0 anchor. + const isHistoryNav = isRestoringPosition || + !!(locationState?.from ?? locationState?.fromDomain ?? locationState?.fromUser); return isHistoryNav ? null : initialItemIdNum ?? null; }); const lastInitialStoryIdRef = useRef(initialItemId); @@ -89,14 +118,31 @@ export function SwipeStoryViewerCore({ // Stories in localStorage but NOT sessionStorage are filtered const [recentlyViewedOnMount] = useState(() => getFilteredViewedIds()); const [sessionViewedOnMount] = useState(() => getSessionViewedIds()); + + // restoredStories is frozen for the mount, so build this id-set once rather + // than on every per-swipe mergedStories recompute. + const restoredIds = useMemo( + () => (restoredStories ? new Set(restoredStories.map(s => s.id)) : null), + [restoredStories], + ); // Merge injected story (if any) with feed stories, avoiding duplicates // Also filter out recently-viewed stories (unless viewed this session) // IMPORTANT: If anchorStoryId is set, that story is moved to index 0 const mergedStories = useMemo(() => { + // Restoring: seed the list with the restored stories first, then live stories + // not already present (id-dedup is mandatory — panels key on story.id). The + // snapshot holds the scrollback from the front (index 0), so prepending it keeps + // feed order: live front-stories are dups and drop out, nothing is sorted behind + // the anchor. Frozen for the mount so the neighborhood survives feeds whose live + // `stories` restart at page 0 after a reload; loadMore appends past it. + const baseStories = restoredStories + ? [...restoredStories, ...stories.filter(s => !restoredIds!.has(s.id))] + : stories; + // Find anchor story in feed (the story that should be first) const anchorStory = anchorStoryId - ? stories.find(s => s.id === anchorStoryId) + ? baseStories.find(s => s.id === anchorStoryId) : null; // Priority for first position: @@ -108,8 +154,8 @@ export function SwipeStoryViewerCore({ const firstStory = anchorStory ?? (shouldUseInjectedStory ? injectedStory : null); let result = firstStory - ? [firstStory, ...stories.filter(s => s.id !== firstStory.id)] - : stories; + ? [firstStory, ...baseStories.filter(s => s.id !== firstStory.id)] + : baseStories; // Also include injectedStory in the list (for swiping back to it) // but only if it's not already the firstStory @@ -121,18 +167,20 @@ export function SwipeStoryViewerCore({ // - firstStory (linked story at anchor position) // - injectedStory (so user can swipe back to it) // - initialItemId (current URL - browser back/forward) + // - restored stories (keep the neighborhood intact despite hide windows) // - stories viewed THIS session (in sessionStorage) const filtered = result.filter(story => story === firstStory || story === injectedStory || story.id === initialItemIdNum || + (restoredIds?.has(story.id) ?? false) || sessionViewedOnMount.has(story.id) || !recentlyViewedOnMount.has(story.id) ); // Fallback: if all filtered out, show everything return filtered.length > 0 ? filtered : result; - }, [injectedStory, stories, anchorStoryId, initialItemIdNum, sessionViewedOnMount, recentlyViewedOnMount]); + }, [injectedStory, stories, anchorStoryId, initialItemIdNum, sessionViewedOnMount, recentlyViewedOnMount, restoredStories, restoredIds]); // Defer listener attachment until the main container (with ref) actually renders. // On cold start (no localStorage cache), stories start empty → loading skeleton renders @@ -184,8 +232,11 @@ export function SwipeStoryViewerCore({ useEffect(() => { if (!initialItemId) return; - // Don't wait for stories to load - fetch immediately if this is a direct navigation - const storyInList = stories.some(s => s.id === initialItemIdNum); + // Don't wait for stories to load — fetch immediately on direct navigation. + // Count the restored snapshot too: on a reload live `stories` may not hold the + // story, and a needless re-fetch could paint an error screen over a good restore. + const storyInList = stories.some(s => s.id === initialItemIdNum) || + (restoredStories?.some(s => s.id === initialItemIdNum) ?? false); if (storyInList) { // Story found in feed, clear injected story and stale error state if (injectedStory && injectedStory.id === initialItemIdNum) { @@ -249,7 +300,7 @@ export function SwipeStoryViewerCore({ fetchedStoryIdRef.current = null; } }; - }, [initialItemId, initialItemIdNum, stories, injectedStory, injectedError]); + }, [initialItemId, initialItemIdNum, stories, injectedStory, injectedError, restoredStories]); // Scroll to index 0 when injected story arrives and is anchored // This handles: user navigates to out-of-feed story, we fetch it, then scroll to it @@ -270,14 +321,37 @@ export function SwipeStoryViewerCore({ // Uses both pageshow (for bfcache) and visibilitychange (for tab switches) // pageshow fires BEFORE first paint on bfcache restore - critical for preventing flash const savedIndexOnHideRef = useRef(null); + // Synced via effect so the long-lived hide listener reads the latest list/viewer + // without re-subscribing (avoids a stale closure). + const mergedStoriesRef = useRef(mergedStories); + const backStateRef = useRef(backState); + useEffect(() => { + mergedStoriesRef.current = mergedStories; + backStateRef.current = backState; + }); 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; try { sessionStorage.setItem('__swipe_scrollY', String(window.scrollY)); } catch { /* quota exceeded — non-critical */ } + persistSnapshot(); }; // Restore position when page is shown from bfcache (persisted=true) @@ -300,6 +374,7 @@ export function SwipeStoryViewerCore({ try { sessionStorage.setItem('__swipe_scrollY', String(window.scrollY)); } catch { /* quota exceeded — non-critical */ } + persistSnapshot(); } else if (document.visibilityState === 'visible' && savedIndexOnHideRef.current !== null) { const targetIndex = savedIndexOnHideRef.current; savedIndexOnHideRef.current = null; @@ -385,15 +460,31 @@ export function SwipeStoryViewerCore({ if (mergedStories.length === 0) return; - const idx = mergedStories.findIndex(s => s.id === targetStoryId); + let idx = mergedStories.findIndex(s => s.id === targetStoryId); + // Defensive fallback for a drifted/corrupted snapshot: the target id normally + // lives in the restored prefix, but if findIndex misses, use the saved index so + // the restore still resolves (and the snapshot clears). + if (idx < 0 && restoreSnapshot && restoreSnapshot.index >= 0 && restoreSnapshot.index < mergedStories.length) { + idx = restoreSnapshot.index; + } if (idx >= 0) { pendingScrollToStoryIdRef.current = null; hasInitializedScrollRef.current = true; if (idx !== currentIndexRef.current) { scrollToIndex(idx); } + // Consume the snapshot once: restore the best-effort vertical offset (may + // clamp until comments load), then clear it. Use the captured `restoreSnapshot` + // (not a fresh read) so this survives clearSwipePosition() and StrictMode's + // double-invoke — clearing sessionStorage doesn't disturb the frozen base. + if (restoreSnapshot) { + if (restoreSnapshot.scrollY > 0) { + window.scrollTo(0, restoreSnapshot.scrollY); + } + clearSwipePosition(); + } } - }, [mergedStories, initialItemId, initialItemIdNum, anchorStoryId, scrollToIndex, currentIndexRef]); + }, [mergedStories, initialItemId, initialItemIdNum, anchorStoryId, scrollToIndex, currentIndexRef, restoreSnapshot]); usePrefetchItems(currentIndex, mergedStories, 6); @@ -536,9 +627,14 @@ export function SwipeStoryViewerCore({ ); } - // Virtualization: only render panels within this window around currentIndex - // Buffer of 2 ensures smooth swiping (pre-rendered neighbors) while keeping DOM light - // Total rendered: up to 5 panels (current + 2 before + 2 after) + // Virtualization: render heavy content (FullScreenItem ≈ 100+ DOM nodes) only for + // panels within ±BUFFER of currentIndex. Out-of-window panels keep their bare + //
(so container.children stays 1:1 with story index for the gesture engine) + // but render NO content — they're display:none until activated, and the gesture + // only ever reveals current ± 1, which is always in-window. This keeps the live + // DOM ~constant regardless of feed length: a deep/restored list of N stories costs + // ~5 content panels, not N. (A far panel can only become active via a layout-effect + // jump — restore/history-nav — which recenters the window before paint, so no flash.) const VIRTUALIZE_BUFFER = 2; return ( @@ -552,8 +648,8 @@ export function SwipeStoryViewerCore({ const isWithinWindow = distance <= VIRTUALIZE_BUFFER; // Current + adjacent panels are priority (fetch in parallel for smooth swiping) const isPriority = distance <= 1; - // Far panels (distance > 1) defer comment fetch entirely to reduce concurrent requests - // Note: linked story is always at index 0 (reordered), so it's never deferred + // Far panels (distance > 1) defer comment fetch to reduce concurrent requests; + // the active panel (distance 0) is always priority, so it's never deferred. const deferComments = distance > 1; return ( @@ -563,16 +659,13 @@ export function SwipeStoryViewerCore({ data-testid="swipe-panel" data-item-id={story.id} > - {isWithinWindow ? ( + {isWithinWindow && ( - ) : ( - // Skeleton placeholder for non-visible panels (consistent UX during quick swipes) - )}
); diff --git a/src/types.ts b/src/types.ts index b1c737c..3f22b60 100644 --- a/src/types.ts +++ b/src/types.ts @@ -161,6 +161,19 @@ export interface LocationState { isComment?: boolean; } +// Durable per-tab snapshot (sessionStorage) for restoring the mobile swipe viewer +// after a full reload (bfcache miss). `stories` is a lean projection (omits `text`) +// of the scrollback from the front through a small look-ahead; `index` is the anchor's +// position in it and advisory — restore re-finds by `storyId`. +export interface SwipePosition { + viewer: LocationState; + storyId: number; + index: number; + scrollY: number; + stories: StoryItem[]; + savedAt: number; +} + // Firebase /user/:id.json shape. `delay` omitted (vestigial HN field). export interface UserProfile { id: string; diff --git a/src/utils/swipePosition.test.ts b/src/utils/swipePosition.test.ts new file mode 100644 index 0000000..3fa3498 --- /dev/null +++ b/src/utils/swipePosition.test.ts @@ -0,0 +1,187 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { + saveSwipePosition, + readSwipePosition, + clearSwipePosition, + SWIPE_POSITION_KEY, + SWIPE_POSITION_AHEAD, +} from './swipePosition'; +import { createStoryItem } from '../test/factories'; +import type { StoryItem } from '../types'; + +describe('swipePosition', () => { + beforeEach(() => { + sessionStorage.clear(); + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-02-25T12:00:00Z')); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + const stories: StoryItem[] = [ + createStoryItem({ id: 1, title: 'A' }), + createStoryItem({ id: 2, title: 'B' }), + createStoryItem({ id: 3, title: 'C' }), + ]; + + describe('save / read roundtrip', () => { + it('persists and reads back a snapshot', () => { + saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 320, stories }); + + const result = readSwipePosition()!; + + expect(result).not.toBeNull(); + expect(result.viewer).toEqual({ from: 'top' }); + expect(result.storyId).toBe(2); + expect(result.scrollY).toBe(320); + expect(result.stories.map(s => s.id)).toEqual([1, 2, 3]); + expect(result.savedAt).toBe(Date.now()); + }); + + it('rewrites index window-relative so stories[index].id === storyId', () => { + saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories }); + + const result = readSwipePosition()!; + expect(result.stories[result.index].id).toBe(2); + }); + + it('returns null when nothing is stored', () => { + expect(readSwipePosition()).toBeNull(); + }); + }); + + describe('lean projection', () => { + it('omits the heavy `text` body from stored stories', () => { + const withText = createStoryItem({ id: 9, type: 'ask', text: '

huge ask body

' }); + saveSwipePosition({ viewer: { from: 'ask' }, storyId: 9, index: 0, scrollY: 0, stories: [withText] }); + + const result = readSwipePosition()!; + expect(result.stories[0]).not.toHaveProperty('text'); + // The fields used by the list/title still survive. + expect(result.stories[0].id).toBe(9); + expect(result.stories[0].type).toBe('ask'); + }); + }); + + describe('window: full scrollback from the front + bounded look-ahead', () => { + it('keeps the whole scrollback from the front and only a bounded look-ahead', () => { + const big: StoryItem[] = Array.from({ length: 200 }, (_, i) => createStoryItem({ id: i })); + saveSwipePosition({ viewer: { from: 'top' }, storyId: 100, index: 100, scrollY: 0, stories: big }); + + const result = readSwipePosition()!; + // Behind the anchor: everything from the front (index 0) is preserved... + expect(result.stories[0].id).toBe(0); + expect(result.index).toBe(100); + expect(result.stories[result.index].id).toBe(100); + // ...ahead of it: only a bounded look-ahead, so the list can't grow unbounded. + expect(result.stories.length).toBe(100 + SWIPE_POSITION_AHEAD + 1); + expect(result.stories[result.stories.length - 1].id).toBe(100 + SWIPE_POSITION_AHEAD); + }); + + it('preserves feed order from the front so a prepended restore cannot reorder it', () => { + const big: StoryItem[] = Array.from({ length: 50 }, (_, i) => createStoryItem({ id: i })); + saveSwipePosition({ viewer: { from: 'top' }, storyId: 30, index: 30, scrollY: 0, stories: big }); + + const result = readSwipePosition()!; + expect(result.stories.map(s => s.id)).toEqual( + Array.from({ length: 30 + SWIPE_POSITION_AHEAD + 1 }, (_, i) => i), + ); + }); + + it('does not pad ahead when the anchor is near the end of the feed', () => { + const big: StoryItem[] = Array.from({ length: 200 }, (_, i) => createStoryItem({ id: i })); + saveSwipePosition({ viewer: { from: 'top' }, storyId: 198, index: 198, scrollY: 0, stories: big }); + + const result = readSwipePosition()!; + expect(result.stories[result.stories.length - 1].id).toBe(199); // clamped to feed end + expect(result.stories[result.index].id).toBe(198); + }); + }); + + describe('TTL', () => { + it('returns the snapshot within the 30-minute window', () => { + saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories }); + + vi.advanceTimersByTime(29 * 60 * 1000); + + expect(readSwipePosition()).not.toBeNull(); + }); + + it('expires (and removes) the snapshot after 30 minutes', () => { + saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories }); + + vi.advanceTimersByTime(31 * 60 * 1000); + + expect(readSwipePosition()).toBeNull(); + expect(sessionStorage.getItem(SWIPE_POSITION_KEY)).toBeNull(); + }); + }); + + describe('corruption / shape tolerance', () => { + it('returns null for corrupted JSON', () => { + sessionStorage.setItem(SWIPE_POSITION_KEY, 'not valid json'); + expect(readSwipePosition()).toBeNull(); + }); + + it('returns null when required fields are missing or malformed', () => { + sessionStorage.setItem(SWIPE_POSITION_KEY, JSON.stringify({ storyId: 2, savedAt: Date.now() })); + expect(readSwipePosition()).toBeNull(); + + sessionStorage.setItem( + SWIPE_POSITION_KEY, + JSON.stringify({ viewer: { from: 'top' }, storyId: 'nope', stories: [], savedAt: Date.now() }), + ); + expect(readSwipePosition()).toBeNull(); + }); + }); + + describe('quota tolerance', () => { + it('does not throw when sessionStorage.setItem fails', () => { + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new DOMException('QuotaExceededError'); + }); + + expect(() => + saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories }), + ).not.toThrow(); + }); + }); + + describe('field defaults', () => { + it('defaults index and scrollY to 0 when absent but the record is otherwise valid', () => { + sessionStorage.setItem( + SWIPE_POSITION_KEY, + JSON.stringify({ viewer: { from: 'top' }, storyId: 2, stories: [{ id: 2 }], savedAt: Date.now() }), + ); + + const result = readSwipePosition()!; + expect(result).not.toBeNull(); + expect(result.index).toBe(0); + expect(result.scrollY).toBe(0); + }); + + it('returns null when viewer is present but not an object', () => { + sessionStorage.setItem( + SWIPE_POSITION_KEY, + JSON.stringify({ viewer: 'top', storyId: 2, stories: [], savedAt: Date.now() }), + ); + + expect(readSwipePosition()).toBeNull(); + }); + }); + + describe('clearSwipePosition', () => { + it('removes a stored snapshot', () => { + saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories }); + clearSwipePosition(); + expect(readSwipePosition()).toBeNull(); + }); + + it('does not throw when nothing is stored', () => { + expect(() => clearSwipePosition()).not.toThrow(); + }); + }); +}); diff --git a/src/utils/swipePosition.ts b/src/utils/swipePosition.ts new file mode 100644 index 0000000..5e02e48 --- /dev/null +++ b/src/utils/swipePosition.ts @@ -0,0 +1,102 @@ +import type { StoryItem, SwipePosition } from '../types'; + +/** + * Durable per-tab swipe-position snapshot (sessionStorage). Survives 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." + */ + +export const SWIPE_POSITION_KEY = '__swipe_pos'; + +// Matches the existing list session-state window (getListSessionState). +const SWIPE_POSITION_TTL_MS = 30 * 60 * 1000; + +// How many stories to keep AHEAD of the anchor. Behind it we store the whole +// scrollback (from index 0), so a restore rebuilds the list in feed order — +// prepending it can't push live front-stories behind the anchor. Ahead, a small +// look-ahead suffices; loadMore refills as the user swipes forward. +export const SWIPE_POSITION_AHEAD = 10; + +/** Lean projection: omits `text` (the heavy Ask/Show HTML body); FullScreenItem re-fetches. */ +function projectStory(s: StoryItem): StoryItem { + return { + id: s.id, + type: s.type, + title: s.title, + url: s.url, + points: s.points, + author: s.author, + createdAt: s.createdAt, + commentCount: s.commentCount, + }; +} + +/** + * 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). + */ +export function saveSwipePosition(record: Omit): void { + try { + const { stories, index } = record; + const end = Math.min(stories.length, index + SWIPE_POSITION_AHEAD + 1); + const windowed = stories.slice(0, end).map(projectStory); + + const payload: SwipePosition = { + viewer: record.viewer, + storyId: record.storyId, + index, + scrollY: record.scrollY, + stories: windowed, + savedAt: Date.now(), + }; + sessionStorage.setItem(SWIPE_POSITION_KEY, JSON.stringify(payload)); + } 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; + } +} + +export function clearSwipePosition(): void { + try { + sessionStorage.removeItem(SWIPE_POSITION_KEY); + } catch { + /* best-effort */ + } +}