Early demo of #638

Actions are not working yet
This commit is contained in:
xmflsct 2022-12-31 15:53:02 +01:00
parent eb385b8872
commit 13303c4269
5 changed files with 221 additions and 102 deletions

View File

@ -37,6 +37,7 @@ export interface Props {
disableDetails?: boolean
disableOnPress?: boolean
isConversation?: boolean
isRemote?: boolean
}
// When the poll is long
@ -47,7 +48,8 @@ const TimelineDefault: React.FC<Props> = ({
highlighted = false,
disableDetails = false,
disableOnPress = false,
isConversation = false
isConversation = false,
isRemote = false
}) => {
const status = item.reblog ? item.reblog : item
const rawContent = useRef<string[]>([])
@ -175,7 +177,8 @@ const TimelineDefault: React.FC<Props> = ({
inThread: queryKey?.[1].page === 'Toot',
disableDetails,
disableOnPress,
isConversation
isConversation,
isRemote
}}
>
{disableOnPress ? (

View File

@ -21,6 +21,7 @@ type StatusContextType = {
disableDetails?: boolean
disableOnPress?: boolean
isConversation?: boolean
isRemote?: boolean
}
const StatusContext = createContext<StatusContextType>({} as StatusContextType)

View File

@ -17,7 +17,7 @@ import HeaderSharedReplies from './HeaderShared/Replies'
import HeaderSharedVisibility from './HeaderShared/Visibility'
const TimelineHeaderDefault: React.FC = () => {
const { queryKey, rootQueryKey, status, highlighted, disableDetails, rawContent } =
const { queryKey, rootQueryKey, status, highlighted, disableDetails, rawContent, isRemote } =
useContext(StatusContext)
if (!status) return null
@ -58,6 +58,14 @@ const TimelineHeaderDefault: React.FC = () => {
: { marginTop: StyleConstants.Spacing.XS, marginBottom: StyleConstants.Spacing.S })
}}
>
{isRemote ? (
<Icon
name='Wifi'
size={StyleConstants.Font.Size.M}
color={colors.secondary}
style={{ marginRight: StyleConstants.Spacing.S }}
/>
) : null}
<HeaderSharedCreated
created_at={status.created_at}
edited_at={status.edited_at}

View File

@ -4,11 +4,14 @@ import Icon from '@components/Icon'
import ComponentSeparator from '@components/Separator'
import CustomText from '@components/Text'
import TimelineDefault from '@components/Timeline/Default'
import { useQuery } from '@tanstack/react-query'
import apiGeneral from '@utils/api/general'
import apiInstance from '@utils/api/instance'
import { getHost } from '@utils/helpers/urlMatcher'
import { TabSharedStackScreenProps } from '@utils/navigation/navigators'
import { QueryKeyTimeline, useTootQuery } from '@utils/queryHooks/timeline'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import React, { useEffect, useRef } from 'react'
import React, { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { FlatList, View } from 'react-native'
import { Circle } from 'react-native-animated-spinkit'
@ -23,54 +26,204 @@ const TabSharedToot: React.FC<TabSharedStackScreenProps<'Tab-Shared-Toot'>> = ({
const { colors } = useTheme()
const { t } = useTranslation(['componentTimeline', 'screenTabs'])
const [hasRemoteContent, setHasRemoteContent] = useState<boolean>(false)
useEffect(() => {
navigation.setOptions({
title: t('screenTabs:shared.toot.name'),
headerTitle: () => (
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
{hasRemoteContent ? (
<Icon
name='Wifi'
size={StyleConstants.Font.Size.M}
color={colors.primaryDefault}
style={{ marginRight: StyleConstants.Spacing.S }}
/>
) : null}
<CustomText
style={{ color: colors.primaryDefault }}
fontSize='L'
fontWeight='Bold'
numberOfLines={1}
children={t('screenTabs:shared.toot.name')}
/>
</View>
),
headerLeft: () => <HeaderLeft onPress={() => navigation.goBack()} />
})
}, [])
}, [hasRemoteContent])
const flRef = useRef<FlatList>(null)
const scrolled = useRef(false)
const queryKey: QueryKeyTimeline = ['Timeline', { page: 'Toot', toot: toot.id }]
const { data, status, refetch } = useTootQuery({
...queryKey[1],
options: {
meta: { toot },
const finalData = useRef<(Mastodon.Status & { _level?: number; _remote?: boolean })[]>([
{ ...toot, _level: 0, _remote: false }
])
const highlightIndex = useRef<number>(0)
const queryLocal = useQuery(
['Timeline', { page: 'Toot', toot: toot.id, remote: false }],
async () => {
const context = await apiInstance<{
ancestors: Mastodon.Status[]
descendants: Mastodon.Status[]
}>({
method: 'get',
url: `statuses/${toot.id}/context`
})
const statuses: (Mastodon.Status & { _level?: number })[] = [
...context.body.ancestors,
toot,
...context.body.descendants
]
const highlight = context.body.ancestors.length
highlightIndex.current = highlight
for (const [index, status] of statuses.entries()) {
if (index < highlight || status.id === toot.id) {
statuses[index]._level = 0
continue
}
const repliedLevel = statuses.find(s => s.id === status.in_reply_to_id)?._level
statuses[index]._level = (repliedLevel || 0) + 1
}
return { pages: [{ body: statuses }] }
},
{
staleTime: 0,
refetchOnMount: true,
onSuccess: data => {
if (data.pages[0].body.length < 1) {
navigation.goBack()
return
}
if (!scrolled.current) {
scrolled.current = true
const pointer = data.pages[0].body.findIndex(({ id }) => id === toot.id)
if (pointer < 1) return
const length = flRef.current?.props.data?.length
if (!length) return
try {
setTimeout(() => {
try {
flRef.current?.scrollToIndex({
index: pointer,
viewOffset: 100
})
} catch {}
}, 500)
} catch (error) {
return
if (finalData.current.length < data.pages[0].body.length) {
// if the remote has been loaded first
finalData.current = data.pages[0].body
if (!scrolled.current) {
scrolled.current = true
const pointer = data.pages[0].body.findIndex(({ id }) => id === toot.id)
if (pointer < 1) return
const length = flRef.current?.props.data?.length
if (!length) return
try {
setTimeout(() => {
try {
flRef.current?.scrollToIndex({
index: pointer,
viewOffset: 100
})
} catch {}
}, 500)
} catch (error) {
return
}
}
}
}
}
})
)
useQuery(
['Timeline', { page: 'Toot', toot: toot.id, remote: true }],
async () => {
let context:
| {
ancestors: Mastodon.Status[]
descendants: Mastodon.Status[]
}
| undefined
try {
const domain = getHost(toot.url || toot.uri)
if (!domain?.length) {
throw new Error()
}
const id = (toot.url || toot.uri).match(new RegExp(/\/([0-9]+)$/))?.[1]
if (!id?.length) {
throw new Error()
}
context = await apiGeneral<{
ancestors: Mastodon.Status[]
descendants: Mastodon.Status[]
}>({
method: 'get',
domain,
url: `api/v1/statuses/${id}/context`
}).then(res => res.body)
} catch {}
if (!context) {
throw new Error()
}
const statuses: (Mastodon.Status & { _level?: number })[] = [
...context.ancestors,
toot,
...context.descendants
]
const highlight = context.ancestors.length
highlightIndex.current = highlight
for (const [index, status] of statuses.entries()) {
if (index < highlight || status.id === toot.id) {
statuses[index]._level = 0
continue
}
const repliedLevel = statuses.find(s => s.id === status.in_reply_to_id)?._level
statuses[index]._level = (repliedLevel || 0) + 1
}
return { pages: [{ body: statuses }] }
},
{
enabled: toot.account.acct !== toot.account.username, // When on the same instance, these two values are the same
staleTime: 0,
refetchOnMount: false,
onSuccess: data => {
if (finalData.current.length < 1 && data.pages[0].body.length < 1) {
navigation.goBack()
return
}
if (finalData.current?.length < data.pages[0].body.length) {
finalData.current = data.pages[0].body.map(remote => {
const localMatch = finalData.current?.find(local => local.uri === remote.uri)
return localMatch ? { ...localMatch, _remote: false } : { ...remote, _remote: true }
})
setHasRemoteContent(true)
}
scrolled.current = true
const pointer = data.pages[0].body.findIndex(({ id }) => id === toot.id)
if (pointer < 1) return
const length = flRef.current?.props.data?.length
if (!length) return
try {
setTimeout(() => {
try {
flRef.current?.scrollToIndex({
index: pointer,
viewOffset: 100
})
} catch {}
}, 500)
} catch (error) {
return
}
}
}
)
const empty = () => {
switch (status) {
case 'loading':
return <Circle size={StyleConstants.Font.Size.L} color={colors.secondary} />
switch (queryLocal.status) {
case 'error':
return (
<>
@ -88,7 +241,7 @@ const TabSharedToot: React.FC<TabSharedStackScreenProps<'Tab-Shared-Toot'>> = ({
<Button
type='text'
content={t('componentTimeline:empty.error.button')}
onPress={() => refetch()}
onPress={() => queryLocal.refetch()}
/>
</>
)
@ -124,17 +277,17 @@ const TabSharedToot: React.FC<TabSharedStackScreenProps<'Tab-Shared-Toot'>> = ({
ref={flRef}
scrollEventThrottle={16}
windowSize={7}
data={data?.pages[0].body}
data={finalData.current}
renderItem={({ item, index }) => {
const prev = data?.pages[0].body[index - 1]?._level || 0
const prev = finalData.current?.[index - 1]?._level || 0
const curr = item._level
const next = data?.pages[0].body[index + 1]?._level || 0
const next = finalData.current?.[index + 1]?._level || 0
return (
<View
style={{
paddingLeft:
index > (data?.highlightIndex || 0)
index > highlightIndex.current
? Math.min(item._level - 1, MAX_LEVEL) * StyleConstants.Spacing.S
: undefined
}}
@ -146,10 +299,11 @@ const TabSharedToot: React.FC<TabSharedStackScreenProps<'Tab-Shared-Toot'>> = ({
>
<TimelineDefault
item={item}
queryKey={queryKey}
queryKey={['Timeline', { page: 'Toot', toot: toot.id }]}
rootQueryKey={rootQueryKey}
highlighted={toot.id === item.id}
isConversation={toot.id !== item.id}
isRemote={item._remote}
/>
{curr > 1 || next > 1
? [...new Array(curr)].map((_, i) => {
@ -283,7 +437,7 @@ const TabSharedToot: React.FC<TabSharedStackScreenProps<'Tab-Shared-Toot'>> = ({
const offset = error.averageItemLength * error.index
flRef.current?.scrollToOffset({ offset })
try {
error.index < (data?.pages[0].body.length || 0) &&
error.index < (finalData.current.length || 0) &&
setTimeout(
() =>
flRef.current?.scrollToIndex({
@ -307,6 +461,20 @@ const TabSharedToot: React.FC<TabSharedStackScreenProps<'Tab-Shared-Toot'>> = ({
{empty()}
</View>
}
ListFooterComponent={
<View
style={{
flex: 1,
alignItems: 'center',
backgroundColor: colors.backgroundDefault,
marginHorizontal: StyleConstants.Spacing.M
}}
>
{queryLocal.isFetching ? (
<Circle size={StyleConstants.Font.Size.L} color={colors.secondary} />
) : null}
</View>
}
/>
)
}

View File

@ -19,67 +19,6 @@ import deleteItem from './timeline/deleteItem'
import editItem from './timeline/editItem'
import updateStatusProperty from './timeline/updateStatusProperty'
const queryFunctionToot = async ({ queryKey, meta }: QueryFunctionContext<QueryKeyTimeline>) => {
// @ts-ignore
const id = queryKey[1].toot
const target =
(meta?.toot as Mastodon.Status) ||
undefined ||
(await apiInstance<Mastodon.Status>({
method: 'get',
url: `statuses/${id}`
}).then(res => res.body))
const context = await apiInstance<{
ancestors: Mastodon.Status[]
descendants: Mastodon.Status[]
}>({
method: 'get',
url: `statuses/${id}/context`
})
const statuses: (Mastodon.Status & { _level?: number })[] = [
...context.body.ancestors,
target,
...context.body.descendants
]
const highlightIndex = context.body.ancestors.length
for (const [index, status] of statuses.entries()) {
if (index < highlightIndex || status.id === id) {
statuses[index]._level = 0
continue
}
const repliedLevel = statuses.find(s => s.id === status.in_reply_to_id)?._level
statuses[index]._level = (repliedLevel || 0) + 1
}
return { pages: [{ body: statuses }], highlightIndex }
}
const useTootQuery = ({
options,
...queryKeyParams
}: QueryKeyTimeline[1] & {
options?: UseQueryOptions<
{
pages: { body: (Mastodon.Status & { _level: number })[] }[]
highlightIndex: number
},
AxiosError
>
}) => {
const queryKey: QueryKeyTimeline = ['Timeline', { ...queryKeyParams }]
return useQuery(queryKey, queryFunctionToot, {
staleTime: 0,
refetchOnMount: true,
...options
})
}
/* ----- */
export type QueryKeyTimeline = [
'Timeline',
(
@ -501,4 +440,4 @@ const useTimelineMutation = ({
})
}
export { useTootQuery, useTimelineQuery, useTimelineMutation }
export { useTimelineQuery, useTimelineMutation }