From a7c35a85538bd19a0aaebbc20fe70c36268f3f50 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Wed, 4 Nov 2026 13:27:09 +0100 Subject: [PATCH 1/4] fix: keep the phone's comment viewer on its comment after a retry When a comment's siblings failed to load, the viewer still started the swipe, on the one-comment list the failed load left. The automatic retry then brought in the siblings, but with the swipe already started the viewer showed the first of them and moved the URL there, away from the comment that was opened. The swipe now starts only once the siblings load without an error. --- src/components/SwipeCommentViewer.test.tsx | 18 ++++++++++++++++++ src/components/SwipeCommentViewer.tsx | 7 ++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/components/SwipeCommentViewer.test.tsx b/src/components/SwipeCommentViewer.test.tsx index 3734f8c..8ccb09d 100644 --- a/src/components/SwipeCommentViewer.test.tsx +++ b/src/components/SwipeCommentViewer.test.tsx @@ -331,6 +331,24 @@ describe('SwipeCommentViewer', () => { expect(paths).toEqual(['/item/1003', '/item/3101']); }); + it('stays on the comment it was opened on when its siblings load on a retry', async () => { + let parentReads = 0; + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345 && parentReads++ === 0) throw new Error('Network error'); + return defaultItems[Number(id)] ?? null; + }); + + render(, { + initialEntries: [{ pathname: '/item/1003', state: { isComment: true } }], + }); + + // The retry waits out a 2s backoff. + await waitFor(() => { + expect(screen.getAllByTestId('swipe-panel')).toHaveLength(4); + expect(activePanelId()).toBe('1003'); + }, { timeout: 5000 }); + }, 10000); + it('sets data-item-id on each panel', async () => { render(, { initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }], diff --git a/src/components/SwipeCommentViewer.tsx b/src/components/SwipeCommentViewer.tsx index 9339faa..0127a74 100644 --- a/src/components/SwipeCommentViewer.tsx +++ b/src/components/SwipeCommentViewer.tsx @@ -71,10 +71,11 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps } }, [initialCommentId]); - // Scroll-init: scroll to correct position once siblings are loaded + // Scroll-init: scroll to correct position once siblings are loaded. A failed + // load leaves the list at the one comment, so this waits for the retry. useLayoutEffect(() => { if (hasInitializedScrollRef.current) return; - if (siblingIds.length === 0 || loading) return; + if (siblingIds.length === 0 || loading || error) return; const idx = siblingIds.indexOf(Number(initialCommentId)); const targetIdx = idx >= 0 ? idx : initialIndex; @@ -82,7 +83,7 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps hasInitializedScrollRef.current = true; setScrollInitialized(true); scrollToIndex(targetIdx); - }, [siblingIds, loading, initialCommentId, initialIndex, scrollToIndex]); + }, [siblingIds, loading, error, initialCommentId, initialIndex, scrollToIndex]); // URL update on swipe — only after scroll position is initialized. // Uses scrollInitialized state (not ref) so it's batched with setCurrentIndex From 7afc97897d4b4d57df8be98afffb947b6ab917e8 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Wed, 4 Nov 2026 13:28:41 +0100 Subject: [PATCH 2/4] perf: show the comment a phone opens while its siblings load The swipe comment viewer showed a skeleton until it had read the comment and its parent from Firebase for the sibling list, and only then started loading the comment itself. The comment now shows as the only panel while the siblings load, and loads alongside them. Once they're in, the swipe starts on that same panel: it stays mounted, isn't fetched again, and keeps the reader's place in it. useSwipeScroll gets `resetToIndex` for this, which switches to the new list without moving the page. While the siblings retry after a failed load, the comment stays on screen instead of a skeleton. On "Ask HN: Who wants to be hired? (November 2026)" a comment now shows after 0.8-1.0s instead of 1.2s, or 2.3s instead of 2.7-2.8s on slow 4G. The swipe is ready when it was before. --- src/components/SwipeCommentViewer.test.tsx | 37 ++++++++++++++++ src/components/SwipeCommentViewer.tsx | 50 +++++++++------------- src/hooks/useSwipeScroll.test.ts | 24 +++++++++++ src/hooks/useSwipeScroll.ts | 14 ++++++ 4 files changed, 96 insertions(+), 29 deletions(-) diff --git a/src/components/SwipeCommentViewer.test.tsx b/src/components/SwipeCommentViewer.test.tsx index 8ccb09d..6dee730 100644 --- a/src/components/SwipeCommentViewer.test.tsx +++ b/src/components/SwipeCommentViewer.test.tsx @@ -8,6 +8,7 @@ import { http, HttpResponse } from 'msw'; import { server } from '../mocks/server'; import { hnSdk } from '../api/hnSdk'; import { __resetFetchCachesForTests } from '../api/hn'; +import { mockAlgoliaCommentItem1003 } from '../mocks/handlers'; import { ALGOLIA_API } from '../config/api'; import type { FirebaseItem } from '../types'; @@ -331,6 +332,42 @@ describe('SwipeCommentViewer', () => { expect(paths).toEqual(['/item/1003', '/item/3101']); }); + it('shows the comment it was opened on while its siblings load, and keeps it when they land', async () => { + let releaseParent!: () => void; + const parentRead = new Promise(resolve => { releaseParent = resolve; }); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345) await parentRead; + return defaultItems[Number(id)] ?? null; + }); + let commentFetches = 0; + server.use( + http.get(`${ALGOLIA_API}/items/1003`, () => { + commentFetches++; + return HttpResponse.json(mockAlgoliaCommentItem1003); + }), + ); + + render(, { + initialEntries: [{ pathname: '/item/1003', state: { isComment: true } }], + }); + + expect(await screen.findByText(mockAlgoliaCommentItem1003.text)).toBeInTheDocument(); + expect(screen.getAllByTestId('swipe-panel')).toHaveLength(1); + expect(activePanelId()).toBe('1003'); + + window.scrollTo = vi.fn(); + releaseParent(); + + // Third of [1001, 1002, 1003, 1004]. + await waitFor(() => { + expect(screen.getAllByTestId('swipe-panel')).toHaveLength(4); + }); + expect(activePanelId()).toBe('1003'); + expect(screen.getByText(mockAlgoliaCommentItem1003.text)).toBeInTheDocument(); + expect(commentFetches).toBe(1); + expect(window.scrollTo).not.toHaveBeenCalled(); + }); + it('stays on the comment it was opened on when its siblings load on a retry', async () => { let parentReads = 0; vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { diff --git a/src/components/SwipeCommentViewer.tsx b/src/components/SwipeCommentViewer.tsx index 0127a74..5f23265 100644 --- a/src/components/SwipeCommentViewer.tsx +++ b/src/components/SwipeCommentViewer.tsx @@ -33,7 +33,7 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps const { containerRef, currentIndex, - scrollToIndex, + resetToIndex, } = useSwipeScroll({ itemCount: siblingIds.length, initialIndex, @@ -44,7 +44,11 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps const isOurNavigationRef = useRef(false); const lastInitialCommentIdRef = useRef(initialCommentId); - const currentCommentId = siblingIds[currentIndex]; + // Until its siblings are in, the list holds just the comment being opened. + // It shows meanwhile, and the swipe starts once they've loaded. + const isOpening = !scrollInitialized && siblingIds.length === 1; + const shownIndex = scrollInitialized ? currentIndex : initialIndex; + const currentCommentId = siblingIds[shownIndex]; // Track comment authors as they load — used for document title const [authorsByCommentId, setAuthorsByCommentId] = useState>({}); @@ -71,19 +75,25 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps } }, [initialCommentId]); - // Scroll-init: scroll to correct position once siblings are loaded. A failed - // load leaves the list at the one comment, so this waits for the retry. + // A comment opens at its top, wherever the page before it was. + useLayoutEffect(() => { + if (isOpening) window.scrollTo(0, 0); + }, [isOpening]); + + // Scroll-init: once the siblings are in, the swipe starts on the comment + // that has been showing, at the reader's place in it. A failed load leaves + // the list at that one comment, so the swipe waits for the retry. useLayoutEffect(() => { if (hasInitializedScrollRef.current) return; if (siblingIds.length === 0 || loading || error) return; const idx = siblingIds.indexOf(Number(initialCommentId)); - const targetIdx = idx >= 0 ? idx : initialIndex; hasInitializedScrollRef.current = true; setScrollInitialized(true); - scrollToIndex(targetIdx); - }, [siblingIds, loading, error, initialCommentId, initialIndex, scrollToIndex]); + resetToIndex(idx >= 0 ? idx : initialIndex); + if (idx < 0) window.scrollTo(0, 0); + }, [siblingIds, loading, error, initialCommentId, initialIndex, resetToIndex]); // URL update on swipe — only after scroll position is initialized. // Uses scrollInitialized state (not ref) so it's batched with setCurrentIndex @@ -127,16 +137,6 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps }; }, []); - if (loading && siblingIds.length <= 1) { - return ( -
-
- -
-
- ); - } - if (error && siblingIds.length <= 1 && !isRetrying) { return (
@@ -145,18 +145,10 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps ); } - if (error && siblingIds.length <= 1 && isRetrying) { - return ( -
-
- -
-
- ); - } - const VIRTUALIZE_BUFFER = 2; + // One container for the opening comment and the full list, and panels keyed + // by id, so the comment on screen isn't mounted again when its siblings land. return (
{siblingIds.map((id, index) => { - const distance = Math.abs(index - currentIndex); + const distance = Math.abs(index - shownIndex); const isWithinWindow = distance <= VIRTUALIZE_BUFFER; return (
diff --git a/src/hooks/useSwipeScroll.test.ts b/src/hooks/useSwipeScroll.test.ts index 94d58a1..16ba0c2 100644 --- a/src/hooks/useSwipeScroll.test.ts +++ b/src/hooks/useSwipeScroll.test.ts @@ -362,6 +362,30 @@ describe('useSwipeScroll', () => { }); }); + // -- resetToIndex -- + + describe('resetToIndex', () => { + it('switches panel where the page is, and forgets the saved positions', () => { + render(createElement(TestHarness), { wrapper: Wrapper }); + + mockScrollY = 200; + act(() => { hookResult.scrollToIndex(1); }); + mockScrollY = 300; + vi.mocked(window.scrollTo).mockClear(); + + act(() => { hookResult.resetToIndex(2); }); + + expect(hookResult.currentIndex).toBe(2); + expect(hasActive(2)).toBe(true); + expect(activePanelCount()).toBe(1); + expect(window.scrollTo).not.toHaveBeenCalled(); + + // Panel 0 was left at 200 before the reset. + act(() => { hookResult.scrollToIndex(0); }); + expect(window.scrollTo).toHaveBeenCalledWith(0, 0); + }); + }); + // -- Touch gestures -- describe('touch gestures', () => { diff --git a/src/hooks/useSwipeScroll.ts b/src/hooks/useSwipeScroll.ts index 5f17848..3edc00c 100644 --- a/src/hooks/useSwipeScroll.ts +++ b/src/hooks/useSwipeScroll.ts @@ -32,6 +32,12 @@ interface UseSwipeScrollResult { currentIndex: number; currentIndexRef: React.MutableRefObject; scrollToIndex: (index: number) => void; + /** + * Makes `index` the current panel where the page already is, and forgets + * the scroll positions saved for the others: for a new list of panels + * around the one on screen. + */ + resetToIndex: (index: number) => void; isScrollingProgrammaticallyRef: React.MutableRefObject; } @@ -214,6 +220,13 @@ export function useSwipeScroll({ }, 50); }, [activatePanelAndRestoreScroll]); + const resetToIndex = useCallback((index: number) => { + scrollMapRef.current.clear(); + currentIndexRef.current = index; + setCurrentIndex(index); + activatePanel(index); + }, [activatePanel]); + useEffect(() => { if (!enabled) return; const container = containerRef.current; @@ -819,6 +832,7 @@ export function useSwipeScroll({ currentIndex, currentIndexRef, scrollToIndex, + resetToIndex, isScrollingProgrammaticallyRef, }; } From dca2a775b036fcf7be128ee77a0138cda7ff4a21 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Wed, 4 Nov 2026 13:28:59 +0100 Subject: [PATCH 3/4] fix: skip hidden comments in the phone's comment swipe The swipe comment viewer took its comments from the parent's `kids` in Firebase, which include deleted and flagged comments that the thread, like HN, leaves out when nothing is under them. Across the top 15 stories, 29 of 357 top-level comments were such comments, and so are 29 of the 438 on "Ask HN: Who wants to be hired?". Swiping onto a deleted one showed "Comment deleted" with no parent or story link. Swiping onto a flagged one showed "[flagged]" with its author. Once the list is in, the viewer reads every sibling from Firebase, and the swipe passes over the flagged and deleted ones with no replies, the rule the comment page's reply check uses. It never passes over the comment it was opened on, or one whose read fails. Those panels stay in the list, so the reads don't hold up the swipe, and a swipe under way keeps its target. The panels loaded ahead on each side are now the swipe's next stops rather than the nearest panels. On "Who wants to be hired?" the swipe starts when it did before, and passes over hidden comments from about 1.5s after the page opens, or 7.4s on slow 4G. A swipe before then can still land on one. The reads add about 620KB. --- e2e/comment-swipe.spec.ts | 39 ++++++++++ e2e/fixtures/swipe-helpers.ts | 86 ++++++++++++---------- src/api/hn.ts | 16 ++++ src/components/SwipeCommentViewer.test.tsx | 20 +++++ src/components/SwipeCommentViewer.tsx | 20 ++++- src/hooks/useSiblingComments.test.ts | 54 ++++++++++++++ src/hooks/useSiblingComments.ts | 22 +++++- src/hooks/useSwipeScroll.test.ts | 39 +++++++++- src/hooks/useSwipeScroll.ts | 17 ++++- 9 files changed, 262 insertions(+), 51 deletions(-) diff --git a/e2e/comment-swipe.spec.ts b/e2e/comment-swipe.spec.ts index 75a1724..68322a9 100644 --- a/e2e/comment-swipe.spec.ts +++ b/e2e/comment-swipe.spec.ts @@ -1,6 +1,7 @@ import { test, expect } from '@playwright/test'; import { setupApiMocks, FIREBASE_WS_PATTERN, createFirebaseWsHandler } from './fixtures/api-mocks'; import { + dispatchSwipeGesture, expectActiveSwipePanelText, waitForSwipeReady, smoothScrollAndAwaitSettled, @@ -273,6 +274,44 @@ test.describe('Mobile Comment Swipe Viewer', () => { await expect(page.getByText('Comment deleted').first()).toBeVisible({ timeout: 10000 }); }); + test('swipes past a deleted sibling with no replies', async ({ page }) => { + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ + itemOverrides: { + 5555: { + id: 5555, + time: Math.floor(Date.now() / 1000) - 600, + parent: 12345, + type: 'comment', + deleted: true, + }, + 12345: { + id: 12345, + title: 'Rust Is the Future of JavaScript Infrastructure', + url: 'https://leerob.io/blog/rust', + by: 'leerob', + score: 284, + time: Math.floor(Date.now() / 1000) - 3600, + descendants: 5, + kids: [1001, 5555, 1002, 1003, 1004], + type: 'story', + }, + }, + })); + + await page.goto('/#/item/1001'); + await waitForSwipeReady(page, 5); + // 1003 is the swipe's second stop once 5555 is known to be skipped. + await expect(page.locator('[data-item-id="1003"] .comment-content').first()).toBeAttached({ timeout: 10000 }); + + const container = page.getByTestId('swipe-container'); + const width = await container.evaluate((el) => el.getBoundingClientRect().width); + await dispatchSwipeGesture(container, { forward: true, width }); + + await waitForScrollAtIndex(page, 2); + await expect(page).toHaveURL(/\/item\/1002/, { timeout: 5000 }); + await expectActiveSwipePanelText(page, 'jgrahamc', { minPanels: 5 }); + }); + test('shows error state when comment fetch fails', async ({ page }) => { // Auto-retry exhausts 3 backoff attempts (2+4+8s) before showing error. test.setTimeout(60000); diff --git a/e2e/fixtures/swipe-helpers.ts b/e2e/fixtures/swipe-helpers.ts index 95a04bb..7818430 100644 --- a/e2e/fixtures/swipe-helpers.ts +++ b/e2e/fixtures/swipe-helpers.ts @@ -84,6 +84,51 @@ export async function expectActiveSwipePanelText( await expect(activePanel.getByText(text)).toBeVisible({ timeout }); } +/** + * Dispatch one swipe gesture on the swipe container, forward or back. + * Uses Event + Object.defineProperty to avoid `new Touch()` / `new TouchEvent()` + * which throw "Illegal constructor" in WebKit (Safari) and may be unavailable + * in Firefox desktop even with hasTouch:true. + */ +export async function dispatchSwipeGesture(container: Locator, { forward, width }: { forward: boolean; width: number }) { + await container.evaluate((el, { forward, width }) => { + const rect = el.getBoundingClientRect(); + const centerX = rect.left + width / 2; + const centerY = rect.top + rect.height / 2; + + // Swipe distance: 40% of panel width (exceeds the 25% commit threshold) + const swipeDistance = width * 0.4; + const endX = forward ? centerX - swipeDistance : centerX + swipeDistance; + + const makeTouch = (clientX: number) => ({ + identifier: 1, + target: el, + clientX, + clientY: centerY, + pageX: clientX, + pageY: centerY, + screenX: clientX, + screenY: centerY, + radiusX: 1, + radiusY: 1, + rotationAngle: 0, + force: 1, + }); + + const dispatchTouch = (type: string, touches: object[], changed?: object[]) => { + const event = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperty(event, 'touches', { value: touches }); + Object.defineProperty(event, 'changedTouches', { value: changed ?? touches }); + Object.defineProperty(event, 'targetTouches', { value: touches }); + el.dispatchEvent(event); + }; + + dispatchTouch('touchstart', [makeTouch(centerX)]); + dispatchTouch('touchmove', [makeTouch(endX)]); + dispatchTouch('touchend', [], [makeTouch(endX)]); + }, { forward, width }); +} + /** * Navigate the swipe viewer to a specific panel index by simulating touch * gesture events that trigger the hook's native gesture system. @@ -138,46 +183,7 @@ export async function smoothScrollAndAwaitSettled(container: Locator, targetLeft // initial scrollToIndex — the handler silently ignores the touch. let success = false; for (let attempt = 0; attempt < 3 && !success; attempt++) { - // Dispatch touch gesture for one step. - // Uses Event + Object.defineProperty to avoid `new Touch()` / `new TouchEvent()` - // which throw "Illegal constructor" in WebKit (Safari) and may be unavailable - // in Firefox desktop even with hasTouch:true. - await container.evaluate((el, { forward, width }) => { - const rect = el.getBoundingClientRect(); - const centerX = rect.left + width / 2; - const centerY = rect.top + rect.height / 2; - - // Swipe distance: 40% of panel width (exceeds the 25% commit threshold) - const swipeDistance = width * 0.4; - const endX = forward ? centerX - swipeDistance : centerX + swipeDistance; - - const makeTouch = (clientX: number) => ({ - identifier: 1, - target: el, - clientX, - clientY: centerY, - pageX: clientX, - pageY: centerY, - screenX: clientX, - screenY: centerY, - radiusX: 1, - radiusY: 1, - rotationAngle: 0, - force: 1, - }); - - const dispatchTouch = (type: string, touches: object[], changed?: object[]) => { - const event = new Event(type, { bubbles: true, cancelable: true }); - Object.defineProperty(event, 'touches', { value: touches }); - Object.defineProperty(event, 'changedTouches', { value: changed ?? touches }); - Object.defineProperty(event, 'targetTouches', { value: touches }); - el.dispatchEvent(event); - }; - - dispatchTouch('touchstart', [makeTouch(centerX)]); - dispatchTouch('touchmove', [makeTouch(endX)]); - dispatchTouch('touchend', [], [makeTouch(endX)]); - }, { forward: isForward, width: panelWidth }); + await dispatchSwipeGesture(container, { forward: isForward, width: panelWidth }); // Wait for the animation to complete (panel gets .active). Long enough // for WebKit under load: a gesture that lands late after a retry has diff --git a/src/api/hn.ts b/src/api/hn.ts index ec2e887..d6a8f3e 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -356,6 +356,22 @@ export async function fetchFirebaseItem(id: number | string, signal?: AbortSigna return item; } +/** + * The comments among `ids` that a thread leaves out: flagged and deleted ones + * with no replies. Never `keepId`, so a link to it still opens, nor one whose + * read fails. + */ +export async function fetchHiddenCommentIds(ids: number[], keepId: number, signal?: AbortSignal): Promise> { + const items = await Promise.all(ids.map(id => hnSdk.readItem(id).catch(() => null))); + if (signal?.aborted) { + throw new DOMException('Aborted', 'AbortError'); + } + return new Set(ids.filter((id, i) => { + const item = items[i]; + return id !== keepId && !!item && !item.kids?.length && (!!item.dead || !!item.deleted); + })); +} + // Algolia is much faster than Firebase here — 1-2 requests instead of hundreds // of recursive item fetches. `stopIfCapped` skips the remaining pages of a // thread bigger than search returns. diff --git a/src/components/SwipeCommentViewer.test.tsx b/src/components/SwipeCommentViewer.test.tsx index 6dee730..fb5b34c 100644 --- a/src/components/SwipeCommentViewer.test.tsx +++ b/src/components/SwipeCommentViewer.test.tsx @@ -368,6 +368,26 @@ describe('SwipeCommentViewer', () => { expect(window.scrollTo).not.toHaveBeenCalled(); }); + it('loads the swipe\'s next stops past a deleted sibling, and not the deleted one', async () => { + const items: Record = { + ...defaultItems, + 3001: { id: 3001, type: 'comment', deleted: true, parent: 12345, time: Math.floor(Date.now() / 1000) - 500 }, + 12345: { ...defaultItems[12345], kids: [1001, 3001, 1002, 1003, 1004] }, + }; + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => items[Number(id)] ?? null); + + render(, { + initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }], + }); + + // 1003 is three panels on, but the second stop. + const panel1003 = () => document.querySelector('[data-item-id="1003"]')!; + await waitFor(() => { + expect(panel1003().textContent).toContain(mockAlgoliaCommentItem1003.text); + }); + expect(document.querySelector('[data-item-id="3001"] .animate-pulse')).not.toBeNull(); + }); + it('stays on the comment it was opened on when its siblings load on a retry', async () => { let parentReads = 0; vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { diff --git a/src/components/SwipeCommentViewer.tsx b/src/components/SwipeCommentViewer.tsx index 5f23265..457ef66 100644 --- a/src/components/SwipeCommentViewer.tsx +++ b/src/components/SwipeCommentViewer.tsx @@ -20,7 +20,10 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps // Track a stable comment ID for fetching — only changes on external navigation, not on swipe URL updates const [siblingSourceId, setSiblingSourceId] = useState(initialCommentId); - const { siblingIds, currentIndex: initialIndex, loading, error, retry } = useSiblingComments(siblingSourceId); + const { siblingIds, hiddenIds, currentIndex: initialIndex, loading, error, retry } = useSiblingComments(siblingSourceId); + // Skipped rather than left out, so the panels keep their places while a + // swipe is under way. + const isSkipped = useCallback((index: number) => hiddenIds.has(siblingIds[index]), [hiddenIds, siblingIds]); const { isOnline } = useNetworkStatus(); const { isRetrying } = useAutoRetry({ @@ -38,6 +41,7 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps itemCount: siblingIds.length, initialIndex, enabled: scrollInitialized, + isSkipped, }); const hasInitializedScrollRef = useRef(false); @@ -147,6 +151,17 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps const VIRTUALIZE_BUFFER = 2; + // The shown panel and the swipe's next stops each way. + const windowIndexes = new Set([shownIndex]); + for (const step of [-1, 1]) { + let stops = 0; + for (let index = shownIndex + step; stops < VIRTUALIZE_BUFFER && index >= 0 && index < siblingIds.length; index += step) { + if (isSkipped(index)) continue; + windowIndexes.add(index); + stops++; + } + } + // One container for the opening comment and the full list, and panels keyed // by id, so the comment on screen isn't mounted again when its siblings land. return ( @@ -156,8 +171,7 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps data-testid="swipe-container" > {siblingIds.map((id, index) => { - const distance = Math.abs(index - shownIndex); - const isWithinWindow = distance <= VIRTUALIZE_BUFFER; + const isWithinWindow = windowIndexes.has(index); return (
{ expect(result.current.currentIndex).toBe(1); }); + describe('flagged and deleted siblings', () => { + const now = Math.floor(Date.now() / 1000); + const thread: Record = { + ...mockItems, + 3001: { id: 3001, type: 'comment', deleted: true, parent: 12345, time: now - 500 }, + 3002: { id: 3002, type: 'comment', by: 'spammer', text: '[flagged]', dead: true, parent: 12345, time: now - 400 }, + 3003: { id: 3003, type: 'comment', deleted: true, parent: 12345, kids: [4001], time: now - 200 }, + 12345: { ...mockItems[12345], kids: [1001, 3001, 1002, 3002, 3003, 1003] }, + }; + + beforeEach(() => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => thread[Number(id)] ?? null); + }); + + it('finds the ones with no replies, which the thread leaves out', async () => { + const { result } = renderHook(() => useSiblingComments(1002)); + + await waitFor(() => { + expect(result.current.hiddenIds).toEqual(new Set([3001, 3002])); + }); + expect(result.current.siblingIds).toEqual([1001, 3001, 1002, 3002, 3003, 1003]); + expect(result.current.currentIndex).toBe(2); + }); + + it('never counts the one it was opened on', async () => { + const { result } = renderHook(() => useSiblingComments(3001)); + + await waitFor(() => { + expect(result.current.hiddenIds).toEqual(new Set([3002])); + }); + }); + + it('has the siblings in before it reads them', async () => { + let releaseSiblings!: () => void; + const siblingsRead = new Promise(resolve => { releaseSiblings = resolve; }); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) !== 1002 && Number(id) !== 12345) await siblingsRead; + return thread[Number(id)] ?? null; + }); + const { result } = renderHook(() => useSiblingComments(1002)); + + await waitFor(() => { + expect(result.current.loading).toBe(false); + }); + expect(result.current.siblingIds).toEqual([1001, 3001, 1002, 3002, 3003, 1003]); + expect(result.current.hiddenIds.size).toBe(0); + + releaseSiblings(); + await waitFor(() => { + expect(result.current.hiddenIds).toEqual(new Set([3001, 3002])); + }); + }); + }); + it('returns single comment when parent_id is null', async () => { vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { if (Number(id) === 7777) { diff --git a/src/hooks/useSiblingComments.ts b/src/hooks/useSiblingComments.ts index a5949b7..1ac198e 100644 --- a/src/hooks/useSiblingComments.ts +++ b/src/hooks/useSiblingComments.ts @@ -1,8 +1,15 @@ import { useState, useEffect, useCallback, useRef } from 'react'; -import { fetchFirebaseItem } from '../api/hn'; +import { fetchFirebaseItem, fetchHiddenCommentIds } from '../api/hn'; + +const NO_IDS: ReadonlySet = new Set(); interface UseSiblingCommentsResult { siblingIds: number[]; + /** + * The flagged and deleted siblings with no replies, which the thread leaves + * out. Every sibling is read for this, so it fills in after `siblingIds`. + */ + hiddenIds: ReadonlySet; currentIndex: number; loading: boolean; error: string | null; @@ -11,6 +18,7 @@ interface UseSiblingCommentsResult { export function useSiblingComments(commentId: number | string): UseSiblingCommentsResult { const [siblingIds, setSiblingIds] = useState([Number(commentId)]); + const [hiddenIds, setHiddenIds] = useState(NO_IDS); const [currentIndex, setCurrentIndex] = useState(0); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -21,6 +29,7 @@ export function useSiblingComments(commentId: number | string): UseSiblingCommen // Reset to show at least this comment while loading setSiblingIds([numericId]); + setHiddenIds(NO_IDS); setCurrentIndex(0); setError(null); setLoading(true); @@ -51,6 +60,15 @@ export function useSiblingComments(commentId: number | string): UseSiblingCommen setCurrentIndex(0); } setLoading(false); + + if (kids && kids.length > 1) { + void fetchHiddenCommentIds(kids, numericId, signal).then( + hidden => { + if (!signal.aborted) setHiddenIds(hidden); + }, + () => { /* none are skipped */ }, + ); + } } catch (err) { if (signal.aborted || (err instanceof Error && err.name === 'AbortError')) return; setError(err instanceof Error ? err.message : String(err)); @@ -75,5 +93,5 @@ export function useSiblingComments(commentId: number | string): UseSiblingCommen }; }, [load]); - return { siblingIds, currentIndex, loading, error, retry }; + return { siblingIds, hiddenIds, currentIndex, loading, error, retry }; } diff --git a/src/hooks/useSwipeScroll.test.ts b/src/hooks/useSwipeScroll.test.ts index 16ba0c2..677cbe1 100644 --- a/src/hooks/useSwipeScroll.test.ts +++ b/src/hooks/useSwipeScroll.test.ts @@ -129,10 +129,10 @@ function swipeGesture(el: Element, direction: 'left' | 'right', distance: number type HookResult = ReturnType; let hookResult: HookResult = null!; -function TestHarness({ itemCount = 3, initialIndex = 0, enabled = true }: { - itemCount?: number; initialIndex?: number; enabled?: boolean; +function TestHarness({ itemCount = 3, initialIndex = 0, enabled = true, isSkipped }: { + itemCount?: number; initialIndex?: number; enabled?: boolean; isSkipped?: (index: number) => boolean; }) { - const result = useSwipeScroll({ itemCount, initialIndex, enabled }); + const result = useSwipeScroll({ itemCount, initialIndex, enabled, isSkipped }); // eslint-disable-next-line react-hooks/globals hookResult = result; return createElement('div', { ref: result.containerRef, 'data-testid': 'container' }, @@ -694,6 +694,39 @@ describe('useSwipeScroll', () => { expect(hookResult.currentIndex).toBe(2); }); + it('passes over skipped panels, both ways (reduced motion)', async () => { + reducedMotionValue = true; + const isSkipped = (index: number) => index === 1 || index === 2; + render(createElement(TestHarness, { itemCount: 4, isSkipped }), { wrapper: Wrapper }); + + swipeGesture(getContainer(), 'left', 150); + act(() => { vi.runAllTimers(); }); + await act(async () => { /* flush */ }); + expect(hookResult.currentIndex).toBe(3); + expect(hasActive(3)).toBe(true); + expect(activePanelCount()).toBe(1); + + swipeGesture(getContainer(), 'right', 150); + act(() => { vi.runAllTimers(); }); + await act(async () => { /* flush */ }); + expect(hookResult.currentIndex).toBe(0); + expect(hasActive(0)).toBe(true); + }); + + it('stays when every panel ahead is skipped (reduced motion)', async () => { + reducedMotionValue = true; + const isSkipped = (index: number) => index > 0; + render(createElement(TestHarness, { isSkipped }), { wrapper: Wrapper }); + + swipeGesture(getContainer(), 'left', 150); + act(() => { vi.runAllTimers(); }); + await act(async () => { /* flush */ }); + + expect(hasActive(0)).toBe(true); + expect(activePanelCount()).toBe(1); + expect(hookResult.currentIndex).toBe(0); + }); + it('touchcancel is treated the same as touchend', async () => { reducedMotionValue = true; render(createElement(TestHarness), { wrapper: Wrapper }); diff --git a/src/hooks/useSwipeScroll.ts b/src/hooks/useSwipeScroll.ts index 3edc00c..a754ed9 100644 --- a/src/hooks/useSwipeScroll.ts +++ b/src/hooks/useSwipeScroll.ts @@ -8,6 +8,7 @@ import { } from '../utils/releaseVelocity'; const noop = () => undefined; +const neverSkipped = () => false; /** * Settle curve for a committed swipe: starts at 1.5× its average speed @@ -25,6 +26,8 @@ interface UseSwipeScrollOptions { itemCount: number; initialIndex?: number; enabled?: boolean; + /** Panels a swipe passes over, to the next one it can land on. */ + isSkipped?: (index: number) => boolean; } interface UseSwipeScrollResult { @@ -45,6 +48,7 @@ export function useSwipeScroll({ itemCount, initialIndex = 0, enabled = true, + isSkipped = neverSkipped, }: UseSwipeScrollOptions): UseSwipeScrollResult { const { enableSwipeMode, disableSwipeMode } = useScrollContainer(); @@ -69,6 +73,11 @@ export function useSwipeScroll({ itemCountRef.current = itemCount; }, [itemCount]); + const isSkippedRef = useRef(isSkipped); + useLayoutEffect(() => { + isSkippedRef.current = isSkipped; + }, [isSkipped]); + useLayoutEffect(() => { enableSwipeMode(); const previousScrollRestoration = history.scrollRestoration; @@ -531,9 +540,11 @@ export function useSwipeScroll({ cachedPanelWidth = container.clientWidth || window.innerWidth; // Lock direction and determine target lockedDir = deltaX < 0 ? 'left' : 'right'; - targetIndex = lockedDir === 'left' - ? currentIndexRef.current + 1 - : currentIndexRef.current - 1; + const step = lockedDir === 'left' ? 1 : -1; + targetIndex = currentIndexRef.current + step; + while (targetIndex >= 0 && targetIndex < itemCountRef.current && isSkippedRef.current(targetIndex)) { + targetIndex += step; + } hasTarget = targetIndex >= 0 && targetIndex < itemCountRef.current; } else { // Vertical gesture — stop tracking From cc0e0e44ae332c06a9cde78a672df531f6867574 Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:08:00 +0100 Subject: [PATCH 4/4] fix: keep the opened comment mounted while its siblings retry The phone's comment viewer swaps everything for "Failed to load comments" when its siblings failed to load and `isRetrying` is off. That flag is still off in the render where a load fails, and only comes on in a layout effect after it. So each failure rendered the error branch once, before paint, which unmounted the panels: the comment shown while its siblings load was mounted again, fetched again, and lost the reader's place. Scrolled 600px down it, a reader dropped to 27px in Mobile Chrome and 207px in Mobile Safari at the first failed retry. The viewer now shows the error once the retries have given up, as `SwipeStoryViewer` does. That is the only time the error showed on screen before, so offline, after giving up and on a manual retry it shows as it did. --- src/components/SwipeCommentViewer.test.tsx | 13 ++++++++++++- src/components/SwipeCommentViewer.tsx | 4 ++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/components/SwipeCommentViewer.test.tsx b/src/components/SwipeCommentViewer.test.tsx index fb5b34c..a4776ed 100644 --- a/src/components/SwipeCommentViewer.test.tsx +++ b/src/components/SwipeCommentViewer.test.tsx @@ -388,22 +388,33 @@ describe('SwipeCommentViewer', () => { expect(document.querySelector('[data-item-id="3001"] .animate-pulse')).not.toBeNull(); }); - it('stays on the comment it was opened on when its siblings load on a retry', async () => { + it('stays on the comment it was opened on, without mounting it again, when its siblings load on a retry', async () => { let parentReads = 0; vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { if (Number(id) === 12345 && parentReads++ === 0) throw new Error('Network error'); return defaultItems[Number(id)] ?? null; }); + let commentFetches = 0; + server.use( + http.get(`${ALGOLIA_API}/items/1003`, () => { + commentFetches++; + return HttpResponse.json(mockAlgoliaCommentItem1003); + }), + ); render(, { initialEntries: [{ pathname: '/item/1003', state: { isComment: true } }], }); + expect(await screen.findByText(mockAlgoliaCommentItem1003.text)).toBeInTheDocument(); + const panel = document.querySelector('[data-item-id="1003"]'); // The retry waits out a 2s backoff. await waitFor(() => { expect(screen.getAllByTestId('swipe-panel')).toHaveLength(4); expect(activePanelId()).toBe('1003'); }, { timeout: 5000 }); + expect(document.querySelector('[data-item-id="1003"]')).toBe(panel); + expect(commentFetches).toBe(1); }, 10000); it('sets data-item-id on each panel', async () => { diff --git a/src/components/SwipeCommentViewer.tsx b/src/components/SwipeCommentViewer.tsx index 457ef66..5c3c339 100644 --- a/src/components/SwipeCommentViewer.tsx +++ b/src/components/SwipeCommentViewer.tsx @@ -26,7 +26,7 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps const isSkipped = useCallback((index: number) => hiddenIds.has(siblingIds[index]), [hiddenIds, siblingIds]); const { isOnline } = useNetworkStatus(); - const { isRetrying } = useAutoRetry({ + const { giveUp } = useAutoRetry({ error, retryFn: retry, isOnline, @@ -141,7 +141,7 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps }; }, []); - if (error && siblingIds.length <= 1 && !isRetrying) { + if (error && siblingIds.length <= 1 && giveUp) { return (
void retry().catch(() => { /* error state set internally */ }) }} className="swipe-state-center" />