tooot/src/components/Timeline.tsx

256 lines
7.3 KiB
TypeScript
Raw Normal View History

2021-01-04 18:29:02 +01:00
import ComponentSeparator from '@components/Separator'
import { useScrollToTop } from '@react-navigation/native'
2021-01-24 02:25:43 +01:00
import { QueryKeyTimeline, useTimelineQuery } from '@utils/queryHooks/timeline'
2021-02-10 00:40:44 +01:00
import { getLocalActiveIndex } from '@utils/slices/instancesSlice'
2021-01-04 18:29:02 +01:00
import { StyleConstants } from '@utils/styles/constants'
2021-01-24 02:25:43 +01:00
import { findIndex } from 'lodash'
2021-02-11 01:33:31 +01:00
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { FlatListProps, StyleSheet } from 'react-native'
2020-12-17 12:04:58 +01:00
import { FlatList } from 'react-native-gesture-handler'
import Animated, {
useAnimatedStyle,
useSharedValue,
withTiming
} from 'react-native-reanimated'
import { InfiniteData, useQueryClient } from 'react-query'
2021-02-10 00:40:44 +01:00
import { useSelector } from 'react-redux'
2021-02-11 01:33:31 +01:00
import haptics from './haptics'
2021-01-24 02:25:43 +01:00
import TimelineConversation from './Timeline/Conversation'
import TimelineDefault from './Timeline/Default'
import TimelineEmpty from './Timeline/Empty'
import TimelineEnd from './Timeline/End'
import TimelineNotifications from './Timeline/Notifications'
import TimelineRefresh from './Timeline/Refresh'
2020-12-19 18:21:37 +01:00
export interface Props {
page: App.Pages
hashtag?: Mastodon.Tag['name']
list?: Mastodon.List['id']
toot?: Mastodon.Status['id']
account?: Mastodon.Account['id']
2020-10-31 21:04:46 +01:00
disableRefresh?: boolean
2021-01-01 16:48:16 +01:00
disableInfinity?: boolean
2021-01-15 01:15:27 +01:00
customProps?: Partial<FlatListProps<any>>
}
2020-10-23 09:22:17 +02:00
const Timeline: React.FC<Props> = ({
page,
hashtag,
list,
toot,
account,
2021-01-01 16:48:16 +01:00
disableRefresh = false,
2021-01-15 01:15:27 +01:00
disableInfinity = false,
customProps
}) => {
2021-02-10 00:40:44 +01:00
// Update timeline when account switched
useSelector(getLocalActiveIndex)
2021-01-07 19:13:09 +01:00
const queryKeyParams = {
page,
2021-01-07 19:13:09 +01:00
...(hashtag && { hashtag }),
...(list && { list }),
...(toot && { toot }),
...(account && { account })
}
const queryKey: QueryKeyTimeline = ['Timeline', queryKeyParams]
const {
2020-12-13 01:24:25 +01:00
status,
data,
2020-12-18 23:58:53 +01:00
refetch,
2020-12-21 22:08:29 +01:00
isSuccess,
2021-01-12 00:12:44 +01:00
isFetching,
2021-01-17 22:37:05 +01:00
isLoading,
hasPreviousPage,
fetchPreviousPage,
isFetchingPreviousPage,
2020-12-18 23:58:53 +01:00
hasNextPage,
2020-12-26 12:59:16 +01:00
fetchNextPage,
isFetchingNextPage
2021-01-11 21:36:57 +01:00
} = useTimelineQuery({
2021-01-07 19:13:09 +01:00
...queryKeyParams,
options: {
2021-02-11 01:33:31 +01:00
getPreviousPageParam: firstPage =>
firstPage.links?.prev && {
min_id: firstPage.links.prev,
// https://github.com/facebook/react-native/issues/25239#issuecomment-731100372
limit: '3'
},
getNextPageParam: lastPage =>
lastPage.links?.next && { max_id: lastPage.links.next }
2020-12-21 13:56:04 +01:00
}
})
2021-01-07 19:13:09 +01:00
2021-02-11 01:33:31 +01:00
const flattenData = data?.pages ? data.pages.flatMap(d => [...d.body]) : []
2020-12-12 12:49:29 +01:00
2020-12-17 12:04:58 +01:00
const flRef = useRef<FlatList<any>>(null)
2021-01-24 02:25:43 +01:00
const scrolled = useRef(false)
2020-12-12 12:49:29 +01:00
useEffect(() => {
2021-01-24 02:25:43 +01:00
if (toot && isSuccess && !scrolled.current) {
scrolled.current = true
2021-01-11 21:36:57 +01:00
const pointer = findIndex(flattenData, ['id', toot])
2020-12-12 12:49:29 +01:00
setTimeout(() => {
flRef.current?.scrollToIndex({
2021-01-11 21:36:57 +01:00
index: pointer,
2020-12-12 12:49:29 +01:00
viewOffset: 100
})
}, 500)
}
2021-01-24 02:25:43 +01:00
}, [isSuccess, flattenData.length, scrolled])
2020-10-23 09:22:17 +02:00
2020-12-21 22:58:53 +01:00
const keyExtractor = useCallback(({ id }) => id, [])
2021-02-11 01:33:31 +01:00
const renderItem = useCallback(
({ item }) => {
switch (page) {
case 'Conversations':
return (
<TimelineConversation conversation={item} queryKey={queryKey} />
)
case 'Notifications':
return (
<TimelineNotifications notification={item} queryKey={queryKey} />
)
default:
return (
<TimelineDefault
item={item}
queryKey={queryKey}
{...(toot === item.id && { highlighted: true })}
{...(data?.pages[0].pinned && { pinned: data?.pages[0].pinned })}
/>
)
}
},
[data?.pages[0]]
)
2020-12-21 22:58:53 +01:00
const ItemSeparatorComponent = useCallback(
2020-12-12 22:19:18 +01:00
({ leadingItem }) => (
2021-01-04 18:29:02 +01:00
<ComponentSeparator
{...(toot === leadingItem.id
? { extraMarginLeft: 0 }
: {
extraMarginLeft:
StyleConstants.Avatar.M + StyleConstants.Spacing.S
})}
2020-12-12 22:19:18 +01:00
/>
),
[]
)
const flItemEmptyComponent = useMemo(
2020-12-13 01:24:25 +01:00
() => <TimelineEmpty status={status} refetch={refetch} />,
2020-12-18 23:58:53 +01:00
[status]
2020-12-12 22:19:18 +01:00
)
2020-12-26 12:59:16 +01:00
const onEndReached = useCallback(
2021-01-01 16:48:16 +01:00
() => !disableInfinity && !isFetchingNextPage && fetchNextPage(),
2020-12-26 12:59:16 +01:00
[isFetchingNextPage]
)
const ListFooterComponent = useMemo(
2021-01-01 16:48:16 +01:00
() => <TimelineEnd hasNextPage={!disableInfinity ? hasNextPage : false} />,
2020-12-19 01:57:57 +01:00
[hasNextPage]
)
2021-01-13 01:03:46 +01:00
2020-12-12 12:49:29 +01:00
const onScrollToIndexFailed = useCallback(error => {
const offset = error.averageItemLength * error.index
flRef.current?.scrollToOffset({ offset })
setTimeout(
() =>
flRef.current?.scrollToIndex({ index: error.index, viewOffset: 100 }),
350
2020-10-26 00:27:53 +01:00
)
2020-12-12 12:49:29 +01:00
}, [])
2020-10-23 09:22:17 +02:00
2020-12-13 23:02:54 +01:00
useScrollToTop(flRef)
const queryClient = useQueryClient()
const scrollY = useSharedValue(0)
2021-02-11 01:33:31 +01:00
const [isFetchingLatest, setIsFetchingLatest] = useState(false)
useEffect(() => {
// https://github.com/facebook/react-native/issues/25239#issuecomment-731100372
if (isFetchingLatest) {
if (!isFetchingPreviousPage) {
fetchPreviousPage()
} else {
if (data?.pages[0].body.length === 0) {
setIsFetchingLatest(false)
queryClient.setQueryData<InfiniteData<any> | undefined>(
queryKey,
data => {
if (data?.pages[0].body.length === 0) {
return {
pages: data.pages.slice(1),
pageParams: data.pageParams.slice(1)
}
} else {
return data
}
}
)
}
}
}
}, [isFetchingPreviousPage, isFetchingLatest, data?.pages[0].body])
const onScroll = useCallback(({ nativeEvent }) => {
scrollY.value = nativeEvent.contentOffset.y
}, [])
const onResponderRelease = useCallback(() => {
if (
scrollY.value <= -StyleConstants.Spacing.XL &&
2021-02-11 01:33:31 +01:00
!isFetchingLatest &&
!disableRefresh
) {
2021-02-11 01:33:31 +01:00
haptics('Light')
setIsFetchingLatest(true)
flRef.current?.scrollToOffset({
animated: true,
offset: 1
})
}
}, [scrollY.value, isFetchingLatest, disableRefresh])
const headerPadding = useAnimatedStyle(() => {
if (isFetchingLatest) {
return { paddingTop: withTiming(StyleConstants.Spacing.XL) }
} else {
return { paddingTop: withTiming(0) }
}
2021-02-11 01:33:31 +01:00
}, [isFetchingLatest])
const ListHeaderComponent = useMemo(
() => <Animated.View style={headerPadding} />,
[]
)
2020-12-13 23:02:54 +01:00
2020-12-12 12:49:29 +01:00
return (
<>
<TimelineRefresh isLoading={isLoading} disable={disableRefresh} />
<FlatList
onScroll={onScroll}
onResponderRelease={onResponderRelease}
ref={flRef}
windowSize={8}
data={flattenData}
2021-02-10 00:40:44 +01:00
initialNumToRender={6}
maxToRenderPerBatch={3}
style={styles.flatList}
renderItem={renderItem}
onEndReached={onEndReached}
keyExtractor={keyExtractor}
onEndReachedThreshold={0.75}
ListHeaderComponent={ListHeaderComponent}
ListFooterComponent={ListFooterComponent}
ListEmptyComponent={flItemEmptyComponent}
ItemSeparatorComponent={ItemSeparatorComponent}
{...(toot && isSuccess && { onScrollToIndexFailed })}
maintainVisibleContentPosition={{
minIndexForVisible: 0
}}
{...customProps}
/>
</>
2020-12-12 12:49:29 +01:00
)
2020-10-23 09:22:17 +02:00
}
2020-11-28 17:07:30 +01:00
const styles = StyleSheet.create({
flatList: {
minHeight: '100%'
}
})
2020-10-31 21:04:46 +01:00
export default Timeline