Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172import { 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 { type AuthorFilter, type FeedDescriptor, type FeedParams, type FeedPostSlice, type FeedPostSliceItem, pollLatest, RQKEY, usePostFeedQuery,} from '#/state/queries/post-feed'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 {List, type ListRef} from '#/view/com/util/List'import {LoadMoreRetryBtn} from '#/view/com/util/LoadMoreRetryBtn'import {type VideoFeedSourceContext} from '#/screens/VideoFeed/types'import {atoms as a, useLayoutBreakpoints, useTheme} from '#/alf'import {ProgressGuide, SuggestedFollows} from '#/components/FeedInterstitials'import { PostFeedVideoGridRow, PostFeedVideoGridRowPlaceholder, useVideoGridColumns,} 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 {PostFeedSkeleton} from '#/components/PostFeedSkeleton'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 {ComposerPrompt} from '../feeds/ComposerPrompt'import {DiscoverFallbackHeader} from './DiscoverFallbackHeader'import {FeedShutdownMsg} from './FeedShutdownMsg'import {PostFeedErrorMessage} from './PostFeedErrorMessage'import {PostFeedItem} from './PostFeedItem'import {ShowLessFollowup} from './ShowLessFollowup'import {ViewFullThread} from './ViewFullThread'
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: '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<void>}
// DISABLED need to check if this is causing random feed refreshes -prf// const REFRESH_AFTER = STALE.HOURS.ONEconst 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<ViewStyle> 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<string, unknown> savedFeedConfig?: app.bsky.actor.defs.SavedFeed initialNumToRender?: number isVideoFeed?: boolean lastFetchDate?: () => number ref?: React.Ref<PostFeedRef>}): 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<number>(Date.now()) const [feedType, feedUriOrActorDid, feedTab] = feed.split('|') const videoGridColumns = useVideoGridColumns() 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<string>(), ) 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 welcomeGuide = useProgressGuide('welcome') const followProgressGuide = useProgressGuide('follow-10') const followAndLikeProgressGuide = useProgressGuide('like-10-and-follow-7')
const showProgressInterstitial = (welcomeGuide || followProgressGuide || followAndLikeProgressGuide) && !rightNavVisible
const {trendingVideoDisabled} = useTrendingSettings()
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<FeedRow, {type: 'sliceItem'}>) => { 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 rowItem = { item, feedContext: video.feedContext, reqId: video.reqId, } if (i % videoGridColumns === 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. */ } 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 (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, videoGridColumns, isVideoFeed, areVideoFeedsEnabled, hasPressedShowLessUris, 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<FeedRow>) => { if (row.type === 'empty') { return renderEmptyState() } else if (row.type === 'error') { return ( <PostFeedErrorMessage feedDesc={feed} error={error ?? undefined} onPressTryAgain={onPressTryAgain} savedFeedConfig={savedFeedConfig} /> ) } else if (row.type === 'loadMoreError') { return ( <LoadMoreRetryBtn label={l`There was an issue fetching posts. Tap here to try again.`} onPress={onPressRetryLoadMore} /> ) } else if (row.type === 'loading') { return <PostFeedSkeleton /> } else if (row.type === 'feedShutdownMsg') { return <FeedShutdownMsg feedUri={feedUriOrActorDid} /> } else if (row.type === 'description') { return ( <RichText value={row.value} style={[ a.m_md, a.text_md, a.leading_snug, t.atoms.text_contrast_high, ]} /> ) } else if (row.type === 'interstitialFollows') { return <SuggestedFollows feed={feed} /> } else if (row.type === 'interstitialProgressGuide') { return <ProgressGuide /> } else if (row.type === 'interstitialFeedTrendingTopics') { return ( <FeedTrendingTopicsInterstitial feedSliceIndex={row.feedSliceIndex} /> ) } else if (row.type === 'liveEventFeedsAndTrendingBanner') { return <DiscoverFeedLiveEventFeedsAndTrendingBanner /> } else if (row.type === 'composerPrompt') { return <ComposerPrompt /> } else if (row.type === 'interstitialTrendingVideos') { return <TrendingVideosInterstitial /> } else if (row.type === 'fallbackMarker') { // HACK // tell the user we fell back to discover // see home.ts (feed api) for more info // -prf return <DiscoverFallbackHeader /> } else if (row.type === 'sliceItem') { const slice = row.slice const indexInSlice = row.indexInSlice const item = slice.items[indexInSlice] return ( <PostFeedItem post={item.post} record={item.record} postNumbering={item.postNumbering} reason={indexInSlice === 0 ? slice.reason : undefined} feedContext={slice.feedContext} reqId={slice.reqId} moderation={item.moderation} parentAuthor={item.parentAuthor} showReplyTo={row.showReplyTo} isThreadParent={isThreadParentAt(slice.items, indexInSlice)} isThreadChild={isThreadChildAt(slice.items, indexInSlice)} isThreadLastChild={ isThreadChildAt(slice.items, indexInSlice) && slice.items.length === indexInSlice + 1 } isParentBlocked={item.isParentBlocked} isParentNotFound={item.isParentNotFound} hideTopBorder={rowIndex === 0 && indexInSlice === 0} rootPost={slice.items[0].post} onShowLess={onPressShowLess} /> ) } else if (row.type === 'sliceViewFullThread') { return <ViewFullThread uri={row.uri} /> } else if (row.type === 'videoGridRowPlaceholder') { return ( <View> <PostFeedVideoGridRowPlaceholder /> <PostFeedVideoGridRowPlaceholder /> <PostFeedVideoGridRowPlaceholder /> </View> ) } 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', } }
return ( <PostFeedVideoGridRow items={row.items} sourceContext={sourceContext} /> ) } else if (row.type === 'showLessFollowup') { return <ShowLessFollowup /> } 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 ? ( <View style={[styles.feedFooter]}> <ActivityIndicator /> <View style={{height: offset}} /> </View> ) : shouldRenderEndOfFeed ? ( <View style={{minHeight: offset}}>{renderEndOfFeed()}</View> ) : ( <View style={{height: offset}} /> ) }, [ isFetchingNextPage, shouldRenderEndOfFeed, renderEndOfFeed, headerOffset, bottomBarOffset, ])
const liveNowConfig = useLiveNowConfig()
const seenActorWithStatusRef = useRef<Set<string>>(new Set()) const seenPostUrisRef = useRef<Set<string>>(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<Set<string>>(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 ( <View testID={testID} style={style}> <List testID={testID ? `${testID}-flatlist` : undefined} ref={scrollElRef} data={feedItems} keyExtractor={(item: FeedRow) => 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} /> </View> )}PostFeed = memo(PostFeed)export {PostFeed}
const styles = StyleSheet.create({ feedFooter: {paddingTop: 20},})
export function isThreadParentAt<T>(arr: Array<T>, i: number) { if (arr.length === 1) { return false } return i < arr.length - 1}
export function isThreadChildAt<T>(arr: Array<T>, i: number) { if (arr.length === 1) { return false } return i > 0}