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 3734f8c..a4776ed 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,91 @@ 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('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, 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 () => { render(, { initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }], diff --git a/src/components/SwipeCommentViewer.tsx b/src/components/SwipeCommentViewer.tsx index 9339faa..5c3c339 100644 --- a/src/components/SwipeCommentViewer.tsx +++ b/src/components/SwipeCommentViewer.tsx @@ -20,10 +20,13 @@ 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({ + const { giveUp } = useAutoRetry({ error, retryFn: retry, isOnline, @@ -33,18 +36,23 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps const { containerRef, currentIndex, - scrollToIndex, + resetToIndex, } = useSwipeScroll({ itemCount: siblingIds.length, initialIndex, enabled: scrollInitialized, + isSkipped, }); const hasInitializedScrollRef = useRef(false); 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,18 +79,25 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps } }, [initialCommentId]); - // Scroll-init: scroll to correct position once siblings are loaded + // 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) 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, 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 @@ -126,17 +141,7 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps }; }, []); - if (loading && siblingIds.length <= 1) { - return ( -
-
- -
-
- ); - } - - if (error && siblingIds.length <= 1 && !isRetrying) { + if (error && siblingIds.length <= 1 && giveUp) { return (
void retry().catch(() => { /* error state set internally */ }) }} className="swipe-state-center" /> @@ -144,18 +149,21 @@ export function SwipeCommentViewer({ initialCommentId }: SwipeCommentViewerProps ); } - if (error && siblingIds.length <= 1 && isRetrying) { - return ( -
-
- -
-
- ); - } - 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 (
{siblingIds.map((id, index) => { - const distance = Math.abs(index - currentIndex); - const isWithinWindow = distance <= VIRTUALIZE_BUFFER; + const isWithinWindow = windowIndexes.has(index); return (
diff --git a/src/hooks/useSiblingComments.test.ts b/src/hooks/useSiblingComments.test.ts index 8eb6f1f..c426984 100644 --- a/src/hooks/useSiblingComments.test.ts +++ b/src/hooks/useSiblingComments.test.ts @@ -72,6 +72,60 @@ describe('useSiblingComments', () => { 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 94d58a1..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' }, @@ -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', () => { @@ -670,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 5f17848..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 { @@ -32,6 +35,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; } @@ -39,6 +48,7 @@ export function useSwipeScroll({ itemCount, initialIndex = 0, enabled = true, + isSkipped = neverSkipped, }: UseSwipeScrollOptions): UseSwipeScrollResult { const { enableSwipeMode, disableSwipeMode } = useScrollContainer(); @@ -63,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; @@ -214,6 +229,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; @@ -518,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 @@ -819,6 +843,7 @@ export function useSwipeScroll({ currentIndex, currentIndexRef, scrollToIndex, + resetToIndex, isScrollingProgrammaticallyRef, }; }