diff --git a/src/features/followingV2/home/PostFeed.tsx b/src/features/followingV2/home/PostFeed.tsx index cf789ba90..b423bae8d 100644 --- a/src/features/followingV2/home/PostFeed.tsx +++ b/src/features/followingV2/home/PostFeed.tsx @@ -95,6 +95,8 @@ import { import {useSavedFeedSamples} from './queries/savedFeedSamples' import {useAnchorCorrectionScrollHandlers} from './useAnchorCorrectionScrollHandlers' import {useListRest} from './useListRest' +import {useSettleAtTop} from './useSettleAtTop' +import {useSettleScrollHandlers} from './useSettleScrollHandlers' type FeedRow = | { @@ -385,6 +387,19 @@ let PostFeed = ({ listAtRest: listRest.atRest, }) const fillGap = usePostFeedGapFill(feed, feedParams) + const settleAtTop = useSettleAtTop(feed, feedParams, { + enabled: isAnchored && enabled !== false, + }) + /** + * The list's scroll handlers. Settling judges the offset as the list reports + * it, as it has to know whether the list is really at the top. The Home + * header sees it with the corrections anchoring makes taken out, so they + * can't hide or show it. + */ + const scrollHandlers = useSettleScrollHandlers( + listRest.scrollHandlers, + isAnchored ? settleAtTop : undefined, + ) /** * The top page a refresh from this view wrote, to take the reader up to once @@ -1317,7 +1332,7 @@ let PostFeed = ({ return ( - + { }) /** The feed's view, as PostFeed has it, over `data` already in the cache. */ - function renderView(data = gappedData()) { + function renderView( + data = gappedData(), + {enabled = true}: {enabled?: boolean} = {}, + ) { const queryClient = createQueryClient() queryClient.setQueryData(KEY, data) const wrapper = ({children}: PropsWithChildren) => ( @@ -1403,6 +1413,8 @@ describe('gaps', () => { query: usePostFeedQuery('following'), refresh: usePostFeedRefresh('following').refresh, fillGap: usePostFeedGapFill('following'), + settle: usePostFeedSettle('following'), + settleAtTop: useSettleAtTop('following', undefined, {enabled}), }), {wrapper}, ) @@ -1566,6 +1578,322 @@ describe('gaps', () => { expect(postsOf(cached())).toEqual([['new'], ['gap-1']]) expect(hook.result.current.query.isFetchingNextPage).toBe(false) }) + + describe('settling at the true top', () => { + /** An exhausted page on top of `gappedData`, which sits on its gapped page. */ + function exhaustedAboveGap(): PostFeedData { + const data = gappedData() + return { + pages: [ + { + cursor: 'start:0', + startCursor: 'start:newest', + since: 'start:0', + feed: [feedItem('newest')], + fetchedAt: Date.now(), + }, + ...data.pages, + ], + pageParams: [ + undefined, + {cursor: 'start:0'}, + ...data.pageParams.slice(1), + ], + } + } + + afterEach(() => { + jest.useRealTimers() + }) + + it('cuts the feed at its first open gap, and pagination goes on into the gap', async () => { + const {hook, queryClient, cached} = renderView() + const writes = watchWrites(queryClient) + + await act(async () => { + await expect(hook.result.current.settle(cached())).resolves.toBe(true) + }) + + expect(writes).toHaveLength(1) + expect(postsOf(cached())).toEqual([['new']]) + expect(cached().pageParams).toEqual([undefined]) + await act(() => hook.result.current.query.fetchNextPage()) + expect(requested()).toEqual(['timeline gap:1']) + }) + + it('keeps the pages above the gap', async () => { + const {hook, cached} = renderView(exhaustedAboveGap()) + + await act(() => hook.result.current.settle(cached())) + + expect(postsOf(cached())).toEqual([['newest'], ['new']]) + expect(cached().pageParams).toEqual([undefined, {cursor: 'start:0'}]) + }) + + it('writes nothing without an open gap, as the second time', async () => { + const {hook, queryClient, cached} = renderView() + await act(() => hook.result.current.settle(cached())) + const writes = watchWrites(queryClient) + + await act(async () => { + await expect(hook.result.current.settle(cached())).resolves.toBe(false) + }) + + expect(writes).toHaveLength(0) + }) + + it('writes nothing once the gap is filled', async () => { + const {hook, queryClient, cached} = renderView() + mockClient.call.mockReturnValueOnce(CONTINUATION) + await act(() => hook.result.current.fillGap('gap:1')) + const writes = watchWrites(queryClient) + + await act(async () => { + await expect(hook.result.current.settle(cached())).resolves.toBe(false) + }) + + expect(writes).toHaveLength(0) + expect(postsOf(cached())).toEqual([['new'], ['gap-1']]) + }) + + it('gives way to a refresh that has replaced the top since the reader came to rest', async () => { + const {hook, cached} = renderView() + const before = cached() + mockClient.call.mockReturnValueOnce({ + cursor: 'timeline:1', + feed: [feedItem('fresh')], + }) + await act(() => hook.result.current.refresh()) + const refreshed = cached() + + await act(async () => { + await expect(hook.result.current.settle(before)).resolves.toBe(false) + }) + + expect(cached()).toBe(refreshed) + }) + + it('gives way to a fill that has landed since the reader came to rest', async () => { + const {hook, cached} = renderView() + const before = cached() + mockClient.call.mockReturnValueOnce(CONTINUATION) + await act(() => hook.result.current.fillGap('gap:1')) + const filled = cached() + + await act(async () => { + await expect(hook.result.current.settle(before)).resolves.toBe(false) + }) + + expect(cached()).toBe(filled) + }) + + it('leaves a refresh in flight to write after it', async () => { + const {hook, cached} = renderView() + const top = holdNextRequest() + let refreshing!: Promise + act(() => { + refreshing = hook.result.current.refresh() + }) + + await act(() => hook.result.current.settle(cached())) + expect(postsOf(cached())).toEqual([['new']]) + + await act(async () => { + top.respond('fresh') + await refreshing + }) + expect(postsOf(cached())).toEqual([['fresh']]) + }) + + it('cancels a page load still in flight, and drops its page', async () => { + const {hook, cached} = renderView() + const next = holdNextRequest() + let loading!: Promise + act(() => { + loading = hook.result.current.query.fetchNextPage() + }) + + await act(() => hook.result.current.settle(cached())) + await act(async () => { + next.respond('late') + await loading + }) + + expect(postsOf(cached())).toEqual([['new']]) + expect(hook.result.current.query.isFetchingNextPage).toBe(false) + }) + + it('leaves a valid snapshot', async () => { + const {hook, cached} = renderView(exhaustedAboveGap()) + await act(() => hook.result.current.settle(cached())) + + const snapshot = selectFollowingSnapshot(cached()) + + expect(snapshot?.pages.map(page => page.cursor)).toEqual([ + 'start:0', + 'gap:1', + ]) + expect(readFollowingSnapshot(roundTrip(snapshot))).toEqual(cached()) + }) + + it('brings a post the dropped pages held back into the pages kept', async () => { + const data = gappedData() + data.pages[0].feed.push(feedItem('timeline-1')) + const {hook, cached} = renderView(data) + const slicesOfTop = () => + hook.result.current.query.data!.pages[0].slices.map(slice => + slice.feedPostUri.split('/').pop(), + ) + await waitFor(() => expect(slicesOfTop()).toEqual(['new'])) + + await act(() => hook.result.current.settle(cached())) + + /* + * Tuned without the pages below it, the top page keeps its copy of a + * post they had: a row can come back above or inside the viewport. + */ + await waitFor(() => expect(slicesOfTop()).toEqual(['new', 'timeline-1'])) + }) + + describe('when the reader comes to rest at the top', () => { + async function wait(ms: number) { + act(() => { + jest.advanceTimersByTime(ms) + }) + // Lets the settle's write go through. + await act(() => Promise.resolve()) + } + + it('settles once the list has stayed there, after a drag that leaves it still', async () => { + jest.useFakeTimers() + const {hook, cached} = renderView() + const {settleAtTop} = hook.result.current + + act(() => { + settleAtTop.onBeginDrag() + settleAtTop.onEndDrag(0, 0) + }) + await wait(SETTLE_QUIET_MS - 1) + expect(postsOf(cached())).toHaveLength(3) + + await wait(1) + expect(postsOf(cached())).toEqual([['new']]) + }) + + it('settles at the end of the momentum after a fling', async () => { + jest.useFakeTimers() + const {hook, cached} = renderView() + const {settleAtTop} = hook.result.current + + act(() => { + settleAtTop.onBeginDrag() + settleAtTop.onEndDrag(600, -3) + }) + await wait(SETTLE_QUIET_MS) + expect(postsOf(cached())).toHaveLength(3) + + act(() => settleAtTop.onMomentumEnd(-40)) + await wait(SETTLE_QUIET_MS) + expect(postsOf(cached())).toEqual([['new']]) + }) + + it('never where the list was first put', async () => { + jest.useFakeTimers() + const {cached} = renderView() + + await wait(SETTLE_QUIET_MS * 4) + + expect(postsOf(cached())).toHaveLength(3) + }) + + it('not at rest below the top', async () => { + jest.useFakeTimers() + const {hook, cached} = renderView() + + act(() => hook.result.current.settleAtTop.onEndDrag(400, 0)) + await wait(SETTLE_QUIET_MS) + + expect(postsOf(cached())).toHaveLength(3) + }) + + it('not once another drag starts, or the list leaves the top', async () => { + jest.useFakeTimers() + const {hook, cached} = renderView() + const {settleAtTop} = hook.result.current + + act(() => { + settleAtTop.onEndDrag(0, 0) + settleAtTop.onBeginDrag() + }) + await wait(SETTLE_QUIET_MS) + act(() => { + settleAtTop.onEndDrag(0, 0) + settleAtTop.onLeaveTop() + }) + await wait(SETTLE_QUIET_MS) + + expect(postsOf(cached())).toHaveLength(3) + }) + + it('not on the correction a prepend makes, before or after it lands', async () => { + jest.useFakeTimers() + const gapped = gappedData() + const restored = { + pages: gapped.pages.slice(1), + pageParams: [undefined, {cursor: 'timeline:1'}], + } + const {hook, queryClient, cached} = renderView(restored) + const {settleAtTop} = hook.result.current + /** Puts the gapped page above the restored top, as the prepend does. */ + const prepend = () => + act(() => { + queryClient.setQueryData(KEY, data => ({ + pages: [gapped.pages[0], ...data!.pages], + pageParams: [ + undefined, + {cursor: 'gap:1'}, + ...data!.pageParams.slice(1), + ], + })) + }) + + // At rest at the restored top, then the prepend lands while it waits. + act(() => settleAtTop.onEndDrag(0, 0)) + prepend() + await wait(SETTLE_QUIET_MS) + expect(postsOf(cached())).toHaveLength(3) + + // A rest reported from before the correction, then the correction. + act(() => { + settleAtTop.onMomentumEnd(0) + settleAtTop.onLeaveTop() + }) + await wait(SETTLE_QUIET_MS) + expect(postsOf(cached())).toHaveLength(3) + }) + + it('not once the view has unmounted', async () => { + jest.useFakeTimers() + const {hook, cached} = renderView() + + act(() => hook.result.current.settleAtTop.onEndDrag(0, 0)) + hook.unmount() + await wait(SETTLE_QUIET_MS) + + expect(postsOf(cached())).toHaveLength(3) + }) + + it('not while disabled', async () => { + jest.useFakeTimers() + const {hook, cached} = renderView(undefined, {enabled: false}) + + act(() => hook.result.current.settleAtTop.onEndDrag(0, 0)) + await wait(SETTLE_QUIET_MS) + + expect(postsOf(cached())).toHaveLength(3) + }) + }) + }) }) describe('a cold start', () => { diff --git a/src/features/followingV2/home/queries/postFeed.ts b/src/features/followingV2/home/queries/postFeed.ts index 30c5c6845..d69caa691 100644 --- a/src/features/followingV2/home/queries/postFeed.ts +++ b/src/features/followingV2/home/queries/postFeed.ts @@ -779,6 +779,47 @@ export function usePostFeedGapFill( } } +/** + * Settles the feed once the reader has reached its true top: cuts it at its + * first open gap (see {@link gapBelow}), keeping the pages down to the one + * above the gap and dropping every page below it. That page's cursor goes on + * into the gap, so ordinary pagination loads what's missing and nothing is + * lost. A feed with no open gap is left as it is, so settling again writes + * nothing. Resolves to whether it wrote. + * + * `before` is the data as it was when the reader came to rest at the top. The + * write depends on its pages down to the one below the gap, so it gives way + * to anything that has replaced them since, as the commit of a prepend does. + * It never replaces the top page, so a refresh in flight still writes after + * it. + */ +export function usePostFeedSettle( + feedDesc: FeedDescriptor, + params?: FeedParams, +) { + const queryClient = useQueryClient() + const queryKey = RQKEY(feedDesc, params) + + return async (before: PostFeedData | undefined) => { + const index = + before?.pages.findIndex((_, i) => gapBelow(before.pages, i) === 'open') ?? + -1 + if (!before || index === -1) { + return false + } + return commit( + queryClient, + queryKey, + before, + (data = before) => ({ + pages: data.pages.slice(0, index + 1), + pageParams: data.pageParams.slice(0, index + 1), + }), + {dependsOn: index + 2}, + ) + } +} + /** Whether a page fetched at `fetchedAt` was restored from disk. */ function isRestored(fetchedAt: number | undefined) { return fetchedAt !== undefined && fetchedAt < PROCESS_STARTED_AT diff --git a/src/features/followingV2/home/useSettleAtTop.ts b/src/features/followingV2/home/useSettleAtTop.ts new file mode 100644 index 000000000..c4f6cd836 --- /dev/null +++ b/src/features/followingV2/home/useSettleAtTop.ts @@ -0,0 +1,97 @@ +import {useEffect, useRef} from 'react' +import {useQueryClient} from '@tanstack/react-query' + +import { + type FeedDescriptor, + type FeedParams, + type PostFeedData, + RQKEY, + usePostFeedSettle, +} from './queries/postFeed' + +/** + * How close to its resting offset counts as the top of the list. That offset + * is 0 where the header's space is padding in the content, and negative where + * the platform applies it as an inset, so a small positive bound reads as the + * top under both. Provisional, to be measured on device. + */ +export const SETTLE_AT_TOP_LIMIT = 5 + +/** + * How long the list has to stay at the top after coming to rest there before + * the feed settles. A correction to the list's offset, as a prepend's commit + * makes, arrives as a scroll event after the rest it follows, and leaving the + * top in the meantime calls the settle off. Provisional, to be measured on + * device. + */ +export const SETTLE_QUIET_MS = 250 + +/** What the list reports for {@link useSettleAtTop}. */ +export type SettleAtTopHandlers = { + /** A finger started dragging the list. */ + onBeginDrag: () => void + /** The finger let go, at `offsetY`, with the list moving at `velocityY`. */ + onEndDrag: (offsetY: number, velocityY: number) => void + /** The list stopped after the momentum a drag gave it, at `offsetY`. */ + onMomentumEnd: (offsetY: number) => void + /** A scroll event found the list somewhere other than at the top. */ + onLeaveTop: () => void +} + +/** + * Settles the feed (see {@link usePostFeedSettle}) when the reader brings the + * list to rest at its true top: at the end of a drag that leaves it still, or + * at the end of the momentum after one, at the top, and still there + * {@link SETTLE_QUIET_MS} later. + * + * Only the reader's own movement counts, so neither where the list was first + * put nor where a correction moved it is a rest. The settle depends on the + * data as it was when the list came to rest, and gives way to anything that + * has replaced the pages it would keep since, as a prepend's commit does. It's + * called off by another drag, by the list leaving the top, and by unmounting. + */ +export function useSettleAtTop( + feedDesc: FeedDescriptor, + params: FeedParams | undefined, + {enabled}: {enabled: boolean}, +): SettleAtTopHandlers { + const queryClient = useQueryClient() + const settle = usePostFeedSettle(feedDesc, params) + const queryKey = RQKEY(feedDesc, params) + const isDragging = useRef(false) + const timeout = useRef>(undefined) + + const cancel = () => { + clearTimeout(timeout.current) + timeout.current = undefined + } + useEffect(() => cancel, []) + + const onRest = (offsetY: number) => { + cancel() + if (!enabled || isDragging.current || offsetY > SETTLE_AT_TOP_LIMIT) { + return + } + const before = queryClient.getQueryData(queryKey) + timeout.current = setTimeout(() => { + timeout.current = undefined + void settle(before) + }, SETTLE_QUIET_MS) + } + + return { + onBeginDrag: () => { + isDragging.current = true + cancel() + }, + onEndDrag: (offsetY, velocityY) => { + isDragging.current = false + // Moving, it comes to rest at the end of its momentum instead. + if (!velocityY) { + onRest(offsetY) + } + }, + onMomentumEnd: onRest, + onLeaveTop: cancel, + } +} diff --git a/src/features/followingV2/home/useSettleScrollHandlers.ts b/src/features/followingV2/home/useSettleScrollHandlers.ts new file mode 100644 index 000000000..51eb382eb --- /dev/null +++ b/src/features/followingV2/home/useSettleScrollHandlers.ts @@ -0,0 +1,80 @@ +import {useCallback} from 'react' +import {type ScrollHandlers, useSharedValue} from 'react-native-reanimated' +import {type ReanimatedScrollEvent} from 'react-native-reanimated/lib/typescript/hook/commonTypes' +import {scheduleOnRN} from 'react-native-worklets' + +import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' +import {SETTLE_AT_TOP_LIMIT, type SettleAtTopHandlers} from './useSettleAtTop' + +/** + * The scroll handlers `inner`, such as those from context, for a list to take + * from a `ScrollProvider` around it, with what {@link SettleAtTopHandlers} + * need reported to them as well, on the JS thread. They're reported from each + * event as the list sent it, whatever `inner` passes on. A scroll event is + * reported only when it finds the list off the top where the last event found + * it at the top, so not every frame, and a rest at the top is always followed + * by a report of leaving it. Without `handlers`, they're `inner` as they are. + */ +export function useSettleScrollHandlers( + inner: ScrollHandlers>, + handlers: SettleAtTopHandlers | undefined, +): ScrollHandlers> { + // Destructured outside the worklets, as `List` does (see #4108). + const { + onBeginDrag: onBeginDragInner, + onEndDrag: onEndDragInner, + onScroll: onScrollInner, + onMomentumEnd: onMomentumEndInner, + } = inner + const isAtTop = useSharedValue(true) + const onBeginDragJS = useNonReactiveCallback(handlers?.onBeginDrag) + const onEndDragJS = useNonReactiveCallback(handlers?.onEndDrag) + const onMomentumEndJS = useNonReactiveCallback(handlers?.onMomentumEnd) + const onLeaveTopJS = useNonReactiveCallback(handlers?.onLeaveTop) + + const onBeginDrag = useCallback( + (e: ReanimatedScrollEvent, ctx: Record) => { + 'worklet' + onBeginDragInner?.(e, ctx) + scheduleOnRN(onBeginDragJS) + }, + [onBeginDragInner, onBeginDragJS], + ) + const onEndDrag = useCallback( + (e: ReanimatedScrollEvent, ctx: Record) => { + 'worklet' + onEndDragInner?.(e, ctx) + isAtTop.set(e.contentOffset.y <= SETTLE_AT_TOP_LIMIT) + scheduleOnRN(onEndDragJS, e.contentOffset.y, e.velocity?.y ?? 0) + }, + [onEndDragInner, isAtTop, onEndDragJS], + ) + const onMomentumEnd = useCallback( + (e: ReanimatedScrollEvent, ctx: Record) => { + 'worklet' + onMomentumEndInner?.(e, ctx) + isAtTop.set(e.contentOffset.y <= SETTLE_AT_TOP_LIMIT) + scheduleOnRN(onMomentumEndJS, e.contentOffset.y) + }, + [onMomentumEndInner, isAtTop, onMomentumEndJS], + ) + const onScroll = useCallback( + (e: ReanimatedScrollEvent, ctx: Record) => { + 'worklet' + onScrollInner?.(e, ctx) + const atTop = e.contentOffset.y <= SETTLE_AT_TOP_LIMIT + if (atTop !== isAtTop.get()) { + isAtTop.set(atTop) + if (!atTop) { + scheduleOnRN(onLeaveTopJS) + } + } + }, + [onScrollInner, isAtTop, onLeaveTopJS], + ) + + if (!handlers) { + return inner + } + return {onBeginDrag, onEndDrag, onMomentumEnd, onScroll} +}