From fe4549ade4226f751876e6abe2cc022414fc8729 Mon Sep 17 00:00:00 2001 From: Samuel Newman Date: Fri, 2 Oct 2026 17:38:16 +0300 Subject: [PATCH] Fork Home behind the Following v2 flag (#11843) Co-authored-by: Claude Opus 5.5 (1M context) --- src/Navigation.tsx | 2 +- src/features/followingV2/eligibility.ts | 20 +- src/features/followingV2/home/FeedPage.tsx | 197 +++ src/features/followingV2/home/Home.tsx | 374 +++++ src/features/followingV2/home/PostFeed.tsx | 1197 +++++++++++++++++ src/features/followingV2/home/api/custom.ts | 190 +++ .../followingV2/home/api/following.ts | 42 + src/features/followingV2/home/api/home.ts | 114 ++ src/features/followingV2/home/api/list.ts | 56 + src/features/followingV2/home/api/merge.ts | 359 +++++ src/features/followingV2/home/api/types.ts | 34 + src/features/followingV2/home/index.test.tsx | 67 + src/features/followingV2/home/index.tsx | 24 + .../home/queries/postFeed.test.tsx | 100 ++ .../followingV2/home/queries/postFeed.ts | 509 +++++++ src/screens/VideoFeed/index.tsx | 24 +- src/screens/VideoFeed/types.ts | 5 + 17 files changed, 3306 insertions(+), 8 deletions(-) create mode 100644 src/features/followingV2/home/FeedPage.tsx create mode 100644 src/features/followingV2/home/Home.tsx create mode 100644 src/features/followingV2/home/PostFeed.tsx create mode 100644 src/features/followingV2/home/api/custom.ts create mode 100644 src/features/followingV2/home/api/following.ts create mode 100644 src/features/followingV2/home/api/home.ts create mode 100644 src/features/followingV2/home/api/list.ts create mode 100644 src/features/followingV2/home/api/merge.ts create mode 100644 src/features/followingV2/home/api/types.ts create mode 100644 src/features/followingV2/home/index.test.tsx create mode 100644 src/features/followingV2/home/index.tsx create mode 100644 src/features/followingV2/home/queries/postFeed.test.tsx create mode 100644 src/features/followingV2/home/queries/postFeed.ts diff --git a/src/Navigation.tsx b/src/Navigation.tsx index 41338a61f..5e4e8b2f7 100644 --- a/src/Navigation.tsx +++ b/src/Navigation.tsx @@ -58,7 +58,6 @@ import {CommunityGuidelinesScreen} from '#/view/screens/CommunityGuidelines' import {CopyrightPolicyScreen} from '#/view/screens/CopyrightPolicy' import {DebugModScreen} from '#/view/screens/DebugMod' import {FeedsScreen} from '#/view/screens/Feeds' -import {HomeScreen} from '#/view/screens/Home' import {ListsScreen} from '#/view/screens/Lists' import {ModerationBlockedAccounts} from '#/view/screens/ModerationBlockedAccounts' import {ModerationModlistsScreen} from '#/view/screens/ModerationModlists' @@ -142,6 +141,7 @@ import { import {useAnalytics} from '#/analytics' import {setNavigationMetadata} from '#/analytics/metadata' import {IS_LIQUID_GLASS, IS_NATIVE, IS_WEB} from '#/env' +import {HomeScreen} from '#/features/followingV2/home' import {InviteScannerScreen} from '#/features/inviteFriends' import {router} from '#/routes' diff --git a/src/features/followingV2/eligibility.ts b/src/features/followingV2/eligibility.ts index e658dad3a..81ee6d7db 100644 --- a/src/features/followingV2/eligibility.ts +++ b/src/features/followingV2/eligibility.ts @@ -4,7 +4,8 @@ import {IS_NATIVE} from '#/env' /** * Whether Following v2 behaviour applies. Every Following v2 call site gates * through this rather than reading `following_v2:enable` directly, except the - * Home tab dot (see {@link isFollowingV2HomeDotEnabled}). + * Home tab dot (see {@link isFollowingV2HomeDotEnabled}) and the Home fork + * (see {@link isFollowingV2HomeForkEnabled}). * * Following v2 is native-only: web keeps its existing fetch, refresh and * navigation behaviour whatever the flag says. The platform check runs first, @@ -32,3 +33,20 @@ export function isFollowingV2HomeDotEnabled( ) { return ax.features.enabled(ax.features.FollowingV2Enable) } + +/** + * Whether the Home route renders the Following v2 fork of Home in + * `#/features/followingV2/home` rather than today's Home. This is true wherever + * `following_v2:enable` is on, web included, so web runs the fork's code and + * it doesn't rot while Following v2 is built on it. + * + * Running the fork's code is not the same as Following v2 behaviour applying. + * Inside the fork, the behaviours (persistence, prepends, the new posts pill, + * freshness checks and positioning) stay native-only and keep gating on + * {@link isFollowingV2Eligible}. + */ +export function isFollowingV2HomeForkEnabled( + ax: Pick, +) { + return ax.features.enabled(ax.features.FollowingV2Enable) +} diff --git a/src/features/followingV2/home/FeedPage.tsx b/src/features/followingV2/home/FeedPage.tsx new file mode 100644 index 000000000..d17eb9e87 --- /dev/null +++ b/src/features/followingV2/home/FeedPage.tsx @@ -0,0 +1,197 @@ +import { + type JSX, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from 'react' +import {View} from 'react-native' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {type NavigationProp, useNavigation} from '@react-navigation/native' +import {useQueryClient} from '@tanstack/react-query' + +import {DISCOVER_FEED_URI, VIDEO_FEED_URIS} from '#/lib/constants' +import {useOpenComposer} from '#/lib/hooks/useOpenComposer' +import {getRootNavigation, getTabState, TabState} from '#/lib/routes/helpers' +import {type AllNavigatorParams} from '#/lib/routes/types' +import {listenSoftReset} from '#/state/events' +import {FeedFeedbackProvider, useFeedFeedback} from '#/state/feed-feedback' +import {useSetHomeBadge} from '#/state/home-badge' +import {type FeedSourceInfo} from '#/state/queries/feed' +import {truncateAndInvalidate} from '#/state/queries/util' +import {useSession} from '#/state/session' +import {FAB} from '#/view/com/util/fab/FAB' +import {type ListMethods} from '#/view/com/util/List' +import {LoadLatestBtn} from '#/view/com/util/load-latest/LoadLatestBtn' +import {MainScrollProvider} from '#/view/com/util/MainScrollProvider' +import {useBreakpoints, useTheme} from '#/alf' +import {useHeaderOffset} from '#/components/hooks/useHeaderOffset' +import {EditBig_Stroke2_Corner2_Rounded as EditBigIcon} from '#/components/icons/EditBig' +import {useAnalytics} from '#/analytics' +import {IS_NATIVE} from '#/env' +import { + isFollowingV2Eligible, + isFollowingV2HomeDotEnabled, +} from '#/features/followingV2/eligibility' +import {app} from '#/lexicons' +import {PostFeed} from './PostFeed' +import { + type FeedDescriptor, + type FeedParams, + RQKEY as FEED_RQKEY, +} from './queries/postFeed' + +const POLL_FREQ = 60e3 // 60sec + +export function FeedPage({ + testID, + isPageFocused, + isPageAdjacent, + feed, + feedParams, + renderEmptyState, + renderEndOfFeed, + savedFeedConfig, + feedInfo, +}: { + testID?: string + feed: FeedDescriptor + feedParams?: FeedParams + isPageFocused: boolean + isPageAdjacent: boolean + renderEmptyState: () => JSX.Element + renderEndOfFeed?: () => JSX.Element + savedFeedConfig?: app.bsky.actor.defs.SavedFeed + feedInfo: FeedSourceInfo +}) { + const ax = useAnalytics() + const {hasSession} = useSession() + const {_} = useLingui() + const navigation = useNavigation>() + const queryClient = useQueryClient() + const {openComposer} = useOpenComposer() + const [isScrolledDown, setIsScrolledDown] = useState(false) + const headerOffset = useHeaderOffset() + const feedFeedback = useFeedFeedback(feedInfo, hasSession) + const scrollElRef = useRef(null) + const [hasNew, setHasNew] = useState(false) + const setHomeBadge = useSetHomeBadge() + const isVideoFeed = useMemo(() => { + const isBskyVideoFeed = VIDEO_FEED_URIS.includes(feedInfo.uri) + const feedIsVideoMode = + feedInfo.contentMode === app.bsky.feed.defs.contentModeVideo.value + const _isVideoFeed = isBskyVideoFeed || feedIsVideoMode + return IS_NATIVE && _isVideoFeed + }, [feedInfo]) + const t = useTheme() + const {gtMobile} = useBreakpoints() + + useEffect(() => { + if (isPageFocused) { + setHomeBadge(hasNew) + } + }, [isPageFocused, hasNew, setHomeBadge]) + + const scrollToTop = useCallback(() => { + scrollElRef.current?.scrollToOffset({ + animated: IS_NATIVE, + offset: -headerOffset, + }) + }, [headerOffset]) + + const onSoftReset = useCallback(() => { + const isScreenFocused = + getTabState(getRootNavigation(navigation).getState(), 'Home') === + TabState.InsideAtRoot + if (isScreenFocused && isPageFocused) { + scrollToTop() + void truncateAndInvalidate(queryClient, FEED_RQKEY(feed)) + setHasNew(false) + ax.metric('feed:refresh', { + feedType: feed.split('|')[0], + feedUrl: feed, + reason: 'soft-reset', + }) + } + }, [ax, navigation, isPageFocused, scrollToTop, queryClient, feed]) + + // fires when page within screen is activated/deactivated + useEffect(() => { + if (!isPageFocused) { + return + } + return listenSoftReset(onSoftReset) + }, [onSoftReset, isPageFocused]) + + const onPressCompose = useCallback(() => { + openComposer({logContext: 'Fab'}) + }, [openComposer]) + + const onPressLoadLatest = useCallback(() => { + scrollToTop() + void truncateAndInvalidate(queryClient, FEED_RQKEY(feed)) + setHasNew(false) + ax.metric('feed:refresh', { + feedType: feed.split('|')[0], + feedUrl: feed, + reason: 'load-latest', + }) + }, [ax, scrollToTop, feed, queryClient]) + + const shouldPrefetch = IS_NATIVE && isPageAdjacent + const isDiscoverFeed = feedInfo.uri === DISCOVER_FEED_URI + return ( + + + + + + + {/* + * With Following v2, native replaces Load Latest with the new posts pill + * and mobile web relies on the Home tab dot. Tablet and desktop web have + * no pill, so they keep the button. + */} + {(isScrolledDown || hasNew) && + !isFollowingV2Eligible(ax) && + !(isFollowingV2HomeDotEnabled(ax) && !gtMobile) && ( + + )} + + {hasSession && ( + } + accessibilityRole="button" + accessibilityLabel={_(msg({message: `New post`, context: 'action'}))} + accessibilityHint="" + /> + )} + + ) +} diff --git a/src/features/followingV2/home/Home.tsx b/src/features/followingV2/home/Home.tsx new file mode 100644 index 000000000..3dee54555 --- /dev/null +++ b/src/features/followingV2/home/Home.tsx @@ -0,0 +1,374 @@ +import {useCallback, useEffect, useLayoutEffect, useMemo, useRef} from 'react' +import {ActivityIndicator, StyleSheet} from 'react-native' +import { + Reanimated3DefaultSpringConfig, + withSpring, +} from 'react-native-reanimated' +import {useLingui} from '@lingui/react/macro' +import {useFocusEffect} from '@react-navigation/native' + +import { + DISCOVER_FEED_URI, + PROD_DEFAULT_FEED, + TIMELINE_SAVED_FEED, +} from '#/lib/constants' +import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' +import {useOTAUpdates} from '#/lib/hooks/useOTAUpdates' +import {useSetTitle} from '#/lib/hooks/useSetTitle' +import {useRequestNotificationsPermission} from '#/lib/notifications/notifications' +import { + type HomeTabNavigatorParams, + type NativeStackScreenProps, +} from '#/lib/routes/types' +import {getLocalizedFeedName} from '#/lib/strings/feed-names' +import {emitSoftReset} from '#/state/events' +import { + type SavedFeedSourceInfo, + usePinnedFeedsInfos, +} from '#/state/queries/feed' +import {usePreferencesQuery} from '#/state/queries/preferences' +import {type UsePreferencesQueryResponse} from '#/state/queries/preferences/types' +import {useSession} from '#/state/session' +import {useLoggedOutViewControls} from '#/state/shell/logged-out' +import {useSelectedFeed, useSetSelectedFeed} from '#/state/shell/selected-feed' +import {HomeHeader} from '#/view/com/home/HomeHeader' +import { + Pager, + type PagerRef, + type RenderTabBarFnProps, +} from '#/view/com/pager/Pager' +import {CustomFeedEmptyState} from '#/view/com/posts/CustomFeedEmptyState' +import {FollowingEmptyState} from '#/view/com/posts/FollowingEmptyState' +import {FollowingEndOfFeed} from '#/view/com/posts/FollowingEndOfFeed' +import { + HomeHeaderModeProvider, + useHomeHeaderMode, +} from '#/view/com/util/MainScrollProvider' +import {NoFeedsPinned} from '#/screens/Home/NoFeedsPinned' +import * as Layout from '#/components/Layout' +import {useAnalytics} from '#/analytics' +import {IS_LIQUID_GLASS, IS_WEB} from '#/env' +import {useDemoMode} from '#/storage/hooks/demo-mode' +import {FeedPage} from './FeedPage' +import {type FeedDescriptor, type FeedParams} from './queries/postFeed' + +type Props = NativeStackScreenProps +export function HomeScreen(props: Props) { + const {setShowLoggedOut} = useLoggedOutViewControls() + const {data: preferences} = usePreferencesQuery() + const {currentAccount} = useSession() + const {data: pinnedFeedInfos, isLoading: isPinnedFeedsLoading} = + usePinnedFeedsInfos() + + useEffect(() => { + if (IS_WEB && !currentAccount) { + const getParams = new URLSearchParams(window.location.search) + const splash = getParams.get('splash') + if (splash === 'true') { + setShowLoggedOut(true) + return + } + } + + const params = props.route.params + if ( + currentAccount && + props.route.name === 'Start' && + params?.name && + params?.rkey + ) { + props.navigation.navigate('StarterPack', { + rkey: params.rkey, + name: params.name, + }) + } + }, [ + currentAccount, + props.navigation, + props.route.name, + props.route.params, + setShowLoggedOut, + ]) + + if (preferences && pinnedFeedInfos && !isPinnedFeedsLoading) { + return ( + + + + + + ) + } else { + return ( + + + + + + ) + } +} + +function HomeScreenReady({ + preferences, + pinnedFeedInfos, +}: Props & { + preferences: UsePreferencesQueryResponse + pinnedFeedInfos: SavedFeedSourceInfo[] +}) { + const {i18n} = useLingui() + const ax = useAnalytics() + const allFeeds = useMemo( + () => pinnedFeedInfos.map(f => f.feedDescriptor), + [pinnedFeedInfos], + ) + const maybeRawSelectedFeed: FeedDescriptor | undefined = + useSelectedFeed() ?? allFeeds[0] + const setSelectedFeed = useSetSelectedFeed() + const maybeFoundIndex = allFeeds.indexOf(maybeRawSelectedFeed) + const selectedIndex = Math.max(0, maybeFoundIndex) + const maybeSelectedFeed: FeedDescriptor | undefined = allFeeds[selectedIndex] + const selectedFeedInfo = pinnedFeedInfos[selectedIndex] + const requestNotificationsPermission = useRequestNotificationsPermission() + + useSetTitle(selectedFeedInfo && getLocalizedFeedName(selectedFeedInfo, i18n)) + useOTAUpdates() + + useEffect(() => { + void requestNotificationsPermission('Home') + }, [requestNotificationsPermission]) + + const pagerRef = useRef(null) + const lastPagerReportedIndexRef = useRef(selectedIndex) + useLayoutEffect(() => { + // Since the pager is not a controlled component, adjust it imperatively + // if the selected index gets out of sync with what it last reported. + // This is supposed to only happen on the web when you use the right nav. + if (selectedIndex !== lastPagerReportedIndexRef.current) { + lastPagerReportedIndexRef.current = selectedIndex + pagerRef.current?.setPage(selectedIndex) + } + }, [selectedIndex]) + + const {hasSession} = useSession() + const headerMode = useHomeHeaderMode() + const showHeader = useCallback(() => { + 'worklet' + headerMode.set( + withSpring(0, { + ...Reanimated3DefaultSpringConfig, + overshootClamping: true, + }), + ) + }, [headerMode]) + + useFocusEffect( + useCallback(() => { + return () => showHeader() + }, [showHeader]), + ) + + useFocusEffect( + useNonReactiveCallback(() => { + if (maybeSelectedFeed) { + ax.metric('home:feedDisplayed', { + index: selectedIndex, + feedType: maybeSelectedFeed.split('|')[0], + feedUrl: maybeSelectedFeed, + reason: 'focus', + }) + } + }), + ) + + const onPageSelected = useCallback( + (index: number) => { + showHeader() + const maybeFeed = allFeeds[index] + + // Mutate the ref before setting state to avoid the imperative syncing effect + // above from starting a loop on Android when swiping back and forth. + lastPagerReportedIndexRef.current = index + setSelectedFeed(maybeFeed) + + if (maybeFeed) { + ax.metric('home:feedDisplayed', { + index, + feedType: maybeFeed.split('|')[0], + feedUrl: maybeFeed, + }) + } + }, + [ax, setSelectedFeed, showHeader, allFeeds], + ) + + const onPressSelected = useCallback(() => { + emitSoftReset() + }, []) + + const onPageScrollStateChanged = useCallback( + (state: 'idle' | 'dragging' | 'settling') => { + 'worklet' + if (state === 'dragging') { + showHeader() + } + }, + [showHeader], + ) + + const [demoMode] = useDemoMode() + + const renderTabBar = useCallback( + (props: RenderTabBarFnProps) => { + if (demoMode) { + return ( + + ) + } + return ( + + ) + }, + [onPressSelected, pinnedFeedInfos, demoMode], + ) + + const renderFollowingEmptyState = useCallback(() => { + return + }, []) + + const renderCustomFeedEmptyState = useCallback(() => { + return + }, []) + + const homeFeedParams = useMemo(() => { + return { + mergeFeedEnabled: Boolean(preferences.feedViewPrefs.lab_mergeFeedEnabled), + mergeFeedSources: preferences.feedViewPrefs.lab_mergeFeedEnabled + ? preferences.savedFeeds + .filter(f => f.type === 'feed' || f.type === 'list') + .map(f => f.value) + : [], + } + }, [preferences]) + + if (demoMode) { + return ( + + + + + ) + } + + return hasSession ? ( + + {pinnedFeedInfos.length ? ( + pinnedFeedInfos.map((feedInfo, index) => { + const feed = feedInfo.feedDescriptor + if (feed === 'following') { + return ( + + ) + } + const savedFeedConfig = feedInfo.savedFeed + return ( + + ) + }) + ) : ( + + )} + + ) : ( + + + + ) +} + +const styles = StyleSheet.create({ + loading: { + height: '100%', + alignContent: 'center', + justifyContent: 'center', + paddingBottom: 100, + }, +}) diff --git a/src/features/followingV2/home/PostFeed.tsx b/src/features/followingV2/home/PostFeed.tsx new file mode 100644 index 000000000..bb7954905 --- /dev/null +++ b/src/features/followingV2/home/PostFeed.tsx @@ -0,0 +1,1197 @@ +import { + memo, + useCallback, + useEffect, + useImperativeHandle, + useMemo, + useRef, + useState, +} from 'react' +import { + ActivityIndicator, + AppState, + Dimensions, + LayoutAnimation, + type ListRenderItemInfo, + type StyleProp, + StyleSheet, + View, + type ViewStyle, +} from 'react-native' +import {type RichText as RichTextType} from '@bsky/sdk/richtext' +import {useLingui} from '@lingui/react/macro' +import {useQueryClient} from '@tanstack/react-query' + +import {DISCOVER_FEED_URI, KNOWN_SHUTDOWN_FEEDS} from '#/lib/constants' +import {useBottomBarOffset} from '#/lib/hooks/useBottomBarOffset' +import {useInitialNumToRender} from '#/lib/hooks/useInitialNumToRender' +import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' +import {isNetworkError} from '#/lib/strings/errors' +import {logger} from '#/logger' +import {usePostAuthorShadowFilter} from '#/state/cache/profile-shadow' +import {listenPostCreated} from '#/state/events' +import {useFeedFeedbackContext} from '#/state/feed-feedback' +import {useTrendingSettings} from '#/state/preferences/trending' +import {STALE} from '#/state/queries' +import {truncateAndInvalidate} from '#/state/queries/util' +import {useSession} from '#/state/session' +import {useProgressGuide} from '#/state/shell/progress-guide' +import {useSelectedFeed} from '#/state/shell/selected-feed' +import {ComposerPrompt} from '#/view/com/feeds/ComposerPrompt' +import {DiscoverFallbackHeader} from '#/view/com/posts/DiscoverFallbackHeader' +import {FeedShutdownMsg} from '#/view/com/posts/FeedShutdownMsg' +import {PostFeedErrorMessage} from '#/view/com/posts/PostFeedErrorMessage' +import {PostFeedItem} from '#/view/com/posts/PostFeedItem' +import {ShowLessFollowup} from '#/view/com/posts/ShowLessFollowup' +import {ViewFullThread} from '#/view/com/posts/ViewFullThread' +import {List, type ListRef} from '#/view/com/util/List' +import {PostFeedLoadingPlaceholder} from '#/view/com/util/LoadingPlaceholder' +import {LoadMoreRetryBtn} from '#/view/com/util/LoadMoreRetryBtn' +import {type VideoFeedSourceContext} from '#/screens/VideoFeed/types' +import {atoms as a, useBreakpoints, useLayoutBreakpoints, useTheme} from '#/alf' +import { + AgeAssuranceDismissibleFeedBanner, + useInternalState as useAgeAssuranceBannerState, +} from '#/components/ageAssurance/AgeAssuranceDismissibleFeedBanner' +import {ProgressGuide, SuggestedFollows} from '#/components/FeedInterstitials' +import { + PostFeedVideoGridRow, + PostFeedVideoGridRowPlaceholder, +} from '#/components/feeds/PostFeedVideoGridRow' +import {FeedTrendingTopicsInterstitial} from '#/components/interstitials/FeedTrendingTopics' +import {TrendingVideos as TrendingVideosInterstitial} from '#/components/interstitials/TrendingVideos' +import {isStandardSiteEmbed} from '#/components/Post/Embed/StandardSiteEmbed/utils' +import {RichText} from '#/components/RichText' +import {useAnalytics} from '#/analytics' +import {IS_IOS, IS_NATIVE, IS_WEB} from '#/env' +import {DiscoverFeedLiveEventFeedsAndTrendingBanner} from '#/features/liveEvents/components/DiscoverFeedLiveEventFeedsAndTrendingBanner' +import { + isStatusStillActive, + isStatusValidForViewers, + useLiveNowConfig, +} from '#/features/liveNow' +import {app} from '#/lexicons' +import * as bsky from '#/types/bsky' +import { + type AuthorFilter, + type FeedDescriptor, + type FeedParams, + type FeedPostSlice, + type FeedPostSliceItem, + pollLatest, + RQKEY, + usePostFeedQuery, +} from './queries/postFeed' + +type FeedRow = + | { + type: 'loading' + key: string + } + | { + type: 'empty' + key: string + } + | { + type: 'error' + key: string + } + | { + type: 'loadMoreError' + key: string + } + | { + type: 'feedShutdownMsg' + key: string + } + | { + type: 'fallbackMarker' + key: string + } + | { + type: 'description' + key: string + value: RichTextType + } + | { + type: 'sliceItem' + key: string + slice: FeedPostSlice + indexInSlice: number + showReplyTo: boolean + } + | { + type: 'videoGridRowPlaceholder' + key: string + } + | { + type: 'videoGridRow' + key: string + items: FeedPostSliceItem[] + sourceFeedUri: string + feedContexts: (string | undefined)[] + reqIds: (string | undefined)[] + } + | { + type: 'sliceViewFullThread' + key: string + uri: string + } + | { + type: 'interstitialFollows' + key: string + } + | { + type: 'interstitialProgressGuide' + key: string + } + | { + type: 'interstitialFeedTrendingTopics' + key: string + feedSliceIndex: number + } + | { + type: 'interstitialTrendingVideos' + key: string + } + | { + type: 'showLessFollowup' + key: string + } + | { + type: 'ageAssuranceBanner' + key: string + } + | { + type: 'composerPrompt' + key: string + } + | { + type: 'liveEventFeedsAndTrendingBanner' + key: string + } + +export function getItemsForFeedback(feedRow: FeedRow): { + item: FeedPostSliceItem + feedContext: string | undefined + reqId: string | undefined +}[] { + if (feedRow.type === 'sliceItem') { + return feedRow.slice.items.map(item => ({ + item, + feedContext: feedRow.slice.feedContext, + reqId: feedRow.slice.reqId, + })) + } else if (feedRow.type === 'videoGridRow') { + return feedRow.items.map((item, i) => ({ + item, + feedContext: feedRow.feedContexts[i], + reqId: feedRow.reqIds[i], + })) + } else { + return [] + } +} + +export type PostFeedRef = { + refreshFeed: () => Promise +} + +// DISABLED need to check if this is causing random feed refreshes -prf +// const REFRESH_AFTER = STALE.HOURS.ONE +const CHECK_LATEST_AFTER = STALE.SECONDS.THIRTY + +let PostFeed = ({ + feed, + description, + feedParams, + ignoreFilterFor, + style, + enabled, + pollInterval, + disablePoll, + scrollElRef, + onScrolledDownChange, + onHasNew, + renderEmptyState, + renderEndOfFeed, + testID, + headerOffset = 0, + progressViewOffset, + desktopFixedHeightOffset, + ListHeaderComponent, + extraData, + savedFeedConfig, + initialNumToRender: initialNumToRenderOverride, + isVideoFeed = false, + ref, +}: { + feed: FeedDescriptor + description?: RichTextType + feedParams?: FeedParams + ignoreFilterFor?: string + style?: StyleProp + enabled?: boolean + pollInterval?: number + disablePoll?: boolean + scrollElRef?: ListRef + onHasNew?: (v: boolean) => void + onScrolledDownChange?: (isScrolledDown: boolean) => void + renderEmptyState: () => React.ReactElement + renderEndOfFeed?: () => React.ReactElement + testID?: string + headerOffset?: number + progressViewOffset?: number + desktopFixedHeightOffset?: number + ListHeaderComponent?: () => React.ReactElement + extraData?: Record + savedFeedConfig?: app.bsky.actor.defs.SavedFeed + initialNumToRender?: number + isVideoFeed?: boolean + lastFetchDate?: () => number + ref?: React.Ref +}): React.ReactNode => { + const ax = useAnalytics() + const t = useTheme() + const {t: l} = useLingui() + const queryClient = useQueryClient() + const {currentAccount, hasSession} = useSession() + const initialNumToRender = useInitialNumToRender() + const feedFeedback = useFeedFeedbackContext() + const [isPTRing, setIsPTRing] = useState(false) + // eslint-disable-next-line react-hooks/purity + const lastFetchRef = useRef(Date.now()) + const [feedType, feedUriOrActorDid, feedTab] = feed.split('|') + const {gtMobile} = useBreakpoints() + const {rightNavVisible} = useLayoutBreakpoints() + const areVideoFeedsEnabled = IS_NATIVE + + const trendingIndices = ax.features.getValue( + ax.features.TrendingDiscoverValues, + { + topics: 5, + accounts: 15, + videos: 30, + }, + ) + + const [hasPressedShowLessUris, setHasPressedShowLessUris] = useState( + () => new Set(), + ) + const onPressShowLess = useCallback( + (interaction: app.bsky.feed.defs.Interaction) => { + if (interaction.item) { + const uri = interaction.item + setHasPressedShowLessUris(prev => new Set([...prev, uri])) + LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) + } + }, + [], + ) + + const feedCacheKey = feedParams?.feedCacheKey + const opts = useMemo( + () => ({enabled, ignoreFilterFor}), + [enabled, ignoreFilterFor], + ) + const { + data, + isFetching, + isFetched, + isError, + error, + refetch, + hasNextPage, + isFetchingNextPage, + fetchNextPage, + } = usePostFeedQuery(feed, feedParams, opts) + const lastFetchedAt = data?.pages[0].fetchedAt + const isEmpty = useMemo( + () => !isFetching && !data?.pages?.some(page => page.slices.length), + [isFetching, data], + ) + + useEffect(() => { + if (lastFetchedAt) { + lastFetchRef.current = lastFetchedAt + } + }, [lastFetchedAt]) + + const checkForNew = useNonReactiveCallback(async () => { + if (!data?.pages[0] || isFetching || !onHasNew || !enabled || disablePoll) { + return + } + + // Discover always has fresh content + if (feedUriOrActorDid === DISCOVER_FEED_URI) { + return onHasNew(true) + } + + try { + if (await pollLatest(data.pages[0])) { + if (isEmpty) { + void refetch() + } else { + onHasNew(true) + } + } + } catch (e) { + if (!isNetworkError(e)) { + logger.warn('Poll latest failed', {feed, message: String(e)}) + } + } + }) + + const isScrolledDownRef = useRef(false) + const handleScrolledDownChange = (isScrolledDown: boolean) => { + isScrolledDownRef.current = isScrolledDown + onScrolledDownChange?.(isScrolledDown) + } + + const myDid = currentAccount?.did || '' + const onPostCreated = useCallback(() => { + // NOTE + // only invalidate if at the top of the feed + // changing content when scrolled can trigger some UI freakouts on iOS and android + // -sfn + if ( + !isScrolledDownRef.current && + (feed === 'following' || + feed === `author|${myDid}|posts_and_author_threads`) + ) { + void queryClient.invalidateQueries({queryKey: RQKEY(feed)}) + } + }, [queryClient, feed, myDid]) + useEffect(() => { + return listenPostCreated(onPostCreated) + }, [onPostCreated]) + + useEffect(() => { + if (enabled && !disablePoll) { + const timeSinceFirstLoad = Date.now() - lastFetchRef.current + if (isEmpty || timeSinceFirstLoad > CHECK_LATEST_AFTER) { + // check for new on enable (aka on focus) + void checkForNew() + } + } + }, [enabled, isEmpty, disablePoll, checkForNew]) + + useEffect(() => { + let cleanup1: () => void | undefined, cleanup2: () => void | undefined + const subscription = AppState.addEventListener('change', nextAppState => { + // check for new on app foreground + if (nextAppState === 'active') { + void checkForNew() + } + }) + cleanup1 = () => subscription.remove() + if (pollInterval) { + // check for new on interval + const i = setInterval(() => { + void checkForNew() + }, pollInterval) + cleanup2 = () => clearInterval(i) + } + return () => { + cleanup1?.() + cleanup2?.() + } + }, [pollInterval, checkForNew]) + + const followProgressGuide = useProgressGuide('follow-10') + const followAndLikeProgressGuide = useProgressGuide('like-10-and-follow-7') + + const showProgressInterstitial = + (followProgressGuide || followAndLikeProgressGuide) && !rightNavVisible + + const {trendingVideoDisabled} = useTrendingSettings() + + const ageAssuranceBannerState = useAgeAssuranceBannerState() + const selectedFeed = useSelectedFeed() + /** + * Cached value of whether the current feed was selected at startup. We don't + * want this to update when user swipes. + */ + // oxlint-disable-next-line react/hook-use-state + const [isCurrentFeedAtStartupSelected] = useState(selectedFeed === feed) + + const blockedOrMutedAuthors = usePostAuthorShadowFilter( + // author feeds have their own handling + feed.startsWith('author|') ? undefined : data?.pages, + ) + + const feedItems: FeedRow[] = useMemo(() => { + // wraps a slice item, and replaces it with a showLessFollowup item + // if the user has pressed show less on it + const sliceItem = (row: Extract) => { + if (hasPressedShowLessUris.has(row.slice.items[row.indexInSlice]?.uri)) { + return { + type: 'showLessFollowup', + key: row.key, + } as const + } else { + return row + } + } + + let feedKind: 'following' | 'discover' | 'profile' | 'thevids' | undefined + if (feedType === 'following') { + feedKind = 'following' + } else if (feedUriOrActorDid === DISCOVER_FEED_URI) { + feedKind = 'discover' + } else if ( + feedType === 'author' && + (feedTab === 'posts_and_author_threads' || + feedTab === 'posts_with_replies') + ) { + feedKind = 'profile' + } + + let arr: FeedRow[] = [] + if (KNOWN_SHUTDOWN_FEEDS.includes(feedUriOrActorDid)) { + arr.push({ + type: 'feedShutdownMsg', + key: 'feedShutdownMsg', + }) + } + if (isFetched) { + if (isError && isEmpty) { + arr.push({ + type: 'error', + key: 'error', + }) + } else if (isEmpty) { + arr.push({ + type: 'empty', + key: 'empty', + }) + } else if (data) { + let sliceIndex = -1 + + if (isVideoFeed) { + const videos: { + item: FeedPostSliceItem + feedContext: string | undefined + reqId: string | undefined + }[] = [] + for (const page of data.pages) { + for (const slice of page.slices) { + const item = slice.items.find( + item => item.uri === slice.feedPostUri, + ) + if ( + item && + bsky.isType(app.bsky.embed.video.view, item.post.embed) && + !blockedOrMutedAuthors.includes(item.post.author.did) + ) { + videos.push({ + item, + feedContext: slice.feedContext, + reqId: slice.reqId, + }) + } + } + } + + const rows: { + item: FeedPostSliceItem + feedContext: string | undefined + reqId: string | undefined + }[][] = [] + for (let i = 0; i < videos.length; i++) { + const video = videos[i] + const item = video.item + const cols = gtMobile ? 3 : 2 + const rowItem = { + item, + feedContext: video.feedContext, + reqId: video.reqId, + } + if (i % cols === 0) { + rows.push([rowItem]) + } else { + rows[rows.length - 1].push(rowItem) + } + } + + for (const row of rows) { + sliceIndex++ + arr.push({ + type: 'videoGridRow', + key: row.map(r => r.item._reactKey).join('-'), + items: row.map(r => r.item), + sourceFeedUri: feedUriOrActorDid, + feedContexts: row.map(r => r.feedContext), + reqIds: row.map(r => r.reqId), + }) + } + } else { + for (const page of data?.pages) { + for (const slice of page.slices) { + sliceIndex++ + + if (hasSession) { + if (feedKind === 'discover') { + if (sliceIndex === 0) { + if (showProgressInterstitial) { + arr.push({ + type: 'interstitialProgressGuide', + key: 'interstitial-' + sliceIndex + '-' + lastFetchedAt, + }) + } else { + /* + * Only insert if Discover was the last selected feed at + * startup, the progress guide isn't shown, and the + * banner is eligible to be shown. + */ + if ( + isCurrentFeedAtStartupSelected && + ageAssuranceBannerState.visible + ) { + arr.push({ + type: 'ageAssuranceBanner', + key: 'ageAssuranceBanner-' + sliceIndex, + }) + } + } + arr.push({ + type: 'liveEventFeedsAndTrendingBanner', + key: 'liveEventFeedsAndTrendingBanner-' + sliceIndex, + }) + // Show composer prompt for Discover and Following feeds + if ( + hasSession && + (feedUriOrActorDid === DISCOVER_FEED_URI || + feed === 'following') + ) { + arr.push({ + type: 'composerPrompt', + key: 'composerPrompt-' + sliceIndex, + }) + } + } else if (sliceIndex === trendingIndices.topics) { + arr.push({ + type: 'interstitialFeedTrendingTopics', + key: 'interstitialFeedTrendingTopics-' + sliceIndex, + feedSliceIndex: sliceIndex, + }) + } else if (sliceIndex === trendingIndices.videos) { + if (areVideoFeedsEnabled && !trendingVideoDisabled) { + arr.push({ + type: 'interstitialTrendingVideos', + key: 'interstitial-' + sliceIndex + '-' + lastFetchedAt, + }) + } + } else if (sliceIndex === trendingIndices.accounts) { + arr.push({ + type: 'interstitialFollows', + key: 'interstitial-' + sliceIndex + '-' + lastFetchedAt, + }) + } + } else if (feedKind === 'following') { + if (sliceIndex === 0) { + // Show composer prompt for Following feed + if (hasSession) { + arr.push({ + type: 'composerPrompt', + key: 'composerPrompt-' + sliceIndex, + }) + } + } + } else if (feedKind === 'profile') { + if (sliceIndex === 5) { + arr.push({ + type: 'interstitialFollows', + key: 'interstitial-' + sliceIndex + '-' + lastFetchedAt, + }) + } + } else { + /* + * Only insert if this feed was the last selected feed at + * startup and the banner is eligible to be shown. + */ + if (sliceIndex === 0 && isCurrentFeedAtStartupSelected) { + arr.push({ + type: 'ageAssuranceBanner', + key: 'ageAssuranceBanner-' + sliceIndex, + }) + } + } + } + + if (slice.isFallbackMarker) { + arr.push({ + type: 'fallbackMarker', + key: + 'sliceFallbackMarker-' + sliceIndex + '-' + lastFetchedAt, + }) + } else if ( + slice.items.some(item => + blockedOrMutedAuthors.includes(item.post.author.did), + ) + ) { + // skip + } else if (slice.isIncompleteThread && slice.items.length >= 3) { + const beforeLast = slice.items.length - 2 + const last = slice.items.length - 1 + arr.push( + sliceItem({ + type: 'sliceItem', + key: slice.items[0]._reactKey, + slice: slice, + indexInSlice: 0, + showReplyTo: false, + }), + ) + arr.push({ + type: 'sliceViewFullThread', + key: slice._reactKey + '-viewFullThread', + uri: slice.items[0].uri, + }) + arr.push( + sliceItem({ + type: 'sliceItem', + key: slice.items[beforeLast]._reactKey, + slice: slice, + indexInSlice: beforeLast, + showReplyTo: + slice.items[beforeLast].parentAuthor?.did !== + slice.items[beforeLast].post.author.did, + }), + ) + arr.push( + sliceItem({ + type: 'sliceItem', + key: slice.items[last]._reactKey, + slice: slice, + indexInSlice: last, + showReplyTo: false, + }), + ) + } else { + for (let i = 0; i < slice.items.length; i++) { + arr.push( + sliceItem({ + type: 'sliceItem', + key: slice.items[i]._reactKey, + slice: slice, + indexInSlice: i, + showReplyTo: i === 0, + }), + ) + } + } + } + } + } + } + if (isError && !isEmpty) { + arr.push({ + type: 'loadMoreError', + key: 'loadMoreError', + }) + } + } else { + if (isVideoFeed) { + arr.push({ + type: 'videoGridRowPlaceholder', + key: 'videoGridRowPlaceholder', + }) + } else { + arr.push({ + type: 'loading', + key: 'loading', + }) + } + } + + if (description?.text) { + arr.unshift({ + key: 'description', + type: 'description', + value: description, + }) + } + + return arr + }, [ + description, + isFetched, + isError, + isEmpty, + lastFetchedAt, + data, + feed, + feedType, + feedUriOrActorDid, + feedTab, + hasSession, + showProgressInterstitial, + trendingVideoDisabled, + gtMobile, + isVideoFeed, + areVideoFeedsEnabled, + hasPressedShowLessUris, + ageAssuranceBannerState, + isCurrentFeedAtStartupSelected, + blockedOrMutedAuthors, + trendingIndices, + ]) + + // events + // = + // + + const refreshFeed = async () => { + if (!enabled) return + + ax.metric('feed:refresh', { + feedType: feedType, + feedUrl: feed, + reason: 'pull-to-refresh', + }) + try { + await truncateAndInvalidate(queryClient, RQKEY(feed, feedParams)) + if (onHasNew) { + onHasNew(false) + } + } catch (err) { + logger.error('Failed to refresh posts feed', {message: err}) + } + } + + const onRefresh = async () => { + setIsPTRing(true) + await refreshFeed() + setIsPTRing(false) + } + + useImperativeHandle(ref, () => ({ + refreshFeed, + })) + + const onEndReached = useCallback(async () => { + if (isFetching || !hasNextPage || isError) return + + ax.metric('feed:endReached', { + feedType: feedType, + feedUrl: feed, + itemCount: feedItems.length, + }) + try { + await fetchNextPage() + } catch (err) { + logger.error('Failed to load more posts', {message: err}) + } + }, [ + ax, + isFetching, + hasNextPage, + isError, + fetchNextPage, + feed, + feedType, + feedItems.length, + ]) + + const onPressTryAgain = useCallback(() => { + void refetch() + onHasNew?.(false) + }, [refetch, onHasNew]) + + const onPressRetryLoadMore = useCallback(() => { + void fetchNextPage() + }, [fetchNextPage]) + + // rendering + // = + + const renderItem = useCallback( + ({item: row, index: rowIndex}: ListRenderItemInfo) => { + if (row.type === 'empty') { + return renderEmptyState() + } else if (row.type === 'error') { + return ( + + ) + } else if (row.type === 'loadMoreError') { + return ( + + ) + } else if (row.type === 'loading') { + return + } else if (row.type === 'feedShutdownMsg') { + return + } else if (row.type === 'description') { + return ( + + ) + } else if (row.type === 'interstitialFollows') { + return + } else if (row.type === 'interstitialProgressGuide') { + return + } else if (row.type === 'ageAssuranceBanner') { + return + } else if (row.type === 'interstitialFeedTrendingTopics') { + return ( + + ) + } else if (row.type === 'liveEventFeedsAndTrendingBanner') { + return + } else if (row.type === 'composerPrompt') { + return + } else if (row.type === 'interstitialTrendingVideos') { + return + } else if (row.type === 'fallbackMarker') { + // HACK + // tell the user we fell back to discover + // see home.ts (feed api) for more info + // -prf + return + } else if (row.type === 'sliceItem') { + const slice = row.slice + const indexInSlice = row.indexInSlice + const item = slice.items[indexInSlice] + return ( + + ) + } else if (row.type === 'sliceViewFullThread') { + return + } else if (row.type === 'videoGridRowPlaceholder') { + return ( + + + + + + ) + } else if (row.type === 'videoGridRow') { + let sourceContext: VideoFeedSourceContext + if (feedType === 'author') { + sourceContext = { + type: 'author', + did: feedUriOrActorDid, + filter: feedTab as AuthorFilter, + } + } else { + sourceContext = { + type: 'feedgen', + uri: row.sourceFeedUri, + sourceInterstitial: feedCacheKey ?? 'none', + followingV2: true, + } + } + + return ( + + ) + } else if (row.type === 'showLessFollowup') { + return + } else { + return null + } + }, + [ + renderEmptyState, + feed, + error, + onPressTryAgain, + savedFeedConfig, + l, + onPressRetryLoadMore, + feedType, + feedUriOrActorDid, + feedTab, + feedCacheKey, + onPressShowLess, + t, + ], + ) + + const shouldRenderEndOfFeed = + !hasNextPage && !isEmpty && !isFetching && !isError && !!renderEndOfFeed + const bottomBarOffset = useBottomBarOffset() + const FeedFooter = useCallback(() => { + /* + * A bit of padding at the bottom of the feed as you scroll and when you + * reach the end, so that content isn't cut off by the bottom of the + * screen. On mobile web, also clear the fixed bottom bar; on native the + * doubled headerOffset already covers the tab bar. + */ + const offset = + Math.max(headerOffset, 32) * (IS_WEB ? 1 : 2) + + (IS_WEB ? bottomBarOffset : 0) + + return isFetchingNextPage ? ( + + + + + ) : shouldRenderEndOfFeed ? ( + {renderEndOfFeed()} + ) : ( + + ) + }, [ + isFetchingNextPage, + shouldRenderEndOfFeed, + renderEndOfFeed, + headerOffset, + bottomBarOffset, + ]) + + const liveNowConfig = useLiveNowConfig() + + const seenActorWithStatusRef = useRef>(new Set()) + const seenPostUrisRef = useRef>(new Set()) + // Tracks every post we've seen so we can fire per-post events exactly once, + // regardless of the post's position within its slice. + const seenPerPostUrisRef = useRef>(new Set()) + + // Helper to calculate position in feed (count only root posts, not interstitials or thread replies) + const getPostPosition = useNonReactiveCallback( + (type: FeedRow['type'], key: string) => { + // Calculate position: find the row index in feedItems, then calculate position + const rowIndex = feedItems.findIndex( + row => row.type === 'sliceItem' && row.key === key, + ) + + if (rowIndex >= 0) { + let position = 0 + for (let i = 0; i < rowIndex && i < feedItems.length; i++) { + const row = feedItems[i] + if (row.type === 'sliceItem') { + // Only count root posts (indexInSlice === 0), not thread replies + if (row.indexInSlice === 0) { + position++ + } + } else if (row.type === 'videoGridRow') { + // Count each video in the grid row + position += row.items.length + } + } + return position + } + }, + ) + + const onItemSeen = useCallback( + (item: FeedRow) => { + feedFeedback.onItemSeen(item) + + // Events that should fire exactly once for every new post, regardless of + // its position within a slice or video grid row. + const onPostSeen = (post: app.bsky.feed.defs.PostView) => { + if (seenPerPostUrisRef.current.has(post.uri)) return + seenPerPostUrisRef.current.add(post.uri) + + // Standard site embed view tracking + if ( + bsky.isType(app.bsky.embed.external.view, post.embed) && + isStandardSiteEmbed(post.embed.external) + ) { + ax.metric('embed:standardSite:view', {url: post.embed.external.uri}) + } + + // Photo embed impression tracking + if ( + bsky.isType(app.bsky.embed.images.view, post.embed) || + bsky.isType(app.bsky.embed.gallery.view, post.embed) + ) { + const totalImages = bsky.isType( + app.bsky.embed.gallery.view, + post.embed, + ) + ? post.embed.items.filter(item => + bsky.isType(app.bsky.embed.gallery.viewImage, item), + ).length + : post.embed.images.length + const useExpandedLayout = bsky.isType( + app.bsky.embed.gallery.view, + post.embed, + ) + ? totalImages > 4 + : ax.features.enabled(ax.features.PostGalleryEmbedEnable) + const layout = + totalImages === 1 + ? 'single' + : useExpandedLayout + ? 'carousel' + : 'grid' + + ax.metric('post:photoEmbed:impression', { + layout, + totalImages, + postUri: post.uri, + postAuthorDid: post.author.did, + feedDescriptor: feedFeedback.feedDescriptor || feed, + }) + } + } + + // Track post:view events + if (item.type === 'sliceItem') { + const slice = item.slice + const indexInSlice = item.indexInSlice + const postItem = slice.items[indexInSlice] + const post = postItem.post + + onPostSeen(post) + + // Track the post selected by the feed once it is actually visible. + if ( + post.uri === slice.feedPostUri && + !seenPostUrisRef.current.has(post.uri) + ) { + seenPostUrisRef.current.add(post.uri) + + const position = getPostPosition( + 'sliceItem', + slice.items[0]._reactKey, + ) + + ax.metric('post:view', { + uri: post.uri, + authorDid: post.author.did, + isReply: !!postItem.record.reply, + logContext: 'FeedItem', + feedDescriptor: feedFeedback.feedDescriptor || feed, + position, + }) + } + + // Live status tracking (existing code) + const actor = post.author + if ( + actor.status && + isStatusValidForViewers(actor.status, liveNowConfig) && + isStatusStillActive(actor.status.expiresAt) + ) { + if (!seenActorWithStatusRef.current.has(actor.did)) { + seenActorWithStatusRef.current.add(actor.did) + ax.metric('live:view:post', { + subject: actor.did, + feed, + }) + } + } + } else if (item.type === 'videoGridRow') { + // Track each video in the grid row + for (let i = 0; i < item.items.length; i++) { + const postItem = item.items[i] + const post = postItem.post + + if (!seenPostUrisRef.current.has(post.uri)) { + seenPostUrisRef.current.add(post.uri) + + const position = getPostPosition('videoGridRow', item.key) + + ax.metric('post:view', { + uri: post.uri, + authorDid: post.author.did, + isReply: !!postItem.record.reply, + logContext: 'FeedItem', + feedDescriptor: feedFeedback.feedDescriptor || feed, + position, + }) + } + } + } + }, + [feedFeedback, feed, liveNowConfig, getPostPosition, ax], + ) + + return ( + + item.key} + renderItem={renderItem} + ListFooterComponent={FeedFooter} + ListHeaderComponent={ListHeaderComponent} + refreshing={isPTRing} + onRefresh={() => void onRefresh()} + headerOffset={headerOffset} + progressViewOffset={progressViewOffset} + contentContainerStyle={{ + minHeight: Dimensions.get('window').height * 1.5, + }} + onScrolledDownChange={handleScrolledDownChange} + onEndReached={() => void onEndReached()} + onEndReachedThreshold={2} // number of posts left to trigger load more + removeClippedSubviews={true} + extraData={extraData} + desktopFixedHeight={ + desktopFixedHeightOffset ? desktopFixedHeightOffset : true + } + initialNumToRender={initialNumToRenderOverride ?? initialNumToRender} + windowSize={9} + maxToRenderPerBatch={IS_IOS ? 5 : 1} + updateCellsBatchingPeriod={40} + onItemSeen={onItemSeen} + /> + + ) +} +PostFeed = memo(PostFeed) +export {PostFeed} + +const styles = StyleSheet.create({ + feedFooter: {paddingTop: 20}, +}) + +export function isThreadParentAt(arr: Array, i: number) { + if (arr.length === 1) { + return false + } + return i < arr.length - 1 +} + +export function isThreadChildAt(arr: Array, i: number) { + if (arr.length === 1) { + return false + } + return i > 0 +} diff --git a/src/features/followingV2/home/api/custom.ts b/src/features/followingV2/home/api/custom.ts new file mode 100644 index 000000000..f0b2594cd --- /dev/null +++ b/src/features/followingV2/home/api/custom.ts @@ -0,0 +1,190 @@ +import { + type Client, + type XrpcRequestParams, + XrpcResponseError, +} from '@atproto/lex' + +import {createBskyTopicsHeader, isBlueskyOwnedFeed} from '#/lib/api/feed/utils' +import {PUBLIC_APPVIEW} from '#/lib/constants' +import {createLexClient} from '#/lib/lexClient' +import { + getAppLanguageAsContentLanguage, + getContentLanguages, +} from '#/state/preferences/languages' +import {app} from '#/lexicons' +import {type FeedAPI, type FeedAPIResponse} from './types' + +type GetCustomFeedParams = XrpcRequestParams + +export class CustomFeedAPI implements FeedAPI { + client: Client + params: GetCustomFeedParams + userInterests?: string + + constructor({ + client, + feedParams, + userInterests, + }: { + client: Client + feedParams: GetCustomFeedParams + userInterests?: string + }) { + this.client = client + this.params = feedParams + this.userInterests = userInterests + } + + async peekLatest(): Promise { + const contentLangs = getContentLanguages().join(',') + const data = await this.client.call( + app.bsky.feed.getFeed, + { + ...this.params, + limit: 1, + }, + {headers: {'Accept-Language': contentLangs}}, + ) + return data.feed[0] + } + + async fetch({ + cursor, + limit, + signal, + }: { + cursor: string | undefined + limit: number + signal?: AbortSignal + }): Promise { + const contentLangs = getContentLanguages().join(',') + const isBlueskyOwned = isBlueskyOwnedFeed(this.params.feed) + + /* + * The authed branch rejects on failure, so the error propagates to the + * query and drives the feed error UI (feedgen offline, misconfigured, rate + * limited). Only the logged-out branch can resolve without data, and it + * signals that with a null body. + */ + const data = this.client.did + ? await this.client.call( + app.bsky.feed.getFeed, + { + ...this.params, + cursor, + limit, + }, + { + signal, + headers: { + ...(isBlueskyOwned + ? createBskyTopicsHeader(this.userInterests) + : {}), + 'Accept-Language': contentLangs, + }, + }, + ) + : await loggedOutFetch({...this.params, cursor, limit}, signal) + + if (!data) { + return { + feed: [], + } + } + + // NOTE + // some custom feeds fail to enforce the pagination limit + // so we manually truncate here + // -prf + const feed = + data.feed.length > limit ? data.feed.slice(0, limit) : data.feed + return { + cursor: data.cursor, + feed, + } + } +} + +let loggedOutAppviewClient: Client | undefined + +/** + * The unauthenticated {@link Client} for logged-out feed reads, pointed at the + * direct appview ({@link PUBLIC_APPVIEW}, `api.bsky.app`). + * + * Deliberately NOT the public appview client (`public.api.bsky.app`): that host + * fronts a cache which does not vary on `Accept-Language`, so it would answer a + * language-filtered read from another language's cached body. The direct + * appview respects the header (verified 2026-08-04), at the cost of not being + * cached. See {@link loggedOutFetch}. + * + * A single module-level instance, because there is no session to scope it to. + * Like the public chat client, it uses plain `fetch` rather than + * `networkAwareFetch`, matching the ad-hoc fetch it replaces: this read has its + * own failure handling and should not move the app-wide network signal. + */ +function getLoggedOutAppviewClient(): Client { + return (loggedOutAppviewClient ??= createLexClient( + {service: PUBLIC_APPVIEW}, + {includeDeviceSessionHeaders: false}, + )) +} + +/* + * HACK + * We want feeds to give language-specific results immediately when a logged-out + * user changes their language. That comes with two problems: + * 1. not all languages have content, and + * 2. our public caching layer does not bust against the `Accept-Language` + * header. + * -prf + * + * Problem 2 is why this uses its own client rather than the app's public + * appview one: it talks to the direct appview, which honors the header, instead + * of the cached `public.api.bsky.app`, which does not vary on it. That trades + * CDN caching for language correctness on logged-out feed traffic. + * + * Problem 1 is host-independent, so it is still handled here: an empty + * language-filtered feed is retried once with the language constraint removed. + */ +async function loggedOutFetch( + params: GetCustomFeedParams, + signal?: AbortSignal, +): Promise { + const contentLangs = getAppLanguageAsContentLanguage() + + 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, '', signal) + return data +} + +/** + * A logged-out `getFeed` read that resolves to null on a response error. + * + * The pre-client code only guarded `res.ok`, so a failed RESPONSE fell through + * to the next attempt while a failed REQUEST rejected. Catching + * `XrpcResponseError` preserves that split: every other lex error - the fetch + * and validation ones - still propagates. + */ +async function getFeedOrNull( + params: GetCustomFeedParams, + contentLangs: string, + signal?: AbortSignal, +): Promise { + try { + return await getLoggedOutAppviewClient().call( + app.bsky.feed.getFeed, + params, + {signal, headers: {'Accept-Language': contentLangs}}, + ) + } catch (e) { + if (e instanceof XrpcResponseError) { + return null + } + throw e + } +} diff --git a/src/features/followingV2/home/api/following.ts b/src/features/followingV2/home/api/following.ts new file mode 100644 index 000000000..27a08c698 --- /dev/null +++ b/src/features/followingV2/home/api/following.ts @@ -0,0 +1,42 @@ +import {type Client} from '@atproto/lex' + +import {app} from '#/lexicons' +import {type FeedAPI, type FeedAPIResponse} from './types' + +export class FollowingFeedAPI implements FeedAPI { + client: Client + + constructor({client}: {client: Client}) { + this.client = client + } + + async peekLatest(): Promise { + const data = await this.client.call(app.bsky.feed.getTimeline, { + limit: 1, + }) + return data.feed[0] + } + + async fetch({ + cursor, + limit, + }: { + cursor: string | undefined + limit: number + }): Promise { + /* + * A failed request rejects rather than resolving, so the error propagates + * to the query and drives the feed error UI. The agent behaved the same + * way - its `success` flag was only ever true - so the empty-page branch + * this replaces was unreachable. + */ + const data = await this.client.call(app.bsky.feed.getTimeline, { + cursor, + limit, + }) + return { + cursor: data.cursor, + feed: data.feed, + } + } +} diff --git a/src/features/followingV2/home/api/home.ts b/src/features/followingV2/home/api/home.ts new file mode 100644 index 000000000..9c90b213a --- /dev/null +++ b/src/features/followingV2/home/api/home.ts @@ -0,0 +1,114 @@ +import {type Client} from '@atproto/lex' +import {type AtUriString} from '@atproto/syntax' + +import {PROD_DEFAULT_FEED} from '#/lib/constants' +import {type app} from '#/lexicons' +import {CustomFeedAPI} from './custom' +import {FollowingFeedAPI} from './following' +import {type FeedAPI, type FeedAPIResponse} from './types' + +// HACK +// the feed API does not include any facilities for passing down +// non-post elements. adding that is a bit of a heavy lift, and we +// have just one temporary usecase for it: flagging when the home feed +// falls back to discover. +// we use this fallback marker post to drive this instead. see Feed.tsx +// for the usage. +// -prf +/* + * A synthetic marker, not a real view: its `uri`/`did`/`indexedAt` are + * deliberately not well-formed, so the literal is asserted rather than branded. + * Only `post.uri` is ever read (see Feed.tsx). + */ +export const FALLBACK_MARKER_POST = { + post: { + uri: 'fallback-marker-post', + cid: 'fake', + record: {}, + author: { + did: 'did:fake', + handle: 'fake.com', + }, + indexedAt: new Date().toISOString(), + }, +} as unknown as app.bsky.feed.defs.FeedViewPost + +export class HomeFeedAPI implements FeedAPI { + client: Client + following: FollowingFeedAPI + discover: CustomFeedAPI + usingDiscover = false + itemCursor = 0 + userInterests?: string + + constructor({ + userInterests, + client, + }: { + userInterests?: string + client: Client + }) { + this.client = client + this.following = new FollowingFeedAPI({client}) + this.discover = new CustomFeedAPI({ + client, + feedParams: {feed: PROD_DEFAULT_FEED('whats-hot') as AtUriString}, + }) + this.userInterests = userInterests + } + + reset() { + this.following = new FollowingFeedAPI({client: this.client}) + this.discover = new CustomFeedAPI({ + client: this.client, + feedParams: {feed: PROD_DEFAULT_FEED('whats-hot') as AtUriString}, + userInterests: this.userInterests, + }) + this.usingDiscover = false + this.itemCursor = 0 + } + + async peekLatest(): Promise { + if (this.usingDiscover) { + return this.discover.peekLatest() + } + return this.following.peekLatest() + } + + async fetch({ + cursor, + limit, + }: { + cursor: string | undefined + limit: number + }): Promise { + if (!cursor) { + this.reset() + } + + let returnCursor + let posts: app.bsky.feed.defs.FeedViewPost[] = [] + + if (!this.usingDiscover) { + const res = await this.following.fetch({cursor, limit}) + returnCursor = res.cursor + posts = posts.concat(res.feed) + if (!returnCursor) { + cursor = '' + posts.push(FALLBACK_MARKER_POST) + this.usingDiscover = true + } + } + + if (this.usingDiscover && !__DEV__) { + const res = await this.discover.fetch({cursor, limit}) + returnCursor = res.cursor + posts = posts.concat(res.feed) + } + + return { + cursor: returnCursor, + feed: posts, + } + } +} diff --git a/src/features/followingV2/home/api/list.ts b/src/features/followingV2/home/api/list.ts new file mode 100644 index 000000000..51e67bb4e --- /dev/null +++ b/src/features/followingV2/home/api/list.ts @@ -0,0 +1,56 @@ +import {type Client, type XrpcRequestParams} from '@atproto/lex' + +import {app} from '#/lexicons' +import {type FeedAPI, type FeedAPIResponse} from './types' + +type GetListFeedParams = XrpcRequestParams< + typeof app.bsky.feed.getListFeed.main +> + +export class ListFeedAPI implements FeedAPI { + client: Client + params: GetListFeedParams + + constructor({ + client, + feedParams, + }: { + client: Client + feedParams: GetListFeedParams + }) { + this.client = client + this.params = feedParams + } + + async peekLatest(): Promise { + const data = await this.client.call(app.bsky.feed.getListFeed, { + ...this.params, + limit: 1, + }) + return data.feed[0] + } + + async fetch({ + cursor, + limit, + }: { + cursor: string | undefined + limit: number + }): Promise { + /* + * A failed request rejects rather than resolving, so the error propagates + * to the query and drives the feed error UI. The agent behaved the same + * way - its `success` flag was only ever true - so the empty-page branch + * this replaces was unreachable. + */ + const data = await this.client.call(app.bsky.feed.getListFeed, { + ...this.params, + cursor, + limit, + }) + return { + cursor: data.cursor, + feed: data.feed, + } + } +} diff --git a/src/features/followingV2/home/api/merge.ts b/src/features/followingV2/home/api/merge.ts new file mode 100644 index 000000000..3d151b37d --- /dev/null +++ b/src/features/followingV2/home/api/merge.ts @@ -0,0 +1,359 @@ +import {type Client} from '@atproto/lex' +import {type AtUriString} from '@atproto/syntax' +import shuffle from 'lodash.shuffle' + +import {createBskyTopicsHeader, isBlueskyOwnedFeed} from '#/lib/api/feed/utils' +import {FeedTuner} from '#/lib/api/feed-manip' +import {type FeedTunerFn} from '#/lib/api/feed-manip' +import {bundleAsync} from '#/lib/async/bundle' +import {timeout} from '#/lib/async/timeout' +import {feedUriToHref} from '#/lib/strings/url-helpers' +import {getContentLanguages} from '#/state/preferences/languages' +import {type FeedParams} from '#/features/followingV2/home/queries/postFeed' +import {app} from '#/lexicons' +import { + type FeedAPI, + type FeedAPIResponse, + type ReasonFeedSource, +} from './types' + +const REQUEST_WAIT_MS = 500 // 500ms +const POST_AGE_CUTOFF = 60e3 * 60 * 24 // 24hours + +/** + * A page of feed items, or `null` when the source could not produce one. Only + * sources that deliberately swallow their own errors return `null`; the rest + * reject so the error reaches the caller. + */ +type MergeFeedPage = { + cursor?: string + feed: app.bsky.feed.defs.FeedViewPost[] +} | null + +export class MergeFeedAPI implements FeedAPI { + userInterests?: string + client: Client + params: FeedParams + feedTuners: FeedTunerFn[] + following: MergeFeedSource_Following + customFeeds: MergeFeedSource_Custom[] = [] + feedCursor = 0 + itemCursor = 0 + sampleCursor = 0 + + constructor({ + client, + feedParams, + feedTuners, + userInterests, + }: { + client: Client + feedParams: FeedParams + feedTuners: FeedTunerFn[] + userInterests?: string + }) { + this.client = client + this.params = feedParams + this.feedTuners = feedTuners + this.userInterests = userInterests + this.following = new MergeFeedSource_Following({ + client: this.client, + feedTuners: this.feedTuners, + }) + } + + reset() { + this.following = new MergeFeedSource_Following({ + client: this.client, + feedTuners: this.feedTuners, + }) + this.customFeeds = [] + this.feedCursor = 0 + this.itemCursor = 0 + this.sampleCursor = 0 + if (this.params.mergeFeedSources) { + this.customFeeds = shuffle( + this.params.mergeFeedSources.map( + feedUri => + new MergeFeedSource_Custom({ + client: this.client, + feedUri, + feedTuners: this.feedTuners, + userInterests: this.userInterests, + }), + ), + ) + } else { + this.customFeeds = [] + } + } + + async peekLatest(): Promise { + const data = await this.client.call(app.bsky.feed.getTimeline, { + limit: 1, + }) + return data.feed[0] + } + + async fetch({ + cursor, + limit, + }: { + cursor: string | undefined + limit: number + }): Promise { + if (!cursor) { + this.reset() + } + + const promises = [] + + // always keep following topped up while the source has another page + if (this.following.hasMore && this.following.numReady < limit) { + await this.following.fetchNext(60) + } + + // pick the next feeds to sample from + const feeds = this.customFeeds.slice(this.feedCursor, this.feedCursor + 3) + this.feedCursor += 3 + if (this.feedCursor > this.customFeeds.length) { + this.feedCursor = 0 + } + + // top up the feeds + const outOfFollows = + !this.following.hasMore && this.following.numReady < limit + if (this.params.mergeFeedEnabled || outOfFollows) { + for (const feed of feeds) { + if (feed.hasMore && feed.numReady < 5) { + promises.push(feed.fetchNext(10)) + } + } + } + + // wait for requests (all capped at a fixed timeout) + await Promise.all(promises) + + // assemble a response by sampling from feeds with content + const posts: app.bsky.feed.defs.FeedViewPost[] = [] + while (posts.length < limit) { + let slice = this.sampleItem() + if (slice[0]) { + posts.push(slice[0]) + } else { + break + } + } + + const hasMore = + this.following.hasMore || + this.following.numReady > 0 || + this.customFeeds.some(feed => feed.hasMore || feed.numReady > 0) + return { + cursor: hasMore ? String(this.itemCursor) : undefined, + feed: posts, + } + } + + sampleItem() { + const i = this.itemCursor++ + const candidateFeeds = this.customFeeds.filter(f => f.numReady > 0) + const canSample = candidateFeeds.length > 0 + const hasFollowsReady = this.following.numReady > 0 + const hasFollows = this.following.hasMore || hasFollowsReady + + // this condition establishes the frequency that custom feeds are woven into follows + const shouldSample = + this.params.mergeFeedEnabled && + i >= 15 && + candidateFeeds.length >= 2 && + (i % 4 === 0 || i % 5 === 0) + + if (!canSample && !hasFollows) { + // no data available + return [] + } + if (shouldSample || !hasFollows) { + // time to sample, or the user isnt following anybody + return candidateFeeds[this.sampleCursor++ % candidateFeeds.length].take(1) + } + if (!hasFollowsReady) { + // stop here so more follows can be fetched + return [] + } + // provide follow + return this.following.take(1) + } +} + +class MergeFeedSource { + client: Client + feedTuners: FeedTunerFn[] + sourceInfo: ReasonFeedSource | undefined + cursor: string | undefined = undefined + seenCursors = new Set() + queue: app.bsky.feed.defs.FeedViewPost[] = [] + hasMore = true + + constructor({ + client, + feedTuners, + }: { + client: Client + feedTuners: FeedTunerFn[] + }) { + this.client = client + this.feedTuners = feedTuners + } + + get numReady() { + return this.queue.length + } + + get needsFetch() { + return this.hasMore && this.queue.length === 0 + } + + take(n: number): app.bsky.feed.defs.FeedViewPost[] { + return this.queue.splice(0, n) + } + + async fetchNext(n: number) { + await Promise.race([this._fetchNextInner(n), timeout(REQUEST_WAIT_MS)]) + } + + _fetchNextInner = bundleAsync(async (n: number) => { + const page = await this._getFeed(this.cursor, n) + if (page) { + this.cursor = page.cursor + const cursor = this.cursor + if (cursor) { + this.hasMore = !this.seenCursors.has(cursor) + this.seenCursors.add(cursor) + } else { + this.hasMore = false + } + if (page.feed.length) { + this.queue = this.queue.concat(page.feed) + } + } else { + this.hasMore = false + } + }) + + protected _getFeed( + _cursor: string | undefined, + _limit: number, + ): Promise { + throw new Error('Must be overridden') + } +} + +class MergeFeedSource_Following extends MergeFeedSource { + tuner = new FeedTuner(this.feedTuners) + + async fetchNext(n: number) { + return this._fetchNextInner(n) + } + + /* + * No error handling: a failed timeline read rejects, which is what the agent + * did too, so the error still reaches `MergeFeedAPI.fetch` and the query. + */ + protected async _getFeed( + cursor: string | undefined, + limit: number, + ): Promise { + const data = await this.client.call(app.bsky.feed.getTimeline, { + cursor, + limit, + }) + // run the tuner pre-emptively to ensure better mixing + const slices = this.tuner.tune(data.feed, { + dryRun: false, + }) + return { + cursor: data.cursor, + feed: slices.map(slice => slice._feedPost), + } + } +} + +class MergeFeedSource_Custom extends MergeFeedSource { + minDate: Date + feedUri: string + userInterests?: string + + constructor({ + client, + feedUri, + feedTuners, + userInterests, + }: { + client: Client + feedUri: string + feedTuners: FeedTunerFn[] + userInterests?: string + }) { + super({ + client, + feedTuners, + }) + this.feedUri = feedUri + this.userInterests = userInterests + this.sourceInfo = { + $type: 'reasonFeedSource', + uri: feedUri, + href: feedUriToHref(feedUri), + } + this.minDate = new Date(Date.now() - POST_AGE_CUTOFF) + } + + protected async _getFeed( + cursor: string | undefined, + limit: number, + ): Promise { + try { + const contentLangs = getContentLanguages().join(',') + const isBlueskyOwned = isBlueskyOwnedFeed(this.feedUri) + const data = await this.client.call( + app.bsky.feed.getFeed, + { + cursor, + limit, + feed: this.feedUri as AtUriString, + }, + { + headers: { + ...(isBlueskyOwned + ? createBskyTopicsHeader(this.userInterests) + : {}), + 'Accept-Language': contentLangs, + }, + }, + ) + // NOTE + // some custom feeds fail to enforce the pagination limit + // so we manually truncate here + // -prf + let feed: app.bsky.feed.defs.FeedViewPost[] = + limit && data.feed.length > limit + ? data.feed.slice(0, limit) + : data.feed + // filter out older posts + feed = feed.filter(post => new Date(post.post.indexedAt) > this.minDate) + // attach source info + for (const post of feed) { + // @ts-expect-error + post.__source = this.sourceInfo + } + return { + cursor: data.cursor, + feed, + } + } catch { + // dont bubble custom-feed errors + return null + } + } +} diff --git a/src/features/followingV2/home/api/types.ts b/src/features/followingV2/home/api/types.ts new file mode 100644 index 000000000..c1cdce2fe --- /dev/null +++ b/src/features/followingV2/home/api/types.ts @@ -0,0 +1,34 @@ +import {type app} from '#/lexicons' + +export interface FeedAPIResponse { + cursor?: string + feed: app.bsky.feed.defs.FeedViewPost[] +} + +export interface FeedAPI { + peekLatest(): Promise + fetch({ + cursor, + limit, + signal, + }: { + cursor: string | undefined + limit: number + signal?: AbortSignal + }): Promise +} + +export interface ReasonFeedSource { + $type: 'reasonFeedSource' + uri: string + href: string +} + +export function isReasonFeedSource(v: unknown): v is ReasonFeedSource { + return ( + !!v && + typeof v === 'object' && + '$type' in v && + v.$type === 'reasonFeedSource' + ) +} diff --git a/src/features/followingV2/home/index.test.tsx b/src/features/followingV2/home/index.test.tsx new file mode 100644 index 000000000..8d6053854 --- /dev/null +++ b/src/features/followingV2/home/index.test.tsx @@ -0,0 +1,67 @@ +import {render, screen} from '@testing-library/react-native' + +import {HomeScreen} from '.' + +const mockEnabled = jest.fn() +let mockIsNative = true + +jest.mock('#/env', () => ({ + get IS_NATIVE() { + return mockIsNative + }, + get IS_WEB() { + return !mockIsNative + }, +})) + +jest.mock('#/analytics', () => ({ + useAnalytics: () => ({ + features: { + enabled: mockEnabled, + FollowingV2Enable: 'following_v2:enable', + }, + }), +})) + +jest.mock('#/view/screens/Home', () => { + const {Text} = + jest.requireActual('react-native') + return {HomeScreen: () => legacy home} +}) + +jest.mock('./Home', () => { + const {Text} = + jest.requireActual('react-native') + return {HomeScreen: () => following v2 home} +}) + +const props = {} as React.ComponentProps + +describe.each([ + {platform: 'native', isNative: true}, + {platform: 'web', isNative: false}, +])('HomeScreen on $platform', ({isNative}) => { + beforeEach(() => { + mockEnabled.mockReset() + mockIsNative = isNative + }) + + it('renders the fork when following v2 is enabled', () => { + mockEnabled.mockReturnValue(true) + + render() + + expect(mockEnabled).toHaveBeenCalledWith('following_v2:enable') + expect(screen.getByText('following v2 home')).toBeTruthy() + expect(screen.queryByText('legacy home')).toBeNull() + }) + + it('renders the legacy home when following v2 is disabled', () => { + mockEnabled.mockReturnValue(false) + + render() + + expect(screen.getByText('legacy home')).toBeTruthy() + expect(screen.queryByText('following v2 home')).toBeNull() + }) +}) diff --git a/src/features/followingV2/home/index.tsx b/src/features/followingV2/home/index.tsx new file mode 100644 index 000000000..6ff40a121 --- /dev/null +++ b/src/features/followingV2/home/index.tsx @@ -0,0 +1,24 @@ +import { + type HomeTabNavigatorParams, + type NativeStackScreenProps, +} from '#/lib/routes/types' +import {HomeScreen as LegacyHomeScreen} from '#/view/screens/Home' +import {useAnalytics} from '#/analytics' +import {isFollowingV2HomeForkEnabled} from '#/features/followingV2/eligibility' +import {HomeScreen as FollowingV2HomeScreen} from './Home' + +/** + * The Home route. With `following_v2:enable` on, it renders the fork of Home in + * this directory, which is where Following v2 changes land, on every platform. + * Otherwise it renders today's Home, unchanged. + */ +export function HomeScreen( + props: NativeStackScreenProps, +) { + const ax = useAnalytics() + return isFollowingV2HomeForkEnabled(ax) ? ( + + ) : ( + + ) +} diff --git a/src/features/followingV2/home/queries/postFeed.test.tsx b/src/features/followingV2/home/queries/postFeed.test.tsx new file mode 100644 index 000000000..c7ef25cdf --- /dev/null +++ b/src/features/followingV2/home/queries/postFeed.test.tsx @@ -0,0 +1,100 @@ +import {type InfiniteData, QueryClient} from '@tanstack/react-query' + +import { + findAllPostsInQueryData, + resetProfilePostsQueries, + RQKEY as LEGACY_RQKEY, + RQKEY_ROOT, +} from '#/state/queries/post-feed' +import {type app} from '#/lexicons' +import {type FeedDescriptor, RQKEY} from './postFeed' + +jest.mock('#/state/preferences/feed-tuners', () => ({})) +jest.mock('#/state/preferences/moderation-opts', () => ({})) +jest.mock('#/state/queries/preferences', () => ({})) +jest.mock('#/state/session', () => ({})) +jest.mock('#/view/com/posts/PostFeedErrorMessage', () => ({})) + +const AUTHOR = 'did:plc:author' +const POST_URI = `at://${AUTHOR}/app.bsky.feed.post/1` +const CUSTOM: FeedDescriptor = `feedgen|at://${AUTHOR}/app.bsky.feed.generator/custom` + +function feedData(): InfiniteData<{feed: app.bsky.feed.defs.FeedViewPost[]}> { + return { + pageParams: [undefined], + pages: [ + { + feed: [ + { + post: { + uri: POST_URI, + author: {did: AUTHOR, handle: 'author.test'}, + }, + } as unknown as app.bsky.feed.defs.FeedViewPost, + ], + }, + ], + } +} + +function isInvalidated(queryClient: QueryClient) { + return queryClient.getQueryCache().getAll()[0].state.isInvalidated +} + +describe('RQKEY', () => { + afterEach(() => { + jest.useRealTimers() + }) + + it('never shares an entry with the legacy key', () => { + const queryClient = new QueryClient() + queryClient.setQueryData(LEGACY_RQKEY(CUSTOM), feedData()) + + expect(queryClient.getQueryData(RQKEY(CUSTOM))).toBeUndefined() + }) + + it('is walked by the legacy cache-wide helpers', () => { + const queryClient = new QueryClient() + queryClient.setQueryData(RQKEY('following'), feedData()) + + expect([...findAllPostsInQueryData(queryClient, POST_URI)]).toHaveLength(1) + }) + + it('is reached by root invalidation', async () => { + const queryClient = new QueryClient() + queryClient.setQueryData(RQKEY('following'), feedData()) + + await queryClient.invalidateQueries({queryKey: [RQKEY_ROOT]}) + + expect(isInvalidated(queryClient)).toBe(true) + }) + + it('is reset when its feed matches a profile reset', () => { + jest.useFakeTimers() + const queryClient = new QueryClient() + queryClient.setQueryData(RQKEY(CUSTOM), feedData()) + + resetProfilePostsQueries(queryClient, AUTHOR) + jest.runAllTimers() + + expect(queryClient.getQueryData(RQKEY(CUSTOM))).toBeUndefined() + }) + + it('is not reached by legacy single-feed filters', async () => { + const queryClient = new QueryClient() + queryClient.setQueryData(RQKEY(CUSTOM), feedData()) + + await queryClient.invalidateQueries({queryKey: LEGACY_RQKEY(CUSTOM)}) + + expect(isInvalidated(queryClient)).toBe(false) + }) + + it('does not reach legacy entries', async () => { + const queryClient = new QueryClient() + queryClient.setQueryData(LEGACY_RQKEY(CUSTOM), feedData()) + + await queryClient.invalidateQueries({queryKey: RQKEY(CUSTOM)}) + + expect(isInvalidated(queryClient)).toBe(false) + }) +}) diff --git a/src/features/followingV2/home/queries/postFeed.ts b/src/features/followingV2/home/queries/postFeed.ts new file mode 100644 index 000000000..bcd475a55 --- /dev/null +++ b/src/features/followingV2/home/queries/postFeed.ts @@ -0,0 +1,509 @@ +import {useCallback, useMemo, useRef} from 'react' +import {AppState} from 'react-native' +import {type Client} from '@atproto/lex' +import {type AtIdentifierString, type AtUriString} from '@atproto/syntax' +import { + moderatePost, + type ModerationDecision, + type ModerationPrefs, +} from '@bsky/sdk/moderation' +import { + type InfiniteData, + type QueryKey, + useInfiniteQuery, +} from '@tanstack/react-query' + +import {AuthorFeedAPI} from '#/lib/api/feed/author' +import {DemoFeedAPI} from '#/lib/api/feed/demo' +import {LikesFeedAPI} from '#/lib/api/feed/likes' +import {PostListFeedAPI} from '#/lib/api/feed/posts' +import {aggregateUserInterests} from '#/lib/api/feed/utils' +import { + type FeedPostNumbering, + FeedTuner, + type FeedTunerFn, +} from '#/lib/api/feed-manip' +import {DISCOVER_FEED_URI} from '#/lib/constants' +import {logger} from '#/logger' +import {useFeedTuners} from '#/state/preferences/feed-tuners' +import {useModerationOpts} from '#/state/preferences/moderation-opts' +import {STALE} from '#/state/queries' +import {RQKEY_ROOT} from '#/state/queries/post-feed' +import {usePreferencesQuery} from '#/state/queries/preferences' +import {DEFAULT_LOGGED_OUT_PREFERENCES} from '#/state/queries/preferences/const' +import {useAutoPagination} from '#/state/queries/util' +import {useAppviewClient, useSession} from '#/state/session' +import * as userActionHistory from '#/state/userActionHistory' +import {KnownError} from '#/view/com/posts/PostFeedErrorMessage' +import {CustomFeedAPI} from '#/features/followingV2/home/api/custom' +import {FollowingFeedAPI} from '#/features/followingV2/home/api/following' +import {HomeFeedAPI} from '#/features/followingV2/home/api/home' +import {ListFeedAPI} from '#/features/followingV2/home/api/list' +import {MergeFeedAPI} from '#/features/followingV2/home/api/merge' +import { + type FeedAPI, + type ReasonFeedSource, +} from '#/features/followingV2/home/api/types' +import {type app} from '#/lexicons' + +type ActorDid = string +export type AuthorFilter = + | 'posts_with_replies' + | 'posts_no_replies' + | 'posts_and_author_threads' + | 'posts_with_media' + | 'posts_with_video' +type FeedUri = string +type ListUri = string +type PostsUriList = string + +export type FeedDescriptor = + | 'following' + | `author|${ActorDid}|${AuthorFilter}` + | `feedgen|${FeedUri}` + | `likes|${ActorDid}` + | `list|${ListUri}` + | `posts|${PostsUriList}` + | 'demo' +export interface FeedParams { + mergeFeedEnabled?: boolean + mergeFeedSources?: string[] + feedCacheKey?: 'discover' | 'explore' | undefined +} + +type RQPageParam = {cursor: string | undefined; api: FeedAPI} | undefined + +/** + * The fork's key prefixes the descriptor with `v2|`, so it never shares a + * cache entry with the legacy feed, and legacy single-feed filters (another + * screen refreshing or resetting the same feed) don't reach it. It keeps the + * legacy root and the descriptor's text, so cache-wide operations still reach + * it: post and profile shadows and the thread cache walk the root, label and + * language changes reset or invalidate the root, and block changes match the + * DID in `queryKey[1]`. The walkers read `pages[].feed`, so the fork's pages + * must keep a `feed` of `FeedViewPost`s. + */ +export function RQKEY(feedDesc: FeedDescriptor, params?: FeedParams) { + return [RQKEY_ROOT, `v2|${feedDesc}`, params || {}] +} + +export interface FeedPostSliceItem { + _reactKey: string + uri: AtUriString + post: app.bsky.feed.defs.PostView + record: app.bsky.feed.post.Main + postNumbering?: FeedPostNumbering + moderation: ModerationDecision + parentAuthor?: app.bsky.actor.defs.ProfileViewBasic + isParentBlocked?: boolean + isParentNotFound?: boolean +} + +export interface FeedPostSlice { + _isFeedPostSlice: boolean + _reactKey: string + items: FeedPostSliceItem[] + isIncompleteThread: boolean + isFallbackMarker: boolean + feedContext: string | undefined + reqId: string | undefined + feedPostUri: string + reason?: + | app.bsky.feed.defs.ReasonRepost + | app.bsky.feed.defs.ReasonPin + | ReasonFeedSource + | {[k: string]: unknown; $type: string} +} + +export interface FeedPageUnselected { + api: FeedAPI + cursor: string | undefined + feed: app.bsky.feed.defs.FeedViewPost[] + fetchedAt: number +} + +export interface FeedPage { + api: FeedAPI + tuner: FeedTuner + cursor: string | undefined + slices: FeedPostSlice[] + fetchedAt: number +} + +/** + * The minimum number of posts we want in a single "page" of results. Since we + * filter out unwanted content, we may fetch more than this number to ensure + * that we get _at least_ this number. + */ +const MIN_POSTS = 30 + +export function usePostFeedQuery( + feedDesc: FeedDescriptor, + params?: FeedParams, + opts?: {enabled?: boolean; ignoreFilterFor?: string}, +) { + const feedTuners = useFeedTuners(feedDesc) + const moderationOpts = useModerationOpts() + const {data: preferences} = usePreferencesQuery() + /** + * Load bearing: we need to await AA state or risk FOUC. This marginally + * delays feeds, but AA state is fetched immediately on load and is then + * available for the remainder of the session, so this delay only affects cold + * loads. -esb + */ + const enabled = + opts?.enabled !== false && Boolean(moderationOpts) && Boolean(preferences) + const userInterests = aggregateUserInterests(preferences) + const followingPinnedIndex = + preferences?.savedFeeds?.findIndex( + f => f.pinned && f.value === 'following', + ) ?? -1 + const enableFollowingToDiscoverFallback = followingPinnedIndex === 0 + const {hasSession} = useSession() + const client = useAppviewClient() + const lastRun = useRef<{ + data: InfiniteData + args: typeof selectArgs + result: InfiniteData + } | null>(null) + const isDiscover = feedDesc.includes(DISCOVER_FEED_URI) + + /** + * The number of posts to fetch in a single request. Because we filter + * unwanted content, we may over-fetch here to try and fill pages by + * `MIN_POSTS`. But if you're doing this, ask @why if it's ok first. + */ + const fetchLimit = MIN_POSTS + + // Make sure this doesn't invalidate unless really needed. + const selectArgs = useMemo( + () => ({ + feedTuners, + moderationOpts, + ignoreFilterFor: opts?.ignoreFilterFor, + isDiscover, + }), + [feedTuners, moderationOpts, opts?.ignoreFilterFor, isDiscover], + ) + + const query = useInfiniteQuery< + FeedPageUnselected, + Error, + InfiniteData, + QueryKey, + RQPageParam + >({ + enabled, + staleTime: STALE.INFINITY, + queryKey: RQKEY(feedDesc, params), + async queryFn({pageParam}: {pageParam: RQPageParam}) { + logger.debug('usePostFeedQuery', {feedDesc, cursor: pageParam?.cursor}) + const {api, cursor} = pageParam + ? pageParam + : { + api: createApi({ + feedDesc, + feedParams: params || {}, + feedTuners, + client, + // Not in the query key because they don't change: + userInterests, + // Not in the query key. Reacting to it switching isn't important: + enableFollowingToDiscoverFallback, + }), + cursor: undefined, + } + + const res = await api.fetch({cursor, limit: fetchLimit}) + + /* + * If this is a public view, we need to check if posts fail moderation. + * If all fail, we throw an error. If only some fail, we continue and let + * moderations happen later, which results in some posts being shown and + * some not. + */ + if (!hasSession) { + assertSomePostsPassModeration( + res.feed, + preferences?.moderationPrefs || + DEFAULT_LOGGED_OUT_PREFERENCES.moderationPrefs, + ) + } + + return { + api, + cursor: res.cursor, + feed: res.feed, + fetchedAt: Date.now(), + } + }, + initialPageParam: undefined, + getNextPageParam: lastPage => + lastPage.cursor + ? { + api: lastPage.api, + cursor: lastPage.cursor, + } + : undefined, + select: useCallback( + (data: InfiniteData) => { + // If the selection depends on some data, that data should + // be included in the selectArgs object and read here. + const {feedTuners, moderationOpts, ignoreFilterFor, isDiscover} = + selectArgs + + const tuner = new FeedTuner(feedTuners) + + // Keep track of the last run and whether we can reuse + // some already selected pages from there. + let reusedPages = [] + if (lastRun.current) { + const { + data: lastData, + args: lastArgs, + result: lastResult, + } = lastRun.current + let canReuse = true + for (let key in selectArgs) { + if (selectArgs.hasOwnProperty(key)) { + if ( + (selectArgs as Record)[key] !== + (lastArgs as Record)[key] + ) { + // Can't do reuse anything if any input has changed. + canReuse = false + break + } + } + } + if (canReuse) { + for (let i = 0; i < data.pages.length; i++) { + if (data.pages[i] && lastData.pages[i] === data.pages[i]) { + reusedPages.push(lastResult.pages[i]) + // Keep the tuner in sync so that the end result is deterministic. + tuner.tune(lastData.pages[i].feed) + continue + } + // Stop as soon as pages stop matching up. + break + } + } + } + + const result = { + pageParams: data.pageParams, + pages: [ + ...reusedPages, + ...data.pages.slice(reusedPages.length).map(page => ({ + api: page.api, + tuner, + cursor: page.cursor, + fetchedAt: page.fetchedAt, + slices: tuner + .tune(page.feed) + .map(slice => { + const moderations = slice.items.map(item => + moderatePost(item.post, moderationOpts!), + ) + + // apply moderation filter + for (let i = 0; i < slice.items.length; i++) { + const ignoreFilter = + slice.items[i].post.author.did === ignoreFilterFor + if (ignoreFilter) { + // remove mutes to avoid confused UIs + moderations[i].causes = moderations[i].causes.filter( + cause => cause.type !== 'muted', + ) + } + if ( + !ignoreFilter && + moderations[i]?.ui('contentList').filter + ) { + return undefined + } + } + + if (isDiscover) { + userActionHistory.seen( + slice.items.map(item => ({ + feedContext: slice.feedContext, + reqId: slice.reqId, + likeCount: item.post.likeCount ?? 0, + repostCount: item.post.repostCount ?? 0, + replyCount: item.post.replyCount ?? 0, + isFollowedBy: Boolean( + item.post.author.viewer?.followedBy, + ), + uri: item.post.uri, + })), + ) + } + + const feedPostSlice: FeedPostSlice = { + _reactKey: slice._reactKey, + _isFeedPostSlice: true, + isIncompleteThread: slice.isIncompleteThread, + isFallbackMarker: slice.isFallbackMarker, + feedContext: slice.feedContext, + reqId: slice.reqId, + reason: slice.reason, + feedPostUri: slice.feedPostUri, + items: slice.items.map((item, i) => { + const feedPostSliceItem: FeedPostSliceItem = { + _reactKey: `${slice._reactKey}-${i}-${item.post.uri}`, + uri: item.post.uri, + post: item.post, + record: item.record, + postNumbering: item.postNumbering, + moderation: moderations[i], + parentAuthor: item.parentAuthor, + isParentBlocked: item.isParentBlocked, + isParentNotFound: item.isParentNotFound, + } + return feedPostSliceItem + }), + } + return feedPostSlice + }) + .filter(n => !!n), + })), + ], + } + // Save for memoization. + lastRun.current = {data, result, args: selectArgs} + return result + }, + [selectArgs /* Don't change. Everything needs to go into selectArgs. */], + ), + }) + + let itemCount = 0 + for (const page of query.data?.pages || []) { + for (const slice of page.slices) { + itemCount += slice.items.length + } + } + useAutoPagination(query, itemCount, MIN_POSTS) + + return query +} + +export async function pollLatest(page: FeedPage | undefined) { + if (!page) { + return false + } + if (AppState.currentState !== 'active') { + return + } + + logger.debug('usePostFeedQuery: pollLatest') + const post = await page.api.peekLatest() + if (post) { + const slices = page.tuner.tune([post], { + dryRun: true, + }) + if (slices[0]) { + return true + } + } + + return false +} + +function createApi({ + feedDesc, + feedParams, + feedTuners, + userInterests, + client, + enableFollowingToDiscoverFallback, +}: { + feedDesc: FeedDescriptor + feedParams: FeedParams + feedTuners: FeedTunerFn[] + userInterests?: string + client: Client + enableFollowingToDiscoverFallback: boolean +}) { + if (feedDesc === 'following') { + if (feedParams.mergeFeedEnabled) { + return new MergeFeedAPI({ + client, + feedParams, + feedTuners, + userInterests, + }) + } else { + if (enableFollowingToDiscoverFallback) { + return new HomeFeedAPI({client, userInterests}) + } else { + return new FollowingFeedAPI({client}) + } + } + } else if (feedDesc.startsWith('author')) { + const [__, actor, filter] = feedDesc.split('|') + /* + * The descriptor is split out of an internally-built string, so neither the + * actor identifier nor the filter token is narrowed by the compiler here. + */ + return new AuthorFeedAPI({ + client, + feedParams: {actor: actor as AtIdentifierString, filter}, + }) + } else if (feedDesc.startsWith('likes')) { + const [__, actor] = feedDesc.split('|') + return new LikesFeedAPI({ + client, + feedParams: {actor: actor as AtIdentifierString}, + }) + } else if (feedDesc.startsWith('feedgen')) { + const [__, feed] = feedDesc.split('|') + return new CustomFeedAPI({ + client, + feedParams: {feed: feed as AtUriString}, + userInterests, + }) + } else if (feedDesc.startsWith('list')) { + const [__, list] = feedDesc.split('|') + return new ListFeedAPI({client, feedParams: {list: list as AtUriString}}) + } else if (feedDesc.startsWith('posts')) { + const [__, uriList] = feedDesc.split('|') + return new PostListFeedAPI({ + client, + feedParams: {uris: uriList.split(',') as AtUriString[]}, + }) + } else if (feedDesc === 'demo') { + return new DemoFeedAPI({client}) + } else { + // shouldnt happen + return new FollowingFeedAPI({client}) + } +} + +function assertSomePostsPassModeration( + feed: app.bsky.feed.defs.FeedViewPost[], + moderationPrefs: ModerationPrefs, +) { + // no posts in this feed + if (feed.length === 0) return true + + // assume false + let somePostsPassModeration = false + + for (const item of feed) { + const moderation = moderatePost(item.post, { + userDid: undefined, + prefs: moderationPrefs, + }) + + if (!moderation.ui('contentList').filter) { + // we have a sfw post + somePostsPassModeration = true + } + } + + if (!somePostsPassModeration) { + throw new Error(KnownError.FeedSignedInOnly) + } +} diff --git a/src/screens/VideoFeed/index.tsx b/src/screens/VideoFeed/index.tsx index 172a62958..7ae57fa7c 100644 --- a/src/screens/VideoFeed/index.tsx +++ b/src/screens/VideoFeed/index.tsx @@ -101,6 +101,7 @@ import {RichText} from '#/components/RichText' import {Text} from '#/components/Typography' import {useAnalytics} from '#/analytics' import {IS_ANDROID} from '#/env' +import {usePostFeedQuery as useFollowingV2PostFeedQuery} from '#/features/followingV2/home/queries/postFeed' import {app} from '#/lexicons' import * as bsky from '#/types/bsky' import {Scrubber, VIDEO_PLAYER_BOTTOM_INSET} from './components/Scrubber' @@ -200,13 +201,24 @@ function Feed() { const feedUri = params.type === 'feedgen' ? params.uri : undefined const {data: feedInfo} = useFeedInfo(feedUri) const feedFeedback = useFeedFeedback(feedInfo ?? undefined, hasSession) + const feedParams = + params.type === 'feedgen' && params.sourceInterstitial !== 'none' + ? {feedCacheKey: params.sourceInterstitial} + : undefined + /* + * Opened from the Following v2 fork of Home, the grid's pages are under the + * fork's query key, so read them from there to keep the starting post and + * the pages already loaded. + */ + const isFollowingV2 = params.type === 'feedgen' && params.followingV2 === true + const legacyQuery = usePostFeedQuery(feedDesc, feedParams, { + enabled: !isFollowingV2, + }) + const followingV2Query = useFollowingV2PostFeedQuery(feedDesc, feedParams, { + enabled: isFollowingV2, + }) const {data, error, hasNextPage, isFetchingNextPage, fetchNextPage} = - usePostFeedQuery( - feedDesc, - params.type === 'feedgen' && params.sourceInterstitial !== 'none' - ? {feedCacheKey: params.sourceInterstitial} - : undefined, - ) + isFollowingV2 ? followingV2Query : legacyQuery const videos = useMemo(() => { let vids = diff --git a/src/screens/VideoFeed/types.ts b/src/screens/VideoFeed/types.ts index 7a3e1fd96..af51354b9 100644 --- a/src/screens/VideoFeed/types.ts +++ b/src/screens/VideoFeed/types.ts @@ -9,6 +9,11 @@ export type VideoFeedSourceContext = uri: string sourceInterstitial: 'discover' | 'explore' | 'none' initialPostUri?: string + /** + * Opened from the Following v2 fork of Home, which caches its feeds + * under its own query key. + */ + followingV2?: boolean } | { type: 'author' -- knotmirror 0.0.1