1
0
mirror of https://github.com/tooot-app/app synced 2025-06-05 22:19:13 +02:00
Use websocket to constantly fetch new notifications. Also use flatlist item view to clear notification.
This commit is contained in:
Zhiyuan Zheng
2021-02-08 23:19:55 +01:00
parent 01d4e6a5b9
commit f5414412d4
22 changed files with 576 additions and 436 deletions

View File

@ -65,7 +65,7 @@ const InstanceAuth = React.memo(
localAddInstance({
url: instanceDomain,
token: accessToken,
uri: instance.uri,
instance,
max_toot_chars: instance.max_toot_chars,
appData
})

View File

@ -15,6 +15,7 @@ const ComponentSeparator = React.memo(
return (
<View
style={{
backgroundColor: theme.background,
borderTopColor: theme.border,
borderTopWidth: StyleSheet.hairlineWidth,
marginLeft:

View File

@ -1,104 +0,0 @@
import { HeaderRight } from '@components/Header'
import Timeline from '@components/Timelines/Timeline'
import SegmentedControl from '@react-native-community/segmented-control'
import { useNavigation } from '@react-navigation/native'
import sharedScreens from '@screens/Tabs/Shared/sharedScreens'
import { getLocalActiveIndex } from '@utils/slices/instancesSlice'
import { useTheme } from '@utils/styles/ThemeManager'
import React, { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Dimensions, StyleSheet } from 'react-native'
import { createNativeStackNavigator } from 'react-native-screens/native-stack'
import { TabView } from 'react-native-tab-view'
import ViewPagerAdapter from 'react-native-tab-view-viewpager-adapter'
import { useSelector } from 'react-redux'
import analytics from './analytics'
const Stack = createNativeStackNavigator<Nav.TabPublicStackParamList>()
const Timelines: React.FC = () => {
const { t, i18n } = useTranslation()
const pages: { title: string; page: App.Pages }[] = [
{ title: t('public:heading.segments.left'), page: 'LocalPublic' },
{ title: t('public:heading.segments.right'), page: 'Local' }
]
const navigation = useNavigation()
const localActiveIndex = useSelector(getLocalActiveIndex)
const onPressSearch = useCallback(() => {
analytics('search_tap', { page: pages[segment].page })
navigation.navigate('Tab-Public', { screen: 'Tab-Shared-Search' })
}, [])
const routes = pages.map(p => ({ key: p.page }))
const renderScene = useCallback(
({
route
}: {
route: {
key: App.Pages
}
}) => {
return localActiveIndex !== null && <Timeline page={route.key} />
},
[localActiveIndex]
)
const { mode } = useTheme()
const [segment, setSegment] = useState(0)
const screenOptions = useMemo(() => {
if (localActiveIndex !== null) {
return {
headerCenter: () => (
<SegmentedControl
appearance={mode}
values={pages.map(p => p.title)}
selectedIndex={segment}
onChange={({ nativeEvent }) =>
setSegment(nativeEvent.selectedSegmentIndex)
}
style={styles.segmentsContainer}
/>
),
headerRight: () => (
<HeaderRight content='Search' onPress={onPressSearch} />
)
}
}
}, [localActiveIndex, mode, segment, i18n.language])
const renderPager = useCallback(props => <ViewPagerAdapter {...props} />, [])
return (
<Stack.Navigator
screenOptions={{ headerHideShadow: true, headerTopInsetEnabled: false }}
>
<Stack.Screen name='Screen-Remote-Root' options={screenOptions}>
{() => (
<TabView
lazy
swipeEnabled
renderPager={renderPager}
renderScene={renderScene}
renderTabBar={() => null}
onIndexChange={index => setSegment(index)}
navigationState={{ index: segment, routes }}
initialLayout={{ width: Dimensions.get('screen').width }}
/>
)}
</Stack.Screen>
{sharedScreens(Stack as any)}
</Stack.Navigator>
)
}
const styles = StyleSheet.create({
segmentsContainer: {
flexBasis: '65%'
}
})
export default React.memo(Timelines, () => true)

View File

@ -1,23 +1,23 @@
import ComponentSeparator from '@components/Separator'
import { useNavigation, useScrollToTop } from '@react-navigation/native'
import { useScrollToTop } from '@react-navigation/native'
import { QueryKeyTimeline, useTimelineQuery } from '@utils/queryHooks/timeline'
import { updateLocalNotification } from '@utils/slices/instancesSlice'
import { StyleConstants } from '@utils/styles/constants'
import { findIndex } from 'lodash'
import React, { useCallback, useEffect, useMemo, useRef } from 'react'
import {
FlatListProps,
Platform,
RefreshControl,
StyleSheet
} from 'react-native'
import { FlatListProps, StyleSheet } from 'react-native'
import { FlatList } from 'react-native-gesture-handler'
import { useDispatch } from 'react-redux'
import Animated, {
useAnimatedStyle,
useSharedValue,
withTiming
} from 'react-native-reanimated'
import { InfiniteData, useQueryClient } from 'react-query'
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'
export interface Props {
page: App.Pages
@ -55,12 +55,25 @@ const Timeline: React.FC<Props> = ({
isSuccess,
isFetching,
isLoading,
hasPreviousPage,
fetchPreviousPage,
isFetchingPreviousPage,
hasNextPage,
fetchNextPage,
isFetchingNextPage
} = useTimelineQuery({
...queryKeyParams,
options: {
getPreviousPageParam: firstPage => {
return Array.isArray(firstPage) && firstPage.length
? {
direction: 'prev',
id: firstPage[0].last_status
? firstPage[0].last_status.id
: firstPage[0].id
}
: undefined
},
getNextPageParam: lastPage => {
return Array.isArray(lastPage) && lastPage.length
? {
@ -76,25 +89,6 @@ const Timeline: React.FC<Props> = ({
const flattenData = data?.pages ? data.pages.flatMap(d => [...d]) : []
// Clear unread notification badge
const dispatch = useDispatch()
const navigation = useNavigation()
useEffect(() => {
const unsubscribe = navigation.addListener('focus', props => {
if (props.target && props.target.includes('Tab-Notifications-Root')) {
if (flattenData.length) {
dispatch(
updateLocalNotification({
latestTime: (flattenData[0] as Mastodon.Notification).created_at
})
)
}
}
})
return unsubscribe
}, [navigation, flattenData])
const flRef = useRef<FlatList<any>>(null)
const scrolled = useRef(false)
useEffect(() => {
@ -122,10 +116,6 @@ const Timeline: React.FC<Props> = ({
<TimelineDefault
item={item}
queryKey={queryKey}
{...(queryKey[1].page === 'RemotePublic' && {
disableDetails: true,
disableOnPress: true
})}
{...(toot === item.id && { highlighted: true })}
/>
)
@ -152,40 +142,27 @@ const Timeline: React.FC<Props> = ({
() => !disableInfinity && !isFetchingNextPage && fetchNextPage(),
[isFetchingNextPage]
)
const ListFooterComponent = useCallback(
const prevId = useSharedValue(null)
const headerPadding = useAnimatedStyle(() => {
if (hasPreviousPage) {
if (isFetchingPreviousPage) {
return { paddingTop: withTiming(StyleConstants.Spacing.XL) }
} else {
return { paddingTop: withTiming(0) }
}
} else {
return { paddingTop: withTiming(0) }
}
}, [hasPreviousPage, isFetchingPreviousPage])
const ListHeaderComponent = useMemo(
() => <Animated.View style={headerPadding} />,
[]
)
const ListFooterComponent = useMemo(
() => <TimelineEnd hasNextPage={!disableInfinity ? hasNextPage : false} />,
[hasNextPage]
)
const isSwipeDown = useRef(false)
const refreshControl = useMemo(
() => (
<RefreshControl
{...(Platform.OS === 'android' && { enabled: true })}
refreshing={
Platform.OS === 'android'
? (isSwipeDown.current && isFetching && !isFetchingNextPage) ||
isLoading
: isSwipeDown.current &&
isFetching &&
!isFetchingNextPage &&
!isLoading
}
onRefresh={() => {
isSwipeDown.current = true
refetch()
}}
/>
),
[isSwipeDown.current, isFetching, isFetchingNextPage, isLoading]
)
useEffect(() => {
if (!isFetching) {
isSwipeDown.current = false
}
}, [isFetching])
const onScrollToIndexFailed = useCallback(error => {
const offset = error.averageItemLength * error.index
flRef.current?.scrollToOffset({ offset })
@ -197,30 +174,68 @@ const Timeline: React.FC<Props> = ({
}, [])
useScrollToTop(flRef)
const queryClient = useQueryClient()
const scrollY = useSharedValue(0)
const onScroll = useCallback(
({ nativeEvent }) => (scrollY.value = nativeEvent.contentOffset.y),
[]
)
const onResponderRelease = useCallback(() => {
if (
scrollY.value <= -StyleConstants.Spacing.XL &&
!isFetchingPreviousPage &&
!disableRefresh
) {
queryClient.setQueryData<InfiniteData<any> | undefined>(
queryKey,
data => {
if (data?.pages[0].length === 0) {
if (data.pages[1]) {
prevId.value = data.pages[1][0].id
}
return {
pages: data.pages.slice(1),
pageParams: data.pageParams.slice(1)
}
} else {
prevId.value = data?.pages[0][0].id
return data
}
}
)
// https://github.com/facebook/react-native/issues/25239#issuecomment-731100372
fetchPreviousPage()
flRef.current?.scrollToOffset({ animated: true, offset: 1 })
}
}, [scrollY.value, isFetchingPreviousPage, disableRefresh])
return (
<FlatList
ref={flRef}
windowSize={8}
data={flattenData}
initialNumToRender={3}
maxToRenderPerBatch={3}
style={styles.flatList}
renderItem={renderItem}
onEndReached={onEndReached}
keyExtractor={keyExtractor}
onEndReachedThreshold={0.75}
ListFooterComponent={ListFooterComponent}
ListEmptyComponent={flItemEmptyComponent}
{...(!disableRefresh && { refreshControl })}
ItemSeparatorComponent={ItemSeparatorComponent}
{...(toot && isSuccess && { onScrollToIndexFailed })}
maintainVisibleContentPosition={{
minIndexForVisible: 0,
autoscrollToTopThreshold: 1
}}
{...customProps}
/>
<>
<TimelineRefresh isLoading={isLoading} disable={disableRefresh} />
<FlatList
onScroll={onScroll}
onResponderRelease={onResponderRelease}
ref={flRef}
windowSize={8}
data={flattenData}
initialNumToRender={3}
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}
/>
</>
)
}

View File

@ -85,6 +85,7 @@ const TimelineAttachment: React.FC<Props> = ({ status }) => {
index={index}
sensitiveShown={sensitiveShown}
video={attachment}
gifv
/>
)
case 'audio':

View File

@ -12,13 +12,15 @@ export interface Props {
index: number
sensitiveShown: boolean
video: Mastodon.AttachmentVideo | Mastodon.AttachmentGifv
gifv?: boolean
}
const AttachmentVideo: React.FC<Props> = ({
total,
index,
sensitiveShown,
video
video,
gifv = false
}) => {
const videoPlayer = useRef<Video>(null)
const [videoLoading, setVideoLoading] = useState(false)
@ -92,7 +94,7 @@ const AttachmentVideo: React.FC<Props> = ({
}}
/>
) : null
) : (
) : gifv ? null : (
<Button
round
overlay