1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
|
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useQueryClient} from '@tanstack/react-query'
import {useAnalytics} from 'lib/analytics/analytics'
import {useInitialNumToRender} from 'lib/hooks/useInitialNumToRender'
import {useTheme} from 'lib/ThemeContext'
import React, {memo} from 'react'
import {
ActivityIndicator,
AppState,
Dimensions,
StyleProp,
StyleSheet,
View,
ViewStyle,
} from 'react-native'
import {FALLBACK_MARKER_POST} from '#/lib/api/feed/home'
import {logger} from '#/logger'
import {isWeb} from '#/platform/detection'
import {listenPostCreated} from '#/state/events'
import {STALE} from '#/state/queries'
import {
FeedDescriptor,
FeedParams,
pollLatest,
RQKEY,
usePostFeedQuery,
} from '#/state/queries/post-feed'
import {useSession} from '#/state/session'
import {List, ListRef} from '../util/List'
import {PostFeedLoadingPlaceholder} from '../util/LoadingPlaceholder'
import {LoadMoreRetryBtn} from '../util/LoadMoreRetryBtn'
import {DiscoverFallbackHeader} from './DiscoverFallbackHeader'
import {FeedErrorMessage} from './FeedErrorMessage'
import {FeedSlice} from './FeedSlice'
const LOADING_ITEM = {_reactKey: '__loading__'}
const EMPTY_FEED_ITEM = {_reactKey: '__empty__'}
const ERROR_ITEM = {_reactKey: '__error__'}
const LOAD_MORE_ERROR_ITEM = {_reactKey: '__load_more_error__'}
// 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 Feed = ({
feed,
feedParams,
ignoreFilterFor,
style,
enabled,
pollInterval,
disablePoll,
scrollElRef,
onScrolledDownChange,
onHasNew,
renderEmptyState,
renderEndOfFeed,
testID,
headerOffset = 0,
desktopFixedHeightOffset,
ListHeaderComponent,
extraData,
}: {
feed: FeedDescriptor
feedParams?: FeedParams
ignoreFilterFor?: string
style?: StyleProp<ViewStyle>
enabled?: boolean
pollInterval?: number
disablePoll?: boolean
scrollElRef?: ListRef
onHasNew?: (v: boolean) => void
onScrolledDownChange?: (isScrolledDown: boolean) => void
renderEmptyState: () => JSX.Element
renderEndOfFeed?: () => JSX.Element
testID?: string
headerOffset?: number
desktopFixedHeightOffset?: number
ListHeaderComponent?: () => JSX.Element
extraData?: any
}): React.ReactNode => {
const theme = useTheme()
const {track} = useAnalytics()
const {_} = useLingui()
const queryClient = useQueryClient()
const {currentAccount} = useSession()
const initialNumToRender = useInitialNumToRender()
const [isPTRing, setIsPTRing] = React.useState(false)
const checkForNewRef = React.useRef<(() => void) | null>(null)
const lastFetchRef = React.useRef<number>(Date.now())
const opts = React.useMemo(
() => ({enabled, ignoreFilterFor}),
[enabled, ignoreFilterFor],
)
const {
data,
isFetching,
isFetched,
isError,
error,
refetch,
hasNextPage,
isFetchingNextPage,
fetchNextPage,
} = usePostFeedQuery(feed, feedParams, opts)
if (data?.pages[0]) {
lastFetchRef.current = data?.pages[0].fetchedAt
}
const isEmpty = React.useMemo(
() => !isFetching && !data?.pages?.some(page => page.slices.length),
[isFetching, data],
)
const checkForNew = React.useCallback(async () => {
if (!data?.pages[0] || isFetching || !onHasNew || !enabled || disablePoll) {
return
}
try {
if (await pollLatest(data.pages[0])) {
onHasNew(true)
}
} catch (e) {
logger.error('Poll latest failed', {feed, message: String(e)})
}
}, [feed, data, isFetching, onHasNew, enabled, disablePoll])
const myDid = currentAccount?.did || ''
const onPostCreated = React.useCallback(() => {
// NOTE
// only invalidate if there's 1 page
// more than 1 page can trigger some UI freakouts on iOS and android
// -prf
if (
data?.pages.length === 1 &&
(feed === 'following' ||
feed === 'home' ||
feed === `author|${myDid}|posts_and_author_threads`)
) {
queryClient.invalidateQueries({queryKey: RQKEY(feed)})
}
}, [queryClient, feed, data, myDid])
React.useEffect(() => {
return listenPostCreated(onPostCreated)
}, [onPostCreated])
React.useEffect(() => {
// we store the interval handler in a ref to avoid needless
// reassignments in other effects
checkForNewRef.current = checkForNew
}, [checkForNew])
React.useEffect(() => {
if (enabled) {
const timeSinceFirstLoad = Date.now() - lastFetchRef.current
// DISABLED need to check if this is causing random feed refreshes -prf
/*if (timeSinceFirstLoad > REFRESH_AFTER) {
// do a full refresh
scrollElRef?.current?.scrollToOffset({offset: 0, animated: false})
queryClient.resetQueries({queryKey: RQKEY(feed)})
} else*/ if (
timeSinceFirstLoad > CHECK_LATEST_AFTER &&
checkForNewRef.current
) {
// check for new on enable (aka on focus)
checkForNewRef.current()
}
}
}, [enabled, feed, queryClient, scrollElRef])
React.useEffect(() => {
let cleanup1: () => void | undefined, cleanup2: () => void | undefined
const subscription = AppState.addEventListener('change', nextAppState => {
// check for new on app foreground
if (nextAppState === 'active') {
checkForNewRef.current?.()
}
})
cleanup1 = () => subscription.remove()
if (pollInterval) {
// check for new on interval
const i = setInterval(() => checkForNewRef.current?.(), pollInterval)
cleanup2 = () => clearInterval(i)
}
return () => {
cleanup1?.()
cleanup2?.()
}
}, [pollInterval])
const feedItems = React.useMemo(() => {
let arr: any[] = []
if (isFetched) {
if (isError && isEmpty) {
arr = arr.concat([ERROR_ITEM])
} else if (isEmpty) {
arr = arr.concat([EMPTY_FEED_ITEM])
} else if (data) {
for (const page of data?.pages) {
arr = arr.concat(page.slices)
}
}
if (isError && !isEmpty) {
arr = arr.concat([LOAD_MORE_ERROR_ITEM])
}
} else {
arr.push(LOADING_ITEM)
}
return arr
}, [isFetched, isError, isEmpty, data])
// events
// =
const onRefresh = React.useCallback(async () => {
track('Feed:onRefresh')
setIsPTRing(true)
try {
await refetch()
onHasNew?.(false)
} catch (err) {
logger.error('Failed to refresh posts feed', {message: err})
}
setIsPTRing(false)
}, [refetch, track, setIsPTRing, onHasNew])
const onEndReached = React.useCallback(async () => {
if (isFetching || !hasNextPage || isError) return
track('Feed:onEndReached')
try {
await fetchNextPage()
} catch (err) {
logger.error('Failed to load more posts', {message: err})
}
}, [isFetching, hasNextPage, isError, fetchNextPage, track])
const onPressTryAgain = React.useCallback(() => {
refetch()
onHasNew?.(false)
}, [refetch, onHasNew])
const onPressRetryLoadMore = React.useCallback(() => {
fetchNextPage()
}, [fetchNextPage])
// rendering
// =
const renderItem = React.useCallback(
({item}: {item: any}) => {
if (item === EMPTY_FEED_ITEM) {
return renderEmptyState()
} else if (item === ERROR_ITEM) {
return (
<FeedErrorMessage
feedDesc={feed}
error={error ?? undefined}
onPressTryAgain={onPressTryAgain}
/>
)
} else if (item === LOAD_MORE_ERROR_ITEM) {
return (
<LoadMoreRetryBtn
label={_(
msg`There was an issue fetching posts. Tap here to try again.`,
)}
onPress={onPressRetryLoadMore}
/>
)
} else if (item === LOADING_ITEM) {
return <PostFeedLoadingPlaceholder />
} else if (item.rootUri === FALLBACK_MARKER_POST.post.uri) {
// HACK
// tell the user we fell back to discover
// see home.ts (feed api) for more info
// -prf
return <DiscoverFallbackHeader />
}
return <FeedSlice slice={item} />
},
[feed, error, onPressTryAgain, onPressRetryLoadMore, renderEmptyState, _],
)
const shouldRenderEndOfFeed =
!hasNextPage && !isEmpty && !isFetching && !isError && !!renderEndOfFeed
const FeedFooter = React.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.
*/
const offset = Math.max(headerOffset, 32) * (isWeb ? 1 : 2)
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])
return (
<View testID={testID} style={style}>
<List
testID={testID ? `${testID}-flatlist` : undefined}
ref={scrollElRef}
data={feedItems}
keyExtractor={item => item._reactKey}
renderItem={renderItem}
ListFooterComponent={FeedFooter}
ListHeaderComponent={ListHeaderComponent}
refreshing={isPTRing}
onRefresh={onRefresh}
headerOffset={headerOffset}
contentContainerStyle={{
minHeight: Dimensions.get('window').height * 1.5,
}}
onScrolledDownChange={onScrolledDownChange}
indicatorStyle={theme.colorScheme === 'dark' ? 'white' : 'black'}
onEndReached={onEndReached}
onEndReachedThreshold={2} // number of posts left to trigger load more
removeClippedSubviews={true}
extraData={extraData}
// @ts-ignore our .web version only -prf
desktopFixedHeight={
desktopFixedHeightOffset ? desktopFixedHeightOffset : true
}
initialNumToRender={initialNumToRender}
windowSize={11}
/>
</View>
)
}
Feed = memo(Feed)
export {Feed}
const styles = StyleSheet.create({
feedFooter: {paddingTop: 20},
})
|