From e83e223b9f0f9e4af8210c5eb4ff73796fe4c028 Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Tue, 4 Aug 2026 12:10:23 -0400 Subject: [PATCH] fix(community-feed): stop feed refetches hijacking scroll position (#151) --- src/state/queries/community-feed.ts | 71 ++++++++++++++++++------ src/view/com/feeds/CommunityFeedPage.tsx | 70 +++++++++++++++++++---- 2 files changed, 111 insertions(+), 30 deletions(-) diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts index 1ad32f88e..1753c6180 100644 --- a/src/state/queries/community-feed.ts +++ b/src/state/queries/community-feed.ts @@ -3,6 +3,7 @@ import { AppBskyFeedDefs, type AppBskyFeedPost, AtUri, + type BskyAgent, jsonToLex, moderatePost, type ModerationDecision, @@ -18,6 +19,7 @@ import { import {communityXrpc} from '#/lib/api/community' import {FeedTuner} from '#/lib/api/feed-manip' import {useModerationOpts} from '#/state/preferences/moderation-opts' +import {STALE} from '#/state/queries' import {usePreferencesQuery} from '#/state/queries/preferences' import { didOrHandleUriMatches, @@ -118,10 +120,60 @@ export function useCommunityTimelineQuery(enabled: boolean) { }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, + // Never auto-refetch when `enabled` flips back on: replaying every + // loaded page shifts content under the viewport (same reason the + // page polls a head probe instead of refetching on a timer). + staleTime: STALE.INFINITY, enabled, }) } +/** + * Fetch the newest surfacing community timeline post, for cheap freshness + * probes. Probes a small window rather than a single item because the raw + * head is often a non-surfacing reply that would hide newer posts behind it. + */ +export async function fetchCommunityTimelineHead( + agent: BskyAgent, +): Promise { + const res = await communityXrpc( + agent, + 'community.blacksky.feed.getCommunityTimeline', + {params: {limit: '10'}}, + ) + if (!res.ok) { + throw new Error(`getCommunityTimeline failed: ${res.status}`) + } + const page = jsonToLex(await res.json()) as CommunityFeedPage + return page.feed?.find(surfacesInCommunityFeed) +} + +// A reply only resurfaces its thread when the root author is +// continuing their own thread; other people's replies stay in the +// thread view. Stands in for followedRepliesOnly, which would pass +// everything here since the whole community is "followed". +export function surfacesInCommunityFeed( + item: AppBskyFeedDefs.FeedViewPost, +): boolean { + // Blocked/muted authors never surface, same as the Following feed. + const authorViewer = item.post.author.viewer + if ( + authorViewer?.blocking || + authorViewer?.blockedBy || + authorViewer?.muted + ) { + return false + } + const reply = (item.post.record as AppBskyFeedPost.Record)?.reply + if (!reply?.root?.uri) return true + // Replies whose parent the appview didn't hydrate are orphans; the + // tuner drops them (removeOrphans), so they must not count as new. + if (!item.reason && !AppBskyFeedDefs.isPostView(item.reply?.parent)) { + return false + } + return new AtUri(reply.root.uri).host === item.post.author.did +} + const COMMUNITY_POST_RQKEY_ROOT = 'community-post' export const COMMUNITY_POST_RQKEY = (uri: string) => [ COMMUNITY_POST_RQKEY_ROOT, @@ -201,24 +253,7 @@ export function useCommunityFeedSlices( return useMemo(() => { if (!moderationOpts) return [] - // A reply only resurfaces its thread when the root author is - // continuing their own thread; other people's replies stay in the - // thread view. Stands in for followedRepliesOnly, which would pass - // everything here since the whole community is "followed". - const surfaced = feedItems.filter(item => { - // Blocked/muted authors never surface, same as the Following feed. - const authorViewer = item.post.author.viewer - if ( - authorViewer?.blocking || - authorViewer?.blockedBy || - authorViewer?.muted - ) { - return false - } - const reply = (item.post.record as AppBskyFeedPost.Record)?.reply - if (!reply?.root?.uri) return true - return new AtUri(reply.root.uri).host === item.post.author.did - }) + const surfaced = feedItems.filter(surfacesInCommunityFeed) // Same tuner stack as the Following feed (see useFeedTuners). const tunerFns = [FeedTuner.removeOrphans] if (preferences?.feedViewPrefs.hideReposts) { diff --git a/src/view/com/feeds/CommunityFeedPage.tsx b/src/view/com/feeds/CommunityFeedPage.tsx index d1713e2cf..0926e1569 100644 --- a/src/view/com/feeds/CommunityFeedPage.tsx +++ b/src/view/com/feeds/CommunityFeedPage.tsx @@ -1,17 +1,26 @@ import {useCallback, useEffect, useMemo, useRef, useState} from 'react' import {ActivityIndicator, type ListRenderItemInfo, View} from 'react-native' +import {moderatePost} from '@atproto/api' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {Trans} from '@lingui/react/macro' +import {useQueryClient} from '@tanstack/react-query' +import {getCurrentState} from '#/lib/appState' +import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' import {s} from '#/lib/styles' +import {logger} from '#/logger' +import {useModerationOpts} from '#/state/preferences/moderation-opts' import { type CommunityFeedSlice, + fetchCommunityTimelineHead, + TIMELINE_RQKEY, useCommunityFeedSlices, useCommunityTimelineQuery, } from '#/state/queries/community-feed' -import {useSession} from '#/state/session' +import {truncateAndInvalidate} from '#/state/queries/util' +import {useAgent, useSession} from '#/state/session' import {isThreadChildAt, isThreadParentAt} from '#/view/com/posts/PostFeed' import {PostFeedItem} from '#/view/com/posts/PostFeedItem' import {ViewFullThread} from '#/view/com/posts/ViewFullThread' @@ -42,6 +51,9 @@ type CommunityFeedRow = export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { const {_} = useLingui() const t = useTheme() + const agent = useAgent() + const queryClient = useQueryClient() + const moderationOpts = useModerationOpts() const {hasSession} = useSession() const headerOffset = useHeaderOffset() const scrollElRef = useRef(null) @@ -54,6 +66,7 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { const { data, isLoading, + isFetching, isError, hasNextPage, fetchNextPage, @@ -115,32 +128,65 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { const [isRefreshing, setIsRefreshing] = useState(false) const [isScrolledDown, setIsScrolledDown] = useState(false) + const [hasNew, setHasNew] = useState(false) const onRefresh = useCallback(async () => { setIsRefreshing(true) try { - await refetch() + await truncateAndInvalidate(queryClient, TIMELINE_RQKEY()) + setHasNew(false) } finally { setIsRefreshing(false) } - }, [refetch]) + }, [queryClient]) - useEffect(() => { - if (isPageFocused) void refetch() - }, [isPageFocused, refetch]) + // Refetching an infinite query replays every loaded page, so doing it on + // a timer shifts content under the user's scroll position (see upstream + // PostFeed's "UI freakouts" note). Poll a head probe instead and light + // the load-latest pill; a real refetch only happens on user action or to + // recover an empty/errored feed. + const checkForNew = useNonReactiveCallback(async () => { + if (!isPageFocused || hasNew || isLoading || isFetching || isRefreshing) { + return + } + if (getCurrentState() !== 'active') return + try { + if (feedItems.length === 0) { + void refetch() + return + } + const head = await fetchCommunityTimelineHead(agent) + if (!head) return + if ( + moderationOpts && + moderatePost(head.post, moderationOpts).ui('contentList').filter + ) { + return + } + if (!feedItems.some(item => item.post.uri === head.post.uri)) { + setHasNew(true) + } + } catch (e) { + logger.debug('CommunityFeedPage: head probe failed', { + message: String(e), + }) + } + }) useEffect(() => { if (!isPageFocused) return - const id = setInterval(() => void refetch(), 60_000) + void checkForNew() + const id = setInterval(() => void checkForNew(), 60_000) return () => clearInterval(id) - }, [isPageFocused, refetch]) + }, [isPageFocused, checkForNew]) const onPressLoadLatest = useCallback(() => { scrollElRef.current?.scrollToOffset({ animated: IS_NATIVE, offset: -headerOffset, }) - void refetch() - }, [scrollElRef, headerOffset, refetch]) + setHasNew(false) + void truncateAndInvalidate(queryClient, TIMELINE_RQKEY()) + }, [scrollElRef, headerOffset, queryClient]) const renderItem = useCallback( ({item, index}: ListRenderItemInfo) => { @@ -256,11 +302,11 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { onScrolledDownChange={setIsScrolledDown} /> - {isScrolledDown && ( + {(isScrolledDown || hasNew) && ( )} {hasSession && ( -- knotmirror 0.0.1