Better lookback update

This commit is contained in:
Zhiyuan Zheng 2022-01-30 22:51:03 +01:00
parent 45ba984ea3
commit bd49caa52a
13 changed files with 116 additions and 106 deletions

View File

@ -3,7 +3,7 @@
"versions": {
"native": "220102",
"major": 3,
"minor": 1,
"minor": 2,
"patch": 0,
"expo": "44.0.0"
},

View File

@ -9,6 +9,7 @@ import ScreenAnnouncements from '@screens/Announcements'
import ScreenCompose from '@screens/Compose'
import ScreenImagesViewer from '@screens/ImagesViewer'
import ScreenTabs from '@screens/Tabs'
import initQuery from '@utils/initQuery'
import { RootStackParamList } from '@utils/navigation/navigators'
import pushUseConnect from '@utils/push/useConnect'
import pushUseReceive from '@utils/push/useReceive'
@ -17,11 +18,7 @@ import { updatePreviousTab } from '@utils/slices/contextsSlice'
import { updateAccountPreferences } from '@utils/slices/instances/updateAccountPreferences'
import { updateConfiguration } from '@utils/slices/instances/updateConfiguration'
import { updateFilters } from '@utils/slices/instances/updateFilters'
import {
getInstanceActive,
getInstances,
updateInstanceActive
} from '@utils/slices/instancesSlice'
import { getInstanceActive, getInstances } from '@utils/slices/instancesSlice'
import { useTheme } from '@utils/styles/ThemeManager'
import { themes } from '@utils/styles/themes'
import * as Analytics from 'expo-firebase-analytics'
@ -76,9 +73,9 @@ const Screens: React.FC<Props> = ({ localCorrupt }) => {
(prev, next) => prev.length === next.length
)
const queryClient = useQueryClient()
pushUseConnect({ mode, t, instances, dispatch })
pushUseReceive({ queryClient, instances })
pushUseRespond({ queryClient, instances, dispatch })
pushUseConnect({ t, instances })
pushUseReceive({ instances })
pushUseRespond({ instances })
// Prevent screenshot alert
useEffect(() => {
@ -165,8 +162,10 @@ const Screens: React.FC<Props> = ({ localCorrupt }) => {
instance => paths[0] === `@${instance.account.acct}@${instance.uri}`
)
if (instanceIndex !== -1 && instanceActive !== instanceIndex) {
dispatch(updateInstanceActive(instances[instanceIndex]))
queryClient.clear()
initQuery({
instance: instances[instanceIndex],
prefetch: { enabled: true }
})
}
}
}

View File

@ -48,9 +48,6 @@ const Timeline: React.FC<Props> = ({
lookback,
customProps
}) => {
// Switching account update timeline
useSelector(getInstanceActive)
const { theme } = useTheme()
const {
@ -152,6 +149,13 @@ const Timeline: React.FC<Props> = ({
])
useScrollToTop(flRef)
useSelector(getInstanceActive, (prev, next) => {
if (prev !== next) {
flRef.current?.scrollToOffset({ offset: 0, animated: false })
}
return prev === next
})
return (
<>
<TimelineRefresh
@ -162,7 +166,6 @@ const Timeline: React.FC<Props> = ({
disableRefresh={disableRefresh}
/>
<AnimatedFlatList
// @ts-ignore
ref={customFLRef || flRef}
scrollEventThrottle={16}
onScroll={onScroll}

View File

@ -8,7 +8,6 @@ import {
RootStackScreenProps
} from '@utils/navigation/navigators'
import { useTheme } from '@utils/styles/ThemeManager'
import { findIndex } from 'lodash'
import React, { RefObject, useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Platform, Share, StatusBar, View } from 'react-native'
@ -120,7 +119,7 @@ const ScreenImagesViewer = ({
const { mode } = useTheme()
const initialIndex = findIndex(imageUrls, ['id', id])
const initialIndex = imageUrls.findIndex(image => image.id === id)
const [currentIndex, setCurrentIndex] = useState(initialIndex)
const messageRef = useRef<FlashMessage>(null)

View File

@ -3,11 +3,11 @@ import Button from '@components/Button'
import haptics from '@components/haptics'
import ComponentInstance from '@components/Instance'
import { useNavigation } from '@react-navigation/native'
import initQuery from '@utils/initQuery'
import {
getInstanceActive,
getInstances,
Instance,
updateInstanceActive
Instance
} from '@utils/slices/instancesSlice'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
@ -21,8 +21,7 @@ import {
View
} from 'react-native'
import { ScrollView } from 'react-native-gesture-handler'
import { useQueryClient } from 'react-query'
import { useDispatch, useSelector } from 'react-redux'
import { useSelector } from 'react-redux'
interface Props {
instance: Instance
@ -30,9 +29,7 @@ interface Props {
}
const AccountButton: React.FC<Props> = ({ instance, selected = false }) => {
const queryClient = useQueryClient()
const navigation = useNavigation()
const dispatch = useDispatch()
return (
<Button
@ -45,8 +42,7 @@ const AccountButton: React.FC<Props> = ({ instance, selected = false }) => {
onPress={() => {
haptics('Light')
analytics('switch_existing_press')
dispatch(updateInstanceActive(instance))
queryClient.clear()
initQuery({ instance, prefetch: { enabled: true } })
navigation.goBack()
}}
/>

View File

@ -3,7 +3,6 @@ import TimelineDefault from '@components/Timeline/Default'
import { useNavigation } from '@react-navigation/native'
import { TabSharedStackScreenProps } from '@utils/navigation/navigators'
import { QueryKeyTimeline } from '@utils/queryHooks/timeline'
import { findIndex } from 'lodash'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { FlatList } from 'react-native'
import { InfiniteQueryObserver, useQueryClient } from 'react-query'
@ -40,7 +39,7 @@ const TabSharedToot: React.FC<TabSharedStackScreenProps<'Tab-Shared-Toot'>> = ({
}
if (!scrolled.current) {
scrolled.current = true
const pointer = findIndex(flattenData, ['id', toot.id])
const pointer = flattenData.findIndex(({ id }) => id === toot.id)
try {
pointer < flattenData.length &&
setTimeout(() => {

View File

@ -1,7 +1,7 @@
import apiInstance from '@api/instance'
import NetInfo from '@react-native-community/netinfo'
import { store } from '@root/store'
import { prefetchTimelineQuery } from '@utils/queryHooks/timeline'
import initQuery from '@utils/initQuery'
import { getPreviousTab } from '@utils/slices/contextsSlice'
import removeInstance from '@utils/slices/instances/remove'
import {
@ -62,43 +62,19 @@ const netInfo = async (): Promise<{
if (instance.timelinesLookback) {
const previousTab = getPreviousTab(store.getState())
let loadPage: Extract<
App.Pages,
'Following' | 'Local' | 'LocalPublic'
> | void = undefined
let loadPage:
| Extract<App.Pages, 'Following' | 'Local' | 'LocalPublic'>
| undefined = undefined
if (previousTab === 'Tab-Local') {
loadPage = 'Following'
} else if (previousTab === 'Tab-Public') {
loadPage = 'LocalPublic'
}
if (loadPage) {
if (instance.timelinesLookback?.[loadPage]?.ids.length > 0) {
log(
'log',
'netInfo',
`prefetching landing page ${instance.timelinesLookback[loadPage].queryKey[1].page} ids: ${instance.timelinesLookback[loadPage].ids}`
)
const prefetch = await prefetchTimelineQuery(
instance.timelinesLookback[loadPage]
)
if (prefetch) {
log('log', 'netInfo', `prefetched from status id ${prefetch}`)
} else {
log('error', 'netInfo', 'failed to prefetch')
}
}
}
for (const page of Object.keys(instance.timelinesLookback)) {
if (page !== loadPage) {
log(
'log',
'netInfo',
`prefetching other page ${instance.timelinesLookback[page].queryKey[1].page} ids: ${instance.timelinesLookback[page].ids}`
)
prefetchTimelineQuery(instance.timelinesLookback[page])
}
}
await initQuery({
instance,
prefetch: { enabled: true, page: loadPage }
})
}
return Promise.resolve({ connected: true })

32
src/utils/initQuery.ts Normal file
View File

@ -0,0 +1,32 @@
import queryClient from '@helpers/queryClient'
import { store } from '@root/store'
import { prefetchTimelineQuery } from './queryHooks/timeline'
import { Instance, updateInstanceActive } from './slices/instancesSlice'
const initQuery = async ({
instance,
prefetch
}: {
instance: Instance
prefetch?: { enabled: boolean; page?: 'Following' | 'LocalPublic' }
}) => {
store.dispatch(updateInstanceActive(instance))
await queryClient.resetQueries()
if (prefetch?.enabled && instance.timelinesLookback) {
if (
prefetch.page &&
instance.timelinesLookback[prefetch.page]?.ids?.length > 0
) {
await prefetchTimelineQuery(instance.timelinesLookback[prefetch.page])
}
for (const page of Object.keys(instance.timelinesLookback)) {
if (page !== prefetch.page) {
prefetchTimelineQuery(instance.timelinesLookback[page])
}
}
}
}
export default initQuery

View File

@ -2,30 +2,32 @@ import apiGeneral from '@api/general'
import apiTooot from '@api/tooot'
import { displayMessage } from '@components/Message'
import navigationRef from '@helpers/navigationRef'
import { Dispatch } from '@reduxjs/toolkit'
import { isDevelopment } from '@utils/checkEnvironment'
import { disableAllPushes, Instance } from '@utils/slices/instancesSlice'
import { useTheme } from '@utils/styles/ThemeManager'
import * as Notifications from 'expo-notifications'
import { useEffect } from 'react'
import { TFunction } from 'react-i18next'
import { useDispatch } from 'react-redux'
export interface Params {
mode: 'light' | 'dark'
t: TFunction<'screens'>
instances: Instance[]
dispatch: Dispatch<any>
}
const pushUseConnect = ({ mode, t, instances, dispatch }: Params) => {
const pushUseConnect = ({ t, instances }: Params) => {
const dispatch = useDispatch()
const { mode } = useTheme()
return useEffect(() => {
const connect = async () => {
const expoToken = isDevelopment
? 'DEVELOPMENT_TOKEN_1'
: (
await Notifications.getExpoPushTokenAsync({
experienceId: '@xmflsct/tooot'
})
).data
? 'DEVELOPMENT_TOKEN_1'
: (
await Notifications.getExpoPushTokenAsync({
experienceId: '@xmflsct/tooot'
})
).data
apiTooot({
method: 'get',

View File

@ -1,19 +1,18 @@
import { displayMessage } from '@components/Message'
import queryClient from '@helpers/queryClient'
import initQuery from '@utils/initQuery'
import { QueryKeyTimeline } from '@utils/queryHooks/timeline'
import { Instance, updateInstanceActive } from '@utils/slices/instancesSlice'
import * as Notifications from 'expo-notifications'
import { findIndex } from 'lodash'
import { useEffect } from 'react'
import { QueryClient } from 'react-query'
import { useDispatch } from 'react-redux'
import pushUseNavigate from './useNavigate'
export interface Params {
queryClient: QueryClient
instances: Instance[]
}
const pushUseReceive = ({ queryClient, instances }: Params) => {
const pushUseReceive = ({ instances }: Params) => {
const dispatch = useDispatch()
return useEffect(() => {
@ -30,8 +29,7 @@ const pushUseReceive = ({ queryClient, instances }: Params) => {
accountId: string
}
const notificationIndex = findIndex(
instances,
const notificationIndex = instances.findIndex(
instance =>
instance.url === payloadData.instanceUrl &&
instance.account.id === payloadData.accountId
@ -42,8 +40,10 @@ const pushUseReceive = ({ queryClient, instances }: Params) => {
description: notification.request.content.body!,
onPress: () => {
if (notificationIndex !== -1) {
dispatch(updateInstanceActive(instances[notificationIndex]))
queryClient.clear()
initQuery({
instance: instances[notificationIndex],
prefetch: { enabled: true }
})
}
pushUseNavigate(payloadData.notification_id)
}

View File

@ -1,19 +1,19 @@
import { Dispatch } from '@reduxjs/toolkit'
import queryClient from '@helpers/queryClient'
import initQuery from '@utils/initQuery'
import { QueryKeyTimeline } from '@utils/queryHooks/timeline'
import { Instance, updateInstanceActive } from '@utils/slices/instancesSlice'
import { Instance } from '@utils/slices/instancesSlice'
import * as Notifications from 'expo-notifications'
import { findIndex } from 'lodash'
import { useEffect } from 'react'
import { QueryClient } from 'react-query'
import { useDispatch } from 'react-redux'
import pushUseNavigate from './useNavigate'
export interface Params {
queryClient: QueryClient
instances: Instance[]
dispatch: Dispatch<any>
}
const pushUseRespond = ({ queryClient, instances, dispatch }: Params) => {
const pushUseRespond = ({ instances }: Params) => {
const dispatch = useDispatch()
return useEffect(() => {
const subscription = Notifications.addNotificationResponseReceivedListener(
({ notification }) => {
@ -28,15 +28,16 @@ const pushUseRespond = ({ queryClient, instances, dispatch }: Params) => {
accountId: string
}
const notificationIndex = findIndex(
instances,
const notificationIndex = instances.findIndex(
instance =>
instance.url === payloadData.instanceUrl &&
instance.account.id === payloadData.accountId
)
if (notificationIndex !== -1) {
dispatch(updateInstanceActive(instances[notificationIndex]))
queryClient.clear()
initQuery({
instance: instances[notificationIndex],
prefetch: { enabled: true }
})
}
pushUseNavigate(payloadData.notification_id)
}

View File

@ -1,5 +1,4 @@
import queryClient from '@helpers/queryClient'
import { findIndex } from 'lodash'
import { InfiniteData } from 'react-query'
import {
MutationVarsTimelineUpdateStatusProperty,
@ -37,7 +36,9 @@ const updateStatusProperty = ({
'boolean'
) {
const items = page.body as Mastodon.Conversation[]
const tootIndex = findIndex(items, ['last_status.id', id])
const tootIndex = items.findIndex(
({ last_status }) => last_status?.id === id
)
if (tootIndex >= 0) {
foundToot = true
updateConversation({ item: items[tootIndex], payload })
@ -47,17 +48,18 @@ const updateStatusProperty = ({
typeof (page.body as Mastodon.Notification[])[0].type === 'string'
) {
const items = page.body as Mastodon.Notification[]
const tootIndex = findIndex(items, ['status.id', id])
const tootIndex = items.findIndex(
({ status }) => status?.id === id
)
if (tootIndex >= 0) {
foundToot = true
updateNotification({ item: items[tootIndex], payload })
}
} else {
const items = page.body as Mastodon.Status[]
const tootIndex = findIndex(items, [
reblog ? 'reblog.id' : 'id',
id
])
const tootIndex = reblog
? items.findIndex(({ reblog }) => reblog?.id === id)
: items.findIndex(toot => toot.id === id)
// if favouriets page and notifications page, remove the item instead
if (tootIndex >= 0) {
foundToot = true
@ -90,7 +92,9 @@ const updateStatusProperty = ({
'boolean'
) {
const items = page.body as Mastodon.Conversation[]
const tootIndex = findIndex(items, ['last_status.id', id])
const tootIndex = items.findIndex(
({ last_status }) => last_status?.id === id
)
if (tootIndex >= 0) {
foundToot = true
updateConversation({ item: items[tootIndex], payload })
@ -101,17 +105,18 @@ const updateStatusProperty = ({
'string'
) {
const items = page.body as Mastodon.Notification[]
const tootIndex = findIndex(items, ['status.id', id])
const tootIndex = items.findIndex(
({ status }) => status?.id === id
)
if (tootIndex >= 0) {
foundToot = true
updateNotification({ item: items[tootIndex], payload })
}
} else {
const items = page.body as Mastodon.Status[]
const tootIndex = findIndex(items, [
reblog ? 'reblog.id' : 'id',
id
])
const tootIndex = reblog
? items.findIndex(({ reblog }) => reblog?.id === id)
: items.findIndex(toot => toot.id === id)
// if favouriets page and notifications page, remove the item instead
if (tootIndex >= 0) {
foundToot = true

View File

@ -3,7 +3,6 @@ import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { RootState } from '@root/store'
import { ComposeStateDraft } from '@screens/Compose/utils/types'
import { QueryKeyTimeline } from '@utils/queryHooks/timeline'
import { findIndex } from 'lodash'
import addInstance from './instances/add'
import removeInstance from './instances/remove'
import { updateAccountPreferences } from './instances/updateAccountPreferences'
@ -130,10 +129,9 @@ const instancesSlice = createSlice({
action: PayloadAction<ComposeStateDraft>
) => {
const activeIndex = findInstanceActive(instances)
const draftIndex = findIndex(instances[activeIndex].drafts, [
'timestamp',
action.payload.timestamp
])
const draftIndex = instances[activeIndex].drafts.findIndex(
({ timestamp }) => timestamp === action.payload.timestamp
)
if (draftIndex === -1) {
instances[activeIndex].drafts.unshift(action.payload)
} else {