tooot/src/components/Timeline/index.tsx

316 lines
9.6 KiB
TypeScript
Raw Normal View History

2021-01-04 18:29:02 +01:00
import ComponentSeparator from '@components/Separator'
2023-01-30 00:25:46 +01:00
import CustomText from '@components/Text'
import TimelineDefault from '@components/Timeline/Default'
import { useNavigation, useScrollToTop } from '@react-navigation/native'
2022-12-11 12:12:46 +01:00
import { UseInfiniteQueryOptions } from '@tanstack/react-query'
2022-06-01 23:13:43 +02:00
import { QueryKeyTimeline, useTimelineQuery } from '@utils/queryHooks/timeline'
2022-12-31 00:07:28 +01:00
import { flattenPages } from '@utils/queryHooks/utils'
import {
getAccountStorage,
setAccountStorage,
useGlobalStorageListener
} from '@utils/storage/actions'
2021-01-04 18:29:02 +01:00
import { StyleConstants } from '@utils/styles/constants'
2021-02-13 13:08:34 +01:00
import { useTheme } from '@utils/styles/ThemeManager'
import { throttle } from 'lodash'
import React, { RefObject, useCallback, useEffect, useRef, useState } from 'react'
2023-01-30 00:25:46 +01:00
import { useTranslation } from 'react-i18next'
import { FlatList, FlatListProps, Platform, RefreshControl } from 'react-native'
2023-01-30 00:25:46 +01:00
import Animated, {
Easing,
runOnJS,
2023-01-30 13:40:43 +01:00
useAnimatedReaction,
2023-01-30 00:25:46 +01:00
useAnimatedScrollHandler,
useAnimatedStyle,
useDerivedValue,
useSharedValue,
withDelay,
withSequence,
withTiming
} from 'react-native-reanimated'
import TimelineEmpty from './Empty'
import TimelineFooter from './Footer'
import TimelineRefresh, { SEPARATION_Y_1, SEPARATION_Y_2 } from './Refresh'
2022-06-01 23:13:43 +02:00
const AnimatedFlatList = Animated.createAnimatedComponent(FlatList<any>)
2020-12-19 18:21:37 +01:00
export interface Props {
flRef?: RefObject<FlatList<any>>
2021-02-27 16:33:54 +01:00
queryKey: QueryKeyTimeline
2022-12-11 12:12:46 +01:00
queryOptions?: Omit<
UseInfiniteQueryOptions<any>,
'notifyOnChangeProps' | 'getNextPageParam' | 'getPreviousPageParam' | 'select' | 'onSuccess'
>
2020-10-31 21:04:46 +01:00
disableRefresh?: boolean
2021-01-01 16:48:16 +01:00
disableInfinity?: boolean
readMarker?: 'read_marker_following'
customProps?: Partial<FlatListProps<any>>
}
2020-10-23 09:22:17 +02:00
const Timeline: React.FC<Props> = ({
2021-02-27 16:33:54 +01:00
flRef: customFLRef,
queryKey,
2022-12-11 12:12:46 +01:00
queryOptions,
2021-01-01 16:48:16 +01:00
disableRefresh = false,
2021-01-15 01:15:27 +01:00
disableInfinity = false,
readMarker = undefined,
2021-01-15 01:15:27 +01:00
customProps
}) => {
const navigation = useNavigation()
2023-01-30 00:25:46 +01:00
const { colors, theme } = useTheme()
const { t } = useTranslation('componentTimeline')
2021-02-13 13:08:34 +01:00
2023-02-07 23:38:34 +01:00
const firstLoad = useSharedValue<boolean>(!readMarker || disableRefresh)
const shouldAutoFetch = useSharedValue<boolean>(!!readMarker && !disableRefresh)
2023-01-30 00:25:46 +01:00
const { data, refetch, isFetching, isLoading, isRefetching, fetchNextPage, isFetchingNextPage } =
useTimelineQuery({
...queryKey[1],
options: {
2022-12-11 12:12:46 +01:00
...queryOptions,
notifyOnChangeProps: Platform.select({
ios: ['dataUpdatedAt', 'isFetching'],
android: ['dataUpdatedAt', 'isFetching', 'isLoading']
2023-02-07 23:38:34 +01:00
}),
onSuccess: () => {
if (!firstLoad.value) {
firstLoad.value = true
fetchingType.value = 1
}
}
}
})
2021-01-07 19:13:09 +01:00
const flRef = useRef<FlatList>(null)
2023-01-30 13:40:43 +01:00
const isFetchingPrev = useSharedValue<boolean>(false)
2023-01-30 00:25:46 +01:00
const [fetchedCount, setFetchedCount] = useState<number | null>(null)
const fetchedNoticeHeight = useSharedValue<number>(100)
2023-01-30 13:40:43 +01:00
const notifiedFetchedNotice = useSharedValue<boolean>(false)
useAnimatedReaction(
() => isFetchingPrev.value,
(curr, prev) => {
if (curr === true && prev === false) {
notifiedFetchedNotice.value = true
}
}
)
useAnimatedReaction(
() => fetchedCount,
(curr, prev) => {
if (curr !== null && prev === null) {
notifiedFetchedNotice.value = false
2023-02-07 23:38:34 +01:00
if (curr === 0) {
shouldAutoFetch.value = false
}
2023-01-30 13:40:43 +01:00
}
},
[fetchedCount]
)
2023-01-30 00:25:46 +01:00
const fetchedNoticeTop = useDerivedValue(() => {
2023-01-30 13:40:43 +01:00
if (notifiedFetchedNotice.value || fetchedCount !== null) {
2023-01-30 00:25:46 +01:00
return withSequence(
withTiming(fetchedNoticeHeight.value + 16 + 4),
withDelay(
2000,
2023-01-30 13:40:43 +01:00
withTiming(
0,
{ easing: Easing.out(Easing.ease) },
finished => finished && runOnJS(setFetchedCount)(null)
)
2023-01-30 00:25:46 +01:00
)
)
} else {
return 0
}
2023-01-30 13:40:43 +01:00
}, [fetchedCount])
2023-01-30 00:25:46 +01:00
const fetchedNoticeAnimate = useAnimatedStyle(() => ({
transform: [{ translateY: fetchedNoticeTop.value }]
}))
2020-12-13 23:02:54 +01:00
2022-06-01 23:13:43 +02:00
const scrollY = useSharedValue(0)
const fetchingType = useSharedValue<0 | 1 | 2>(0)
const onScroll = useAnimatedScrollHandler(
{
onScroll: ({ contentOffset: { y } }) => {
scrollY.value = y
2023-02-07 23:38:34 +01:00
if (
y < 300 &&
!isFetchingPrev.value &&
fetchingType.value === 0 &&
shouldAutoFetch.value &&
Platform.OS === 'ios'
) {
fetchingType.value = 1
}
2022-06-01 23:13:43 +02:00
},
onEndDrag: ({ contentOffset: { y } }) => {
if (!disableRefresh && !isFetching) {
if (y <= SEPARATION_Y_2) {
fetchingType.value = 2
} else if (y <= SEPARATION_Y_1) {
fetchingType.value = 1
2023-02-07 23:38:34 +01:00
shouldAutoFetch.value = true
2022-06-01 23:13:43 +02:00
}
}
}
},
[isFetching]
)
const latestMarker = useRef<string>()
const updateMarkers = useCallback(
2023-02-07 13:56:50 +01:00
throttle(() => {
if (readMarker) {
const currentMarker = getAccountStorage.string(readMarker) || '0'
if ((latestMarker.current || '0') > currentMarker) {
setAccountStorage([{ key: readMarker, value: latestMarker.current }])
} else {
// setAccountStorage([{ key: readMarker, value: '105250709762254246' }])
}
}
}, 1000 * 15),
[]
)
readMarker &&
useEffect(() => {
const unsubscribe = navigation.addListener('blur', () =>
setAccountStorage([{ key: readMarker, value: latestMarker.current }])
)
return unsubscribe
}, [])
const viewabilityConfigCallbackPairs = useRef<
Pick<FlatListProps<any>, 'viewabilityConfigCallbackPairs'>['viewabilityConfigCallbackPairs']
>(
readMarker
? [
{
viewabilityConfig: {
minimumViewTime: 300,
2023-02-07 13:56:50 +01:00
itemVisiblePercentThreshold: 10,
waitForInteraction: false
},
onViewableItemsChanged: ({ viewableItems }) => {
const firstItemId = viewableItems.filter(item => item.isViewable)[0]?.item.id
2023-02-07 13:56:50 +01:00
if (!isFetchingPrev.value && !isRefetching && firstItemId) {
latestMarker.current = firstItemId
updateMarkers()
}
}
}
]
: undefined
)
2021-02-27 16:33:54 +01:00
const androidRefreshControl = Platform.select({
android: {
refreshControl: (
<RefreshControl
enabled
2022-02-12 14:51:01 +01:00
colors={[colors.primaryDefault]}
progressBackgroundColor={colors.backgroundDefault}
2021-02-27 16:33:54 +01:00
refreshing={isFetching || isLoading}
2023-01-08 00:05:58 +01:00
onRefresh={() => {
if (readMarker) {
setAccountStorage([{ key: readMarker, value: undefined }])
}
refetch()
}}
2021-02-27 16:33:54 +01:00
/>
)
}
})
2021-02-13 13:08:34 +01:00
2021-02-27 16:33:54 +01:00
useScrollToTop(flRef)
useGlobalStorageListener('account.active', () =>
flRef.current?.scrollToOffset({ offset: 0, animated: false })
)
2022-01-30 22:51:03 +01:00
2020-12-12 12:49:29 +01:00
return (
2022-06-01 23:13:43 +02:00
<>
<TimelineRefresh
flRef={flRef}
queryKey={queryKey}
2023-01-30 13:40:43 +01:00
isFetchingPrev={isFetchingPrev}
2023-01-30 00:25:46 +01:00
setFetchedCount={setFetchedCount}
2022-06-01 23:13:43 +02:00
scrollY={scrollY}
fetchingType={fetchingType}
disableRefresh={disableRefresh}
readMarker={readMarker}
2022-06-01 23:13:43 +02:00
/>
<AnimatedFlatList
ref={customFLRef || flRef}
scrollEventThrottle={16}
onScroll={onScroll}
windowSize={5}
2022-12-31 00:07:28 +01:00
data={flattenPages(data)}
{...(customProps?.renderItem
? { renderItem: customProps.renderItem }
: { renderItem: ({ item }) => <TimelineDefault item={item} queryKey={queryKey} /> })}
initialNumToRender={3}
maxToRenderPerBatch={3}
onEndReached={() => !disableInfinity && !isFetchingNextPage && fetchNextPage()}
2022-06-01 23:13:43 +02:00
onEndReachedThreshold={0.75}
ListFooterComponent={
<TimelineFooter queryKey={queryKey} disableInfinity={disableInfinity} />
2021-02-27 16:33:54 +01:00
}
2022-06-01 23:13:43 +02:00
ListEmptyComponent={<TimelineEmpty queryKey={queryKey} />}
ItemSeparatorComponent={() => (
<ComponentSeparator
extraMarginLeft={StyleConstants.Avatar.M + StyleConstants.Spacing.S}
/>
)}
viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current}
2023-02-02 14:15:37 +01:00
{...(!isLoading &&
!isFetching && {
maintainVisibleContentPosition: {
minIndexForVisible: 0
}
})}
2022-06-01 23:13:43 +02:00
{...androidRefreshControl}
{...customProps}
/>
2023-01-30 00:25:46 +01:00
{!disableRefresh ? (
<Animated.View
style={[
{
position: 'absolute',
alignSelf: 'center',
top: -fetchedNoticeHeight.value - 16,
paddingVertical: StyleConstants.Spacing.S,
paddingHorizontal: StyleConstants.Spacing.M,
backgroundColor: colors.backgroundDefault,
shadowColor: colors.primaryDefault,
shadowOffset: { width: 0, height: 0 },
shadowOpacity: theme === 'light' ? 0.16 : 0.24,
borderRadius: 99,
justifyContent: 'center',
alignItems: 'center'
},
fetchedNoticeAnimate
]}
onLayout={({
nativeEvent: {
layout: { height }
}
}) => (fetchedNoticeHeight.value = height)}
>
<CustomText
2023-01-30 13:40:43 +01:00
fontStyle='S'
2023-01-30 00:25:46 +01:00
style={{ color: colors.primaryDefault }}
children={
fetchedCount !== null
? fetchedCount > 0
? t('refresh.fetched.found', { count: fetchedCount })
: t('refresh.fetched.none')
: t('refresh.fetching')
}
/>
</Animated.View>
) : null}
2022-06-01 23:13:43 +02:00
</>
2020-12-12 12:49:29 +01:00
)
2020-10-23 09:22:17 +02:00
}
2020-10-31 21:04:46 +01:00
export default Timeline