From 1fc5f4dd08a3ca1ae4f746307648e98e9294ecdb Mon Sep 17 00:00:00 2001 From: Eric Bailey Date: Mon, 21 Sep 2026 07:42:49 -0500 Subject: [PATCH] Defer Explore feed previews and reuse fresh feed queries (#11719) --- src/lib/api/feed/custom.test.ts | 23 +++ src/lib/api/feed/custom.ts | 13 +- src/lib/api/feed/types.ts | 2 + src/screens/Search/Explore.tsx | 11 +- .../queries/explore-feed-previews.test.tsx | 146 ++++++++++++++++++ src/state/queries/explore-feed-previews.tsx | 40 +++-- 6 files changed, 218 insertions(+), 17 deletions(-) create mode 100644 src/state/queries/explore-feed-previews.test.tsx diff --git a/src/lib/api/feed/custom.test.ts b/src/lib/api/feed/custom.test.ts index 10be09310..ae3bed6ac 100644 --- a/src/lib/api/feed/custom.test.ts +++ b/src/lib/api/feed/custom.test.ts @@ -13,6 +13,29 @@ jest.mock('./utils', () => ({ })) describe('CustomFeedAPI', () => { + it('passes the abort signal to authenticated requests', async () => { + const call = jest.fn().mockResolvedValue({feed: []}) + const client = { + did: 'did:plc:test', + call, + } as unknown as Client + const api = new CustomFeedAPI({ + client, + feedParams: { + feed: 'at://did:example:feed/app.bsky.feed.generator/test', + }, + }) + const signal = new AbortController().signal + + await api.fetch({cursor: undefined, limit: 10, signal}) + + expect(call).toHaveBeenCalledWith( + expect.anything(), + expect.anything(), + expect.objectContaining({signal}), + ) + }) + it('preserves the cursor from an empty logged-out fallback page', async () => { const originalFetch = global.fetch const fetchMock: jest.MockedFunction = jest diff --git a/src/lib/api/feed/custom.ts b/src/lib/api/feed/custom.ts index 86b1c12c6..c3329af76 100644 --- a/src/lib/api/feed/custom.ts +++ b/src/lib/api/feed/custom.ts @@ -51,9 +51,11 @@ export class CustomFeedAPI implements FeedAPI { async fetch({ cursor, limit, + signal, }: { cursor: string | undefined limit: number + signal?: AbortSignal }): Promise { const contentLangs = getContentLanguages().join(',') const isBlueskyOwned = isBlueskyOwnedFeed(this.params.feed) @@ -73,6 +75,7 @@ export class CustomFeedAPI implements FeedAPI { limit, }, { + signal, headers: { ...(isBlueskyOwned ? createBskyTopicsHeader(this.userInterests) @@ -81,7 +84,7 @@ export class CustomFeedAPI implements FeedAPI { }, }, ) - : await loggedOutFetch({...this.params, cursor, limit}) + : await loggedOutFetch({...this.params, cursor, limit}, signal) if (!data) { return { @@ -144,16 +147,17 @@ function getLoggedOutAppviewClient(): Client { */ async function loggedOutFetch( params: GetCustomFeedParams, + signal?: AbortSignal, ): Promise { const contentLangs = getAppLanguageAsContentLanguage() - let data = await getFeedOrNull(params, contentLangs) + let data = await getFeedOrNull(params, contentLangs, signal) if (data?.feed?.length) { return data } // no data, try again with language headers removed - data = await getFeedOrNull(params, '') + data = await getFeedOrNull(params, '', signal) return data } @@ -168,12 +172,13 @@ async function loggedOutFetch( async function getFeedOrNull( params: GetCustomFeedParams, contentLangs: string, + signal?: AbortSignal, ): Promise { try { return await getLoggedOutAppviewClient().call( app.bsky.feed.getFeed, params, - {headers: {'Accept-Language': contentLangs}}, + {signal, headers: {'Accept-Language': contentLangs}}, ) } catch (e) { if (e instanceof XrpcResponseError) { diff --git a/src/lib/api/feed/types.ts b/src/lib/api/feed/types.ts index 59803a992..c1cdce2fe 100644 --- a/src/lib/api/feed/types.ts +++ b/src/lib/api/feed/types.ts @@ -10,9 +10,11 @@ export interface FeedAPI { fetch({ cursor, limit, + signal, }: { cursor: string | undefined limit: number + signal?: AbortSignal }): Promise } diff --git a/src/screens/Search/Explore.tsx b/src/screens/Search/Explore.tsx index 210c19265..ffe7b2a28 100644 --- a/src/screens/Search/Explore.tsx +++ b/src/screens/Search/Explore.tsx @@ -285,6 +285,7 @@ export function Explore({ useGetSuggestedFeedsQuery({ enabled: useFullExperience, }) + const [feedPreviewsEnabled, setFeedPreviewsEnabled] = useState(false) const { data: feedPreviewSlices, query: { @@ -294,7 +295,10 @@ export function Explore({ hasNextPage: hasNextPageFeedPreviews, error: feedPreviewSlicesError, }, - } = useFeedPreviews(suggestedFeeds?.feeds ?? [], useFullExperience) + } = useFeedPreviews( + suggestedFeeds?.feeds ?? [], + useFullExperience && feedPreviewsEnabled, + ) const qc = useQueryClient() const [isPTR, setIsPTR] = useState(false) @@ -1094,6 +1098,11 @@ export function Explore({ ) const handleOnEndReached = () => { + if (!useFullExperience) return + if (!feedPreviewsEnabled) { + setFeedPreviewsEnabled(true) + return + } void onLoadMoreFeedPreviews() } diff --git a/src/state/queries/explore-feed-previews.test.tsx b/src/state/queries/explore-feed-previews.test.tsx new file mode 100644 index 000000000..dc5d78544 --- /dev/null +++ b/src/state/queries/explore-feed-previews.test.tsx @@ -0,0 +1,146 @@ +import {type PropsWithChildren} from 'react' +import { + notifyManager, + QueryClient, + QueryClientProvider, +} from '@tanstack/react-query' +import {act, renderHook, waitFor} from '@testing-library/react-native' + +import {useModerationOpts} from '#/state/preferences/moderation-opts' +import {usePreferencesQuery} from '#/state/queries/preferences' +import {useAppviewClient} from '#/state/session' +import {type app} from '#/lexicons' +import {useFeedPreviews} from './explore-feed-previews' + +const mockFetchFeed = jest.fn() + +jest.mock('@lingui/react', () => ({ + useLingui: () => ({_: (message: unknown) => String(message)}), +})) + +jest.mock('#/lib/api/feed/custom', () => ({ + CustomFeedAPI: jest.fn().mockImplementation(() => ({ + fetch: mockFetchFeed, + })), +})) + +jest.mock('#/lib/api/feed/utils', () => ({ + aggregateUserInterests: jest.fn(), +})) + +jest.mock('#/state/preferences/moderation-opts', () => ({ + useModerationOpts: jest.fn(), +})) + +jest.mock('#/state/queries/preferences', () => ({ + usePreferencesQuery: jest.fn(), +})) + +jest.mock('#/state/session', () => ({ + useAppviewClient: jest.fn(), +})) + +const feeds = [ + {uri: 'at://did:plc:first/app.bsky.feed.generator/feed'}, + {uri: 'at://did:plc:second/app.bsky.feed.generator/feed'}, +] as unknown as app.bsky.feed.defs.GeneratorView[] + +function setup() { + const queryClient = new QueryClient({ + defaultOptions: { + queries: {gcTime: Infinity, retry: false}, + }, + }) + const wrapper = ({children}: PropsWithChildren) => ( + {children} + ) + const hook = renderHook(() => useFeedPreviews(feeds), {wrapper}) + + return {hook, queryClient, wrapper} +} + +beforeAll(() => { + notifyManager.setNotifyFunction(callback => { + act(callback) + }) +}) + +beforeEach(() => { + jest.clearAllMocks() + mockFetchFeed.mockResolvedValue({feed: []}) + jest.mocked(useModerationOpts).mockReturnValue({} as never) + jest.mocked(usePreferencesQuery).mockReturnValue({data: undefined} as never) + jest.mocked(useAppviewClient).mockReturnValue({} as never) +}) + +describe('useFeedPreviews', () => { + it('does not refetch while fresh', async () => { + const {hook, wrapper} = setup() + + await waitFor(() => expect(hook.result.current.query.isSuccess).toBe(true)) + + expect(mockFetchFeed).toHaveBeenCalledTimes(1) + expect(mockFetchFeed).toHaveBeenCalledWith( + expect.objectContaining({signal: expect.anything()}), + ) + hook.rerender(undefined) + expect(mockFetchFeed).toHaveBeenCalledTimes(1) + + hook.unmount() + const remountedHook = renderHook(() => useFeedPreviews(feeds), {wrapper}) + await waitFor(() => + expect(remountedHook.result.current.query.isSuccess).toBe(true), + ) + + expect(mockFetchFeed).toHaveBeenCalledTimes(1) + remountedHook.unmount() + }) + + it('reuses a fresh feed across preview-list query keys', async () => { + const {hook, wrapper} = setup() + await waitFor(() => expect(mockFetchFeed).toHaveBeenCalledTimes(1)) + hook.unmount() + + const changedListHook = renderHook(() => useFeedPreviews([feeds[0]]), { + wrapper, + }) + await waitFor(() => + expect(changedListHook.result.current.query.isSuccess).toBe(true), + ) + + expect(mockFetchFeed).toHaveBeenCalledTimes(1) + changedListHook.unmount() + }) + + it('reloads a feed after the query becomes stale', async () => { + const now = jest.spyOn(Date, 'now').mockReturnValue(1_000) + + try { + const {hook, wrapper} = setup() + await waitFor(() => expect(mockFetchFeed).toHaveBeenCalledTimes(1)) + hook.unmount() + + now.mockReturnValue(1_000 + 3 * 60 * 1_000 + 1) + const remountedHook = renderHook(() => useFeedPreviews(feeds), {wrapper}) + await waitFor(() => expect(mockFetchFeed).toHaveBeenCalledTimes(2)) + remountedHook.unmount() + } finally { + now.mockRestore() + } + }) + + it('stops after loading the final feed', async () => { + const {hook} = setup() + await waitFor(() => expect(hook.result.current.query.isSuccess).toBe(true)) + + await act(() => hook.result.current.query.fetchNextPage()) + + expect(mockFetchFeed).toHaveBeenCalledTimes(2) + await waitFor(() => + expect(hook.result.current.query.hasNextPage).toBe(false), + ) + + await act(() => hook.result.current.query.fetchNextPage()) + expect(mockFetchFeed).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/state/queries/explore-feed-previews.tsx b/src/state/queries/explore-feed-previews.tsx index f6d0fd031..1c4544431 100644 --- a/src/state/queries/explore-feed-previews.tsx +++ b/src/state/queries/explore-feed-previews.tsx @@ -7,6 +7,7 @@ import { type InfiniteData, type QueryClient, useInfiniteQuery, + useQueryClient, } from '@tanstack/react-query' import {CustomFeedAPI} from '#/lib/api/feed/custom' @@ -18,6 +19,7 @@ import { } from '#/lib/api/feed-manip' import {cleanError} from '#/lib/strings/errors' import {useModerationOpts} from '#/state/preferences/moderation-opts' +import {STALE} from '#/state/queries' import { type FeedPostSlice, type FeedPostSliceItem, @@ -34,6 +36,7 @@ import * as bsky from '#/types/bsky' const RQKEY_ROOT = 'feed-previews' const RQKEY = (feeds: string[]) => [RQKEY_ROOT, feeds] +const FEED_RQKEY = (feed: string) => ['feed-preview', feed] const LIMIT = 8 // sliced to 6, overfetch to account for moderation const PINNED_POST_URIS: Record = { @@ -124,6 +127,7 @@ export function useFeedPreviews( const uris = feeds.map(feed => feed.uri) const {_} = useLingui() const client = useAppviewClient() + const queryClient = useQueryClient() const {data: preferences} = usePreferencesQuery() const userInterests = aggregateUserInterests(preferences) const moderationOpts = useModerationOpts() @@ -141,23 +145,35 @@ export function useFeedPreviews( const query = useInfiniteQuery({ enabled, + staleTime: STALE.MINUTES.THREE, queryKey: RQKEY(uris), - queryFn: async ({pageParam}) => { + queryFn: async ({pageParam, signal}) => { const feed = feeds[pageParam] - const api = new CustomFeedAPI({ - client, - feedParams: {feed: feed.uri}, - userInterests, + return queryClient.fetchQuery({ + queryKey: FEED_RQKEY(feed.uri), + staleTime: STALE.MINUTES.THREE, + gcTime: STALE.MINUTES.THREE, + queryFn: async () => { + const api = new CustomFeedAPI({ + client, + feedParams: {feed: feed.uri}, + userInterests, + }) + const data = await api.fetch({ + cursor: undefined, + limit: LIMIT, + signal, + }) + return { + feed, + posts: data.feed, + } + }, }) - const data = await api.fetch({cursor: undefined, limit: LIMIT}) - return { - feed, - posts: data.feed, - } }, initialPageParam: 0, - getNextPageParam: (_p, _a, count) => - count < feeds.length ? count + 1 : undefined, + getNextPageParam: (_page, _pages, pageParam) => + pageParam + 1 < feeds.length ? pageParam + 1 : undefined, }) const {data, isFetched, isError, isPending, error} = query -- knotmirror 0.0.1