Continue refine remote logic #638

This commit is contained in:
xmflsct 2023-01-03 23:57:23 +01:00
parent b067b9bdb1
commit 0bcd0c1725
46 changed files with 548 additions and 531 deletions

View File

@ -89,7 +89,7 @@
"react-native-tab-view": "^3.3.4",
"react-redux": "^8.0.5",
"rn-placeholder": "^3.0.3",
"valid-url": "^1.0.9",
"url-parse": "^1.5.10",
"zeego": "^1.0.2"
},
"devDependencies": {
@ -104,7 +104,7 @@
"@types/react-dom": "^18.0.10",
"@types/react-native": "^0.70.8",
"@types/react-native-share-menu": "^5.0.2",
"@types/valid-url": "^1.0.3",
"@types/url-parse": "^1",
"babel-plugin-module-resolver": "^4.1.0",
"babel-plugin-transform-remove-console": "^6.9.4",
"chalk": "^4.1.2",

View File

@ -3,8 +3,9 @@ import * as Sentry from '@sentry/react-native'
import { QueryClientProvider } from '@tanstack/react-query'
import AccessibilityManager from '@utils/accessibility/AccessibilityManager'
import getLanguage from '@utils/helpers/getLanguage'
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import audio from '@utils/startup/audio'
import { dev } from '@utils/startup/dev'
import log from '@utils/startup/log'
import netInfo from '@utils/startup/netInfo'
import push from '@utils/startup/push'
@ -34,6 +35,7 @@ Platform.select({
android: LogBox.ignoreLogs(['Setting a timer for a long period of time'])
})
dev()
sentry()
audio()
push()

View File

@ -19,7 +19,6 @@ import {
View
} from 'react-native'
import FastImage from 'react-native-fast-image'
import validUrl from 'valid-url'
import EmojisContext from './Context'
const EmojisList = () => {
@ -68,83 +67,77 @@ const EmojisList = () => {
>
{item.map(emoji => {
const uri = reduceMotionEnabled ? emoji.static_url : emoji.url
if (validUrl.isHttpsUri(uri)) {
return (
<Pressable
key={emoji.shortcode}
onPress={() => {
addEmoji(`:${emoji.shortcode}:`)
return (
<Pressable
key={emoji.shortcode}
onPress={() => {
addEmoji(`:${emoji.shortcode}:`)
const HALF_LIFE = 60 * 60 * 24 * 7 // 1 week
const calculateScore = (
emoji: StorageAccount['emojis_frequent'][number]
): number => {
var seconds = (new Date().getTime() - emoji.lastUsed) / 1000
var score = emoji.count + 1
var order = Math.log(Math.max(score, 1)) / Math.LN10
var sign = score > 0 ? 1 : score === 0 ? 0 : -1
return (sign * order + seconds / HALF_LIFE) * 10
const HALF_LIFE = 60 * 60 * 24 * 7 // 1 week
const calculateScore = (
emoji: StorageAccount['emojis_frequent'][number]
): number => {
var seconds = (new Date().getTime() - emoji.lastUsed) / 1000
var score = emoji.count + 1
var order = Math.log(Math.max(score, 1)) / Math.LN10
var sign = score > 0 ? 1 : score === 0 ? 0 : -1
return (sign * order + seconds / HALF_LIFE) * 10
}
const currentEmojis = getAccountStorage.object('emojis_frequent')
const foundEmojiIndex = currentEmojis?.findIndex(
e => e.emoji.shortcode === emoji.shortcode && e.emoji.url === emoji.url
)
let newEmojisSort: StorageAccount['emojis_frequent']
if (foundEmojiIndex === -1) {
newEmojisSort = currentEmojis || []
const temp = {
emoji,
score: 0,
count: 0,
lastUsed: new Date().getTime()
}
newEmojisSort.push({
...temp,
score: calculateScore(temp),
count: temp.count + 1
})
} else {
newEmojisSort =
currentEmojis
?.map((e, i) =>
i === foundEmojiIndex
? {
...e,
score: calculateScore(e),
count: e.count + 1,
lastUsed: new Date().getTime()
}
: e
)
.sort((a, b) => b.score - a.score) || []
}
const currentEmojis = getAccountStorage.object('emojis_frequent')
const foundEmojiIndex = currentEmojis?.findIndex(
e => e.emoji.shortcode === emoji.shortcode && e.emoji.url === emoji.url
)
let newEmojisSort: StorageAccount['emojis_frequent']
if (foundEmojiIndex === -1) {
newEmojisSort = currentEmojis || []
const temp = {
emoji,
score: 0,
count: 0,
lastUsed: new Date().getTime()
}
newEmojisSort.push({
...temp,
score: calculateScore(temp),
count: temp.count + 1
})
} else {
newEmojisSort =
currentEmojis
?.map((e, i) =>
i === foundEmojiIndex
? {
...e,
score: calculateScore(e),
count: e.count + 1,
lastUsed: new Date().getTime()
}
: e
)
.sort((a, b) => b.score - a.score) || []
setAccountStorage([
{
key: 'emojis_frequent',
value: newEmojisSort.sort((a, b) => b.score - a.score).slice(0, 20)
}
setAccountStorage([
{
key: 'emojis_frequent',
value: newEmojisSort.sort((a, b) => b.score - a.score).slice(0, 20)
}
])
}}
style={{ padding: StyleConstants.Spacing.S }}
>
<FastImage
accessibilityLabel={t('common:customEmoji.accessibilityLabel', {
emoji: emoji.shortcode
})}
accessibilityHint={t(
'screenCompose:content.root.footer.emojis.accessibilityHint'
)}
source={{ uri }}
style={{ width: 32, height: 32 }}
/>
</Pressable>
)
} else {
return null
}
])
}}
style={{ padding: StyleConstants.Spacing.S }}
>
<FastImage
accessibilityLabel={t('common:customEmoji.accessibilityLabel', {
emoji: emoji.shortcode
})}
accessibilityHint={t('screenCompose:content.root.footer.emojis.accessibilityHint')}
source={{ uri }}
style={{ width: 32, height: 32 }}
/>
</Pressable>
)
})}
</View>
)

View File

@ -5,7 +5,7 @@ import apiGeneral from '@utils/api/general'
import browserPackage from '@utils/helpers/browserPackage'
import { featureCheck } from '@utils/helpers/featureCheck'
import { TabMeStackNavigationProp } from '@utils/navigation/navigators'
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { redirectUri, useAppsMutation } from '@utils/queryHooks/apps'
import { useInstanceQuery } from '@utils/queryHooks/instance'
import { storage } from '@utils/storage'
@ -19,7 +19,6 @@ import {
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import * as AuthSession from 'expo-auth-session'
import * as Random from 'expo-random'
import * as WebBrowser from 'expo-web-browser'
import { debounce } from 'lodash'
import React, { RefObject, useCallback, useState } from 'react'
@ -27,7 +26,7 @@ import { Trans, useTranslation } from 'react-i18next'
import { Alert, Image, KeyboardAvoidingView, Platform, TextInput, View } from 'react-native'
import { ScrollView } from 'react-native-gesture-handler'
import { MMKV } from 'react-native-mmkv'
import validUrl from 'valid-url'
import parse from 'url-parse'
import CustomText from '../Text'
export interface Props {
@ -50,7 +49,7 @@ const ComponentInstance: React.FC<Props> = ({
const whitelisted: boolean =
!!domain.length &&
!!errorCode &&
!!validUrl.isHttpsUri(`https://${domain}`) &&
!!(parse(`https://${domain}/`).hostname === domain) &&
errorCode === 401
const instanceQuery = useInstanceQuery({

View File

@ -7,7 +7,6 @@ import { useTheme } from '@utils/styles/ThemeManager'
import React from 'react'
import { Platform, TextStyle } from 'react-native'
import FastImage from 'react-native-fast-image'
import validUrl from 'valid-url'
const regexEmoji = new RegExp(/(:[A-Za-z0-9_]+:)/)
@ -72,23 +71,19 @@ const ParseEmojis: React.FC<Props> = ({
const uri = reduceMotionEnabled
? emojis[emojiIndex].static_url
: emojis[emojiIndex].url
if (validUrl.isHttpsUri(uri)) {
return (
<CustomText key={emojiShortcode + i}>
{i === 0 ? ' ' : undefined}
<FastImage
source={{ uri }}
style={{
width: adaptedFontsize,
height: adaptedFontsize,
transform: [{ translateY: Platform.OS === 'ios' ? -1 : 2 }]
}}
/>
</CustomText>
)
} else {
return null
}
return (
<CustomText key={emojiShortcode + i}>
{i === 0 ? ' ' : undefined}
<FastImage
source={{ uri: uri.trim() }}
style={{
width: adaptedFontsize,
height: adaptedFontsize,
transform: [{ translateY: Platform.OS === 'ios' ? -1 : 2 }]
}}
/>
</CustomText>
)
}
} else {
return <CustomText key={i}>{str}</CustomText>

View File

@ -3,9 +3,10 @@ import GracefullyImage from '@components/GracefullyImage'
import openLink from '@components/openLink'
import CustomText from '@components/Text'
import { useNavigation } from '@react-navigation/native'
import { matchAccount, matchStatus } from '@utils/helpers/urlMatcher'
import { StackNavigationProp } from '@react-navigation/stack'
import { urlMatcher } from '@utils/helpers/urlMatcher'
import { TabLocalStackParamList } from '@utils/navigation/navigators'
import { useAccountQuery } from '@utils/queryHooks/account'
import { useSearchQuery } from '@utils/queryHooks/search'
import { useStatusQuery } from '@utils/queryHooks/status'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
@ -20,97 +21,44 @@ const TimelineCard: React.FC = () => {
if (!status || !status.card) return null
const { colors } = useTheme()
const navigation = useNavigation()
const navigation = useNavigation<StackNavigationProp<TabLocalStackParamList>>()
const [loading, setLoading] = useState(false)
const isStatus = matchStatus(status.card.url)
const match = urlMatcher(status.card.url)
const [foundStatus, setFoundStatus] = useState<Mastodon.Status>()
const isAccount = matchAccount(status.card.url)
const [foundAccount, setFoundAccount] = useState<Mastodon.Account>()
const searchQuery = useSearchQuery({
type: (() => {
if (isStatus) return 'statuses'
if (isAccount) return 'accounts'
})(),
term: (() => {
if (isStatus) {
if (isStatus.sameInstance) {
return
} else {
return status.card.url
}
}
if (isAccount) {
if (isAccount.sameInstance) {
if (isAccount.style === 'default') {
return
} else {
return isAccount.username
}
} else {
return status.card.url
}
}
})(),
limit: 1,
options: { enabled: false }
})
const statusQuery = useStatusQuery({
id: isStatus?.id || '',
status: match?.status ? { ...match.status, uri: status.card.url } : undefined,
options: { enabled: false }
})
useEffect(() => {
if (isStatus) {
if (match?.status) {
setLoading(true)
if (isStatus.sameInstance) {
statusQuery
.refetch()
.then(res => {
res.data && setFoundStatus(res.data)
setLoading(false)
})
.catch(() => setLoading(false))
} else {
searchQuery
.refetch()
.then(res => {
const status = (res.data as any)?.statuses?.[0]
status && setFoundStatus(status)
setLoading(false)
})
.catch(() => setLoading(false))
}
statusQuery
.refetch()
.then(res => {
res.data && setFoundStatus(res.data)
setLoading(false)
})
.catch(() => setLoading(false))
}
}, [])
const accountQuery = useAccountQuery({
account:
isAccount?.style === 'default' ? { id: isAccount.id, url: status.card.url } : undefined,
account: match?.account ? { ...match?.account, url: status.card.url } : undefined,
options: { enabled: false }
})
useEffect(() => {
if (isAccount) {
if (match?.account) {
setLoading(true)
if (isAccount.sameInstance && isAccount.style === 'default') {
accountQuery
.refetch()
.then(res => {
res.data && setFoundAccount(res.data)
setLoading(false)
})
.catch(() => setLoading(false))
} else {
searchQuery
.refetch()
.then(res => {
const account = (res.data as any)?.accounts?.[0]
account && setFoundAccount(account)
setLoading(false)
})
.catch(() => setLoading(false))
}
accountQuery
.refetch()
.then(res => {
res.data && setFoundAccount(res.data)
setLoading(false)
})
.catch(() => setLoading(false))
}
}, [])
@ -129,10 +77,10 @@ const TimelineCard: React.FC = () => {
</View>
)
}
if (isStatus && foundStatus) {
if (match?.status && foundStatus) {
return <TimelineDefault item={foundStatus} disableDetails disableOnPress />
}
if (isAccount && foundAccount) {
if (match?.account && foundAccount) {
return <ComponentAccount account={foundAccount} />
}
return (
@ -198,7 +146,18 @@ const TimelineCard: React.FC = () => {
overflow: 'hidden',
borderColor: colors.border
}}
onPress={async () => status.card && (await openLink(status.card.url, navigation))}
onPress={async () => {
if (match?.status && foundStatus) {
navigation.push('Tab-Shared-Toot', { toot: foundStatus })
return
}
if (match?.account && foundAccount) {
navigation.push('Tab-Shared-Account', { account: foundAccount })
return
}
status.card?.url && (await openLink(status.card.url, navigation))
}}
children={cardContent()}
/>
)

View File

@ -19,7 +19,7 @@ const TimelineFeedback = () => {
const navigation = useNavigation<StackNavigationProp<TabLocalStackParamList>>()
const { data } = useStatusHistory({
id: status.id,
status,
options: { enabled: status.edited_at !== undefined }
})
@ -82,7 +82,7 @@ const TimelineFeedback = () => {
style={[styles.text, { marginRight: 0, color: colors.blue }]}
onPress={() =>
navigation.push('Tab-Shared-History', {
id: status.id,
status,
detectedLanguage: detectedLanguage?.current || status.language || ''
})
}

View File

@ -1,6 +1,6 @@
import CustomText from '@components/Text'
import queryClient from '@utils/queryHooks'
import removeHTML from '@utils/helpers/removeHTML'
import { queryClient } from '@utils/queryHooks'
import { QueryKeyFilters } from '@utils/queryHooks/filters'
import { QueryKeyTimeline } from '@utils/queryHooks/timeline'
import { StyleConstants } from '@utils/styles/constants'

View File

@ -73,13 +73,8 @@ const HeaderConversation = ({ conversation }: Props) => {
marginBottom: StyleConstants.Spacing.S
}}
>
{conversation.last_status?.created_at ? (
<HeaderSharedCreated
created_at={conversation.last_status?.created_at}
edited_at={conversation.last_status?.edited_at}
/>
) : null}
<HeaderSharedMuted muted={conversation.last_status?.muted} />
{conversation.last_status?.created_at ? <HeaderSharedCreated /> : null}
<HeaderSharedMuted />
</View>
</View>

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, isRemote } =
const { queryKey, rootQueryKey, status, disableDetails, rawContent, isRemote } =
useContext(StatusContext)
if (!status) return null
@ -66,15 +66,11 @@ const TimelineHeaderDefault: React.FC = () => {
style={{ marginRight: StyleConstants.Spacing.S }}
/>
) : null}
<HeaderSharedCreated
created_at={status.created_at}
edited_at={status.edited_at}
highlighted={highlighted}
/>
<HeaderSharedVisibility visibility={status.visibility} />
<HeaderSharedMuted muted={status.muted} />
<HeaderSharedCreated />
<HeaderSharedVisibility />
<HeaderSharedMuted />
<HeaderSharedReplies />
<HeaderSharedApplication application={status.application} />
<HeaderSharedApplication />
</View>
</View>

View File

@ -146,15 +146,10 @@ const TimelineHeaderNotification: React.FC<Props> = ({ notification }) => {
marginBottom: StyleConstants.Spacing.S
}}
>
<HeaderSharedCreated
created_at={notification.status?.created_at || notification.created_at}
edited_at={notification.status?.edited_at}
/>
{notification.status?.visibility ? (
<HeaderSharedVisibility visibility={notification.status.visibility} />
) : null}
<HeaderSharedMuted muted={notification.status?.muted} />
<HeaderSharedApplication application={notification.status?.application} />
<HeaderSharedCreated />
{notification.status?.visibility ? <HeaderSharedVisibility /> : null}
<HeaderSharedMuted />
<HeaderSharedApplication />
</View>
</View>

View File

@ -2,32 +2,31 @@ import openLink from '@components/openLink'
import CustomText from '@components/Text'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import React from 'react'
import React, { useContext } from 'react'
import { useTranslation } from 'react-i18next'
import StatusContext from '../Context'
export interface Props {
application?: Mastodon.Application
}
const HeaderSharedApplication: React.FC<Props> = ({ application }) => {
const HeaderSharedApplication: React.FC = () => {
const { status } = useContext(StatusContext)
const { colors } = useTheme()
const { t } = useTranslation('componentTimeline')
return application && application.name !== 'Web' ? (
return status?.application?.name && status.application.name !== 'Web' ? (
<CustomText
fontStyle='S'
accessibilityRole='link'
onPress={async () => {
application.website && (await openLink(application.website))
status.application?.website && (await openLink(status.application.website))
}}
style={{
flex: 1,
marginLeft: StyleConstants.Spacing.S,
color: colors.secondary
}}
numberOfLines={1}
>
{t('shared.header.shared.application', {
application: application.name
application: status.application.name
})}
</CustomText>
) : null

View File

@ -3,21 +3,23 @@ import RelativeTime from '@components/RelativeTime'
import CustomText from '@components/Text'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import React from 'react'
import React, { useContext } from 'react'
import { useTranslation } from 'react-i18next'
import { FormattedDate } from 'react-intl'
import StatusContext from '../Context'
export interface Props {
created_at: Mastodon.Status['created_at'] | number
edited_at?: Mastodon.Status['edited_at']
highlighted?: boolean
created_at?: Mastodon.Status['created_at'] | number
}
const HeaderSharedCreated: React.FC<Props> = ({ created_at, edited_at, highlighted = false }) => {
const HeaderSharedCreated: React.FC<Props> = ({ created_at }) => {
const { status, highlighted } = useContext(StatusContext)
const { t } = useTranslation('componentTimeline')
const { colors } = useTheme()
const actualTime = edited_at || created_at
if (!status) return null
const actualTime = created_at || status.edited_at || status.created_at
return (
<>
@ -30,7 +32,7 @@ const HeaderSharedCreated: React.FC<Props> = ({ created_at, edited_at, highlight
<RelativeTime time={actualTime} />
)}
</CustomText>
{edited_at ? (
{status.edited_at && !highlighted ? (
<Icon
accessibilityLabel={t('shared.header.shared.edited.accessibilityLabel')}
name='Edit'

View File

@ -1,18 +1,16 @@
import Icon from '@components/Icon'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import React from 'react'
import React, { useContext } from 'react'
import { useTranslation } from 'react-i18next'
import StatusContext from '../Context'
export interface Props {
muted?: Mastodon.Status['muted']
}
const HeaderSharedMuted: React.FC<Props> = ({ muted }) => {
const HeaderSharedMuted: React.FC = () => {
const { status } = useContext(StatusContext)
const { t } = useTranslation('componentTimeline')
const { colors } = useTheme()
return muted ? (
return status?.muted ? (
<Icon
accessibilityLabel={t('shared.header.shared.muted.accessibilityLabel')}
name='VolumeX'

View File

@ -1,19 +1,17 @@
import Icon from '@components/Icon'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import React from 'react'
import React, { useContext } from 'react'
import { useTranslation } from 'react-i18next'
import { StyleSheet } from 'react-native'
import StatusContext from '../Context'
export interface Props {
visibility: Mastodon.Status['visibility']
}
const HeaderSharedVisibility: React.FC<Props> = ({ visibility }) => {
const HeaderSharedVisibility: React.FC = () => {
const { status } = useContext(StatusContext)
const { t } = useTranslation('componentTimeline')
const { colors } = useTheme()
switch (visibility) {
switch (status?.visibility) {
case 'unlisted':
return (
<Icon

View File

@ -47,7 +47,7 @@ const menuAccount = ({
setEnabled(true)
}
}, [openChange, enabled])
const { data: fetchedAccount } = useAccountQuery({ account, options: { enabled } })
const { data: fetchedAccount } = useAccountQuery({ account, _local: true, options: { enabled } })
const actualAccount = status?._remote ? fetchedAccount : account
const { data, isFetched } = useRelationshipQuery({
id: actualAccount?.id,

View File

@ -1,10 +1,10 @@
import { displayMessage } from '@components/Message'
import { useQueryClient } from '@tanstack/react-query'
import { getHost } from '@utils/helpers/urlMatcher'
import { QueryKeyTimeline, useTimelineMutation } from '@utils/queryHooks/timeline'
import { getAccountStorage } from '@utils/storage/actions'
import { useTranslation } from 'react-i18next'
import { Alert } from 'react-native'
import parse from 'url-parse'
const menuInstance = ({
status,
@ -35,9 +35,9 @@ const menuInstance = ({
const menus: ContextMenu[][] = []
const instance = getHost(status.uri)
const instance = parse(status.uri).hostname
if (instance === getAccountStorage.string('auth.domain')) {
if (instance !== getAccountStorage.string('auth.domain')) {
menus.push([
{
key: 'instance-block',

View File

@ -1,5 +1,5 @@
import { ActionSheetOptions } from '@expo/react-native-action-sheet'
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { QueryKeyInstance } from '@utils/queryHooks/instance'
import i18next from 'i18next'
import { Asset, launchImageLibrary } from 'react-native-image-picker'

View File

@ -1,12 +1,13 @@
import apiInstance from '@utils/api/instance'
import browserPackage from '@utils/helpers/browserPackage'
import { matchAccount, matchStatus } from '@utils/helpers/urlMatcher'
import { urlMatcher } from '@utils/helpers/urlMatcher'
import navigationRef from '@utils/navigation/navigationRef'
import { SearchResult } from '@utils/queryHooks/search'
import { queryClient } from '@utils/queryHooks'
import { QueryKeyAccount } from '@utils/queryHooks/account'
import { searchLocalAccount, searchLocalStatus } from '@utils/queryHooks/search'
import { QueryKeyStatus } from '@utils/queryHooks/status'
import { getGlobalStorage } from '@utils/storage/actions'
import * as Linking from 'expo-linking'
import * as WebBrowser from 'expo-web-browser'
import validUrl from 'valid-url'
export let loadingLink = false
@ -15,7 +16,7 @@ const openLink = async (url: string, navigation?: any) => {
return
}
const handleNavigation = (page: 'Tab-Shared-Toot' | 'Tab-Shared-Account', options: {}) => {
const handleNavigation = (page: 'Tab-Shared-Toot' | 'Tab-Shared-Account', options: any) => {
if (navigation) {
navigation.push(page, options)
} else {
@ -24,83 +25,79 @@ const openLink = async (url: string, navigation?: any) => {
}
}
const match = urlMatcher(url)
// If a tooot can be found
const isStatus = matchStatus(url)
if (isStatus) {
if (isStatus.sameInstance) {
handleNavigation('Tab-Shared-Toot', { toot: { id: isStatus.id } })
return
}
if (match?.status?.id) {
loadingLink = true
let response
try {
response = await apiInstance<SearchResult>({
version: 'v2',
method: 'get',
url: 'search',
params: { type: 'statuses', q: url, limit: 1, resolve: true }
})
} catch {}
if (response && response.body && response.body.statuses.length) {
handleNavigation('Tab-Shared-Toot', {
toot: response.body.statuses[0]
})
let response: Mastodon.Status | undefined = undefined
const queryKey: QueryKeyStatus = [
'Status',
{ id: match.status.id, uri: url, _remote: match.status._remote }
]
const cache = queryClient.getQueryData<Mastodon.Status>(queryKey)
if (cache) {
handleNavigation('Tab-Shared-Toot', { toot: cache })
loadingLink = false
return
} else {
try {
response = await searchLocalStatus(url)
} catch {}
if (response) {
handleNavigation('Tab-Shared-Toot', { toot: response })
loadingLink = false
return
}
}
}
// If an account can be found
const isAccount = matchAccount(url)
if (isAccount) {
if (isAccount.sameInstance) {
if (isAccount.style === 'default' && isAccount.id) {
handleNavigation('Tab-Shared-Account', { account: isAccount })
return
}
if (match?.account) {
if (!match.account._remote && match.account.id) {
handleNavigation('Tab-Shared-Account', { account: match.account.id })
return
}
loadingLink = true
let response
try {
response = await apiInstance<SearchResult>({
version: 'v2',
method: 'get',
url: 'search',
params: {
type: 'accounts',
q: isAccount.sameInstance && isAccount.style === 'pretty' ? isAccount.username : url,
limit: 1,
resolve: true
}
})
} catch {}
if (response && response.body && response.body.accounts.length) {
handleNavigation('Tab-Shared-Account', {
account: response.body.accounts[0]
})
let response: Mastodon.Account | undefined = undefined
const queryKey: QueryKeyAccount = [
'Account',
{ id: match.account.id, url: url, _remote: match.account._remote }
]
const cache = queryClient.getQueryData<Mastodon.Status>(queryKey)
if (cache) {
handleNavigation('Tab-Shared-Account', { account: cache })
loadingLink = false
return
} else {
try {
response = await searchLocalAccount(url)
} catch {}
if (response) {
handleNavigation('Tab-Shared-Account', { account: response })
loadingLink = false
return
}
}
}
loadingLink = false
const validatedUrl = validUrl.isWebUri(url)
if (validatedUrl) {
switch (getGlobalStorage.string('app.browser')) {
// Some links might end with an empty space at the end that triggers an error
case 'internal':
await WebBrowser.openBrowserAsync(validatedUrl, {
dismissButtonStyle: 'close',
enableBarCollapsing: true,
...(await browserPackage())
})
break
case 'external':
await Linking.openURL(validatedUrl)
break
}
switch (getGlobalStorage.string('app.browser')) {
// Some links might end with an empty space at the end that triggers an error
case 'internal':
await WebBrowser.openBrowserAsync(url.trim(), {
dismissButtonStyle: 'close',
enableBarCollapsing: true,
...(await browserPackage())
})
break
case 'external':
await Linking.openURL(url.trim())
break
}
}

View File

@ -10,7 +10,7 @@ import { handleError } from '@utils/api/helpers'
import { RootStackScreenProps } from '@utils/navigation/navigators'
import { useInstanceQuery } from '@utils/queryHooks/instance'
import { usePreferencesQuery } from '@utils/queryHooks/preferences'
import { searchFetchToot, SearchResult } from '@utils/queryHooks/search'
import { searchLocalStatus } from '@utils/queryHooks/search'
import { useTimelineMutation } from '@utils/queryHooks/timeline'
import {
getAccountStorage,
@ -156,7 +156,7 @@ const ScreenCompose: React.FC<RootStackScreenProps<'Screen-Compose'>> = ({
content: params.accts.map(acct => `@${acct}`).join(' ') + ' ',
disableDebounce: true
})
searchFetchToot(params.incomingStatus.uri).then(status => {
searchLocalStatus(params.incomingStatus.uri).then(status => {
if (status?.uri === params.incomingStatus.uri) {
composeDispatch({ type: 'updateReply', payload: status })
}

View File

@ -1,6 +1,6 @@
import { emojis } from '@components/Emojis'
import CustomText from '@components/Text'
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { QueryKeyInstance } from '@utils/queryHooks/instance'
import { useTheme } from '@utils/styles/ThemeManager'
import LinkifyIt from 'linkify-it'

View File

@ -1,8 +1,8 @@
import { MenuContainer, MenuRow } from '@components/Menu'
import { useActionSheet } from '@expo/react-native-action-sheet'
import { androidActionSheetStyles } from '@utils/helpers/androidActionSheetStyles'
import queryClient from '@utils/queryHooks'
import { TabMeProfileStackScreenProps } from '@utils/navigation/navigators'
import { queryClient } from '@utils/queryHooks'
import { QueryKeyPreferences } from '@utils/queryHooks/preferences'
import { useProfileMutation, useProfileQuery } from '@utils/queryHooks/profile'
import { useTheme } from '@utils/styles/ThemeManager'

View File

@ -4,11 +4,13 @@ import { displayMessage } from '@components/Message'
import { useActionSheet } from '@expo/react-native-action-sheet'
import { useNavigation } from '@react-navigation/native'
import { androidActionSheetStyles } from '@utils/helpers/androidActionSheetStyles'
import { urlMatcher } from '@utils/helpers/urlMatcher'
import { storage } from '@utils/storage'
import { getGlobalStorage, useGlobalStorage } from '@utils/storage/actions'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import React from 'react'
import { Alert } from 'react-native'
import { MMKV } from 'react-native-mmkv'
const SettingsDev: React.FC = () => {
@ -37,6 +39,17 @@ const SettingsDev: React.FC = () => {
)
}
/>
<Button
type='text'
content={'Test link matcher'}
style={{
marginHorizontal: StyleConstants.Spacing.Global.PagePadding * 2,
marginBottom: StyleConstants.Spacing.Global.PagePadding
}}
onPress={() =>
Alert.prompt('URL', undefined, text => console.log(urlMatcher(text)), 'plain-text')
}
/>
<Button
type='text'
content={'Test flash message'}

View File

@ -32,6 +32,7 @@ const TabSharedAccount: React.FC<TabSharedStackScreenProps<'Tab-Shared-Account'>
const { data, dataUpdatedAt } = useAccountQuery({
account,
_local: true,
options: {
onSuccess: a => {
if (account._remote) {

View File

@ -111,11 +111,11 @@ const ContentView: React.FC<{
const TabSharedHistory: React.FC<TabSharedStackScreenProps<'Tab-Shared-History'>> = ({
navigation,
route: {
params: { id, detectedLanguage }
params: { status, detectedLanguage }
}
}) => {
const { t } = useTranslation('screenTabs')
const { data } = useStatusHistory({ id })
const { data } = useStatusHistory({ status })
useEffect(() => {
navigation.setOptions({

View File

@ -5,7 +5,7 @@ import CustomText from '@components/Text'
import apiInstance from '@utils/api/instance'
import { TabSharedStackScreenProps } from '@utils/navigation/navigators'
import { useRulesQuery } from '@utils/queryHooks/reports'
import { searchFetchToot } from '@utils/queryHooks/search'
import { searchLocalStatus } from '@utils/queryHooks/search'
import { getAccountStorage } from '@utils/storage/actions'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
@ -55,7 +55,7 @@ const TabSharedReport: React.FC<TabSharedStackScreenProps<'Tab-Shared-Report'>>
const body = new FormData()
if (status) {
if (status._remote) {
const fetchedStatus = await searchFetchToot(status.uri)
const fetchedStatus = await searchLocalStatus(status.uri)
if (fetchedStatus) {
body.append('status_ids[]', fetchedStatus.id)
}

View File

@ -6,7 +6,7 @@ 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 { urlMatcher } from '@utils/helpers/urlMatcher'
import { TabSharedStackScreenProps } from '@utils/navigation/navigators'
import { QueryKeyTimeline } from '@utils/queryHooks/timeline'
import { getAccountStorage } from '@utils/storage/actions'
@ -66,6 +66,7 @@ const TabSharedToot: React.FC<TabSharedStackScreenProps<'Tab-Shared-Toot'>> = ({
const flRef = useRef<FlatList>(null)
const scrolled = useRef(false)
const match = urlMatcher(toot.url || toot.uri)
const finalData = useRef<(Mastodon.Status & { key?: string })[]>([
{ ...toot, _level: 0, key: 'cached' }
])
@ -145,11 +146,11 @@ const TabSharedToot: React.FC<TabSharedStackScreenProps<'Tab-Shared-Toot'>> = ({
useQuery(
queryKey.remote,
async () => {
const domain = getHost(toot.url || toot.uri)
const domain = match?.domain
if (!domain?.length) {
return Promise.reject('Cannot parse remote doamin')
}
const id = (toot.url || toot.uri).match(new RegExp(/\/([0-9]+)$/))?.[1]
const id = match?.status?.id
if (!id?.length) {
return Promise.reject('Cannot parse remote toot id')
}
@ -191,7 +192,7 @@ const TabSharedToot: React.FC<TabSharedStackScreenProps<'Tab-Shared-Toot'>> = ({
{
enabled:
['public', 'unlisted'].includes(toot.visibility) &&
getHost(toot.uri) !== getAccountStorage.string('auth.domain'),
match?.domain !== getAccountStorage.string('auth.domain'),
staleTime: 0,
refetchOnMount: true,
onSuccess: data => {

View File

@ -1,62 +1,69 @@
import { getAccountStorage } from '@utils/storage/actions'
import parse from 'url-parse'
const getHost = (url: unknown): string | undefined | null => {
if (typeof url !== 'string') return undefined
const matches = url.match(/^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+)/i)
return matches?.[1]
}
const matchStatus = (
url: string
): { id: string; style: 'default' | 'pretty'; sameInstance: boolean } | null => {
// https://social.xmflsct.com/web/statuses/105590085754428765 <- default
// https://social.xmflsct.com/@tooot/105590085754428765 <- pretty
const matcherStatus = new RegExp(/(https?:\/\/)?([^\/]+)\/(web\/statuses|@.+)\/([0-9]+)/)
const matched = url.match(matcherStatus)
if (matched) {
const hostname = matched[2]
const style = matched[3] === 'web/statuses' ? 'default' : 'pretty'
const id = matched[4]
const sameInstance = hostname === getAccountStorage.string('auth.domain')
return { id, style, sameInstance }
}
return null
}
const matchAccount = (
export const urlMatcher = (
url: string
):
| { id: string; style: 'default'; sameInstance: boolean }
| { username: string; style: 'pretty'; sameInstance: boolean }
| null => {
// https://social.xmflsct.com/web/accounts/14195 <- default
// https://social.xmflsct.com/web/@tooot <- pretty ! cannot be searched on the same instance
// https://social.xmflsct.com/@tooot <- pretty
const matcherAccount = new RegExp(
/(https?:\/\/)?([^\/]+)(\/web\/accounts\/([0-9]+)|\/web\/(@.+)|\/(@.+))/
)
const matched = url.match(matcherAccount)
if (matched) {
const hostname = matched[2]
const account = matched.filter(i => i).reverse()?.[0]
if (account) {
const style = account.startsWith('@') ? 'pretty' : 'default'
const sameInstance = hostname === getAccountStorage.string('auth.domain')
return style === 'default'
? { id: account, style, sameInstance }
: { username: account, style, sameInstance }
} else {
return null
| {
domain: string
account?: Partial<Pick<Mastodon.Account, 'id' | 'acct' | '_remote'>>
status?: Partial<Pick<Mastodon.Status, 'id' | '_remote'>>
}
| undefined => {
const parsed = parse(url)
if (!parsed.hostname.length || !parsed.pathname.length) return undefined
const domain = parsed.hostname
const _remote = parsed.hostname !== getAccountStorage.string('auth.domain')
let statusId: string | undefined
let accountId: string | undefined
let accountAcct: string | undefined
const segments = parsed.pathname.split('/')
const last = segments[segments.length - 1]
const length = segments.length // there is a starting slash
switch (last?.startsWith('@')) {
case true:
if (length === 2 || (length === 3 && segments[length - 2] === 'web')) {
// https://social.xmflsct.com/@tooot <- Mastodon v4.0 and above
// https://social.xmflsct.com/web/@tooot <- Mastodon v3.5 and below ! cannot be searched on the same instance
accountAcct = `${last}@${domain}`
}
break
case false:
const nextToLast = segments[length - 2]
if (nextToLast) {
if (nextToLast === 'statuses') {
if (length === 4 && segments[length - 3] === 'web') {
// https://social.xmflsct.com/web/statuses/105590085754428765 <- old
statusId = last
} else if (
length === 5 &&
segments[length - 2] === 'statuses' &&
segments[length - 4] === 'users'
) {
// https://social.xmflsct.com/users/tooot/statuses/105590085754428765 <- default Mastodon
statusId = last
// accountAcct = `@${segments[length - 3]}@${domain}`
}
} else if (
nextToLast.startsWith('@') &&
(length === 3 || (length === 4 && segments[length - 3] === 'web'))
) {
// https://social.xmflsct.com/web/@tooot/105590085754428765 <- pretty Mastodon v3.5 and below
// https://social.xmflsct.com/@tooot/105590085754428765 <- pretty Mastodon v4.0 and above
statusId = last
// accountAcct = `${nextToLast}@${domain}`
}
}
break
}
return null
return {
domain,
...((accountId || accountAcct) && { account: { id: accountId, acct: accountAcct, _remote } }),
...(statusId && { status: { id: statusId, _remote } })
}
}
export { getHost, matchStatus, matchAccount }

View File

@ -94,7 +94,7 @@ export type TabSharedStackParamList = {
hashtag: Mastodon.Tag['name']
}
'Tab-Shared-History': {
id: Mastodon.Status['id']
status: Mastodon.Status
detectedLanguage: string
}
'Tab-Shared-Report': {

View File

@ -5,7 +5,7 @@ import {
PERMISSION_MANAGE_REPORTS,
PERMISSION_MANAGE_USERS
} from '@utils/helpers/permissions'
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { QueryKeyProfile } from '@utils/queryHooks/profile'
import { getAccountDetails, getGlobalStorage } from '@utils/storage/actions'
import * as Notifications from 'expo-notifications'

View File

@ -1,5 +1,5 @@
import { displayMessage } from '@components/Message'
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { QueryKeyTimeline } from '@utils/queryHooks/timeline'
import { generateAccountKey, setAccount, useGlobalStorage } from '@utils/storage/actions'
import * as Notifications from 'expo-notifications'

View File

@ -1,4 +1,4 @@
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { QueryKeyTimeline } from '@utils/queryHooks/timeline'
import { generateAccountKey, setAccount, useGlobalStorage } from '@utils/storage/actions'
import * as Notifications from 'expo-notifications'

View File

@ -1,68 +1,89 @@
import { QueryFunctionContext, useQuery, UseQueryOptions } from '@tanstack/react-query'
import apiGeneral from '@utils/api/general'
import apiInstance from '@utils/api/instance'
import { urlMatcher } from '@utils/helpers/urlMatcher'
import { AxiosError } from 'axios'
import { SearchResult } from './search'
import { searchLocalAccount } from './search'
export type QueryKeyAccount = [
'Account',
Pick<Mastodon.Account, 'id' | 'url' | '_remote'> | undefined
(
| (Partial<Pick<Mastodon.Account, 'id' | 'acct' | 'username' | '_remote'>> &
Pick<Mastodon.Account, 'url'> & { _local?: boolean })
| undefined
)
]
const accountQueryFunction = async ({ queryKey }: QueryFunctionContext<QueryKeyAccount>) => {
const key = queryKey[1]
if (!key) return Promise.reject()
let matchedId = key.id
let matchedAccount: Mastodon.Account | undefined = undefined
if (key._remote) {
await apiInstance<SearchResult>({
version: 'v2',
method: 'get',
url: 'search',
params: {
q: key.url,
type: 'accounts',
limit: 1,
resolve: true
}
})
.then(res => {
const account = res.body.accounts[0]
if (account.url !== key.url) {
return Promise.reject()
} else {
matchedId = account.id
}
})
.catch(() => Promise.reject())
}
const match = urlMatcher(key.url)
const res = await apiInstance<Mastodon.Account>({
method: 'get',
url: `accounts/${matchedId}`
})
return res.body
const domain = match?.domain
const id = key.id || match?.account?.id
const acct = key.acct || key.username || match?.account?.acct
if (!key._local && domain) {
try {
if (id) {
matchedAccount = await apiGeneral<Mastodon.Account>({
method: 'get',
domain: domain,
url: `api/v1/accounts/${id}`
}).then(res => ({ ...res.body, _remote: true }))
} else if (acct) {
matchedAccount = await apiGeneral<Mastodon.Account>({
method: 'get',
domain: domain,
url: 'api/v1/accounts/lookup',
params: { acct }
}).then(res => ({ ...res.body, _remote: true }))
}
} catch {}
}
if (!matchedAccount) {
matchedAccount = await searchLocalAccount(key.url)
}
} else {
if (!matchedAccount) {
matchedAccount = await apiInstance<Mastodon.Account>({
method: 'get',
url: `accounts/${key.id}`
}).then(res => res.body)
}
}
return matchedAccount
}
const useAccountQuery = ({
options,
...queryKeyParams
}: { account?: QueryKeyAccount[1] } & {
account,
_local,
options
}: {
account?: QueryKeyAccount[1]
_local?: boolean
options?: UseQueryOptions<Mastodon.Account, AxiosError>
}) => {
const queryKey: QueryKeyAccount = [
'Account',
queryKeyParams.account
account
? {
id: queryKeyParams.account.id,
url: queryKeyParams.account.url,
_remote: queryKeyParams.account._remote
id: account.id,
username: account.username,
url: account.url,
_remote: account._remote,
...(_local && { _local })
}
: undefined
]
return useQuery(queryKey, accountQueryFunction, {
...options,
enabled: (queryKeyParams.account?._remote ? !!queryKeyParams.account : true) && options?.enabled
enabled: (account?._remote ? !!account : true) && options?.enabled
})
}

View File

@ -1,6 +1,6 @@
import { QueryClient } from '@tanstack/react-query'
const queryClient = new QueryClient({
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 5,
@ -15,12 +15,10 @@ const queryClient = new QueryClient({
}
}
}
},
logger: {
log: log => console.log(log),
warn: () => {},
error: () => {}
}
})
// @ts-ignore
import('react-query-native-devtools').then(({ addPlugin }) => {
addPlugin({ queryClient })
})
export default queryClient

View File

@ -2,7 +2,7 @@ import haptics from '@components/haptics'
import { displayMessage } from '@components/Message'
import { useMutation, useQuery, UseQueryOptions } from '@tanstack/react-query'
import apiInstance from '@utils/api/instance'
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { AxiosError } from 'axios'
import i18next from 'i18next'
import { RefObject } from 'react'

View File

@ -1,5 +1,6 @@
import { QueryFunctionContext, useQuery, UseQueryOptions } from '@tanstack/react-query'
import apiInstance from '@utils/api/instance'
import { queryClient } from '@utils/queryHooks'
import { AxiosError } from 'axios'
export type QueryKeySearch = [
@ -43,22 +44,27 @@ const useSearchQuery = <T = SearchResult>({
options?: UseQueryOptions<SearchResult, AxiosError, T>
}) => {
const queryKey: QueryKeySearch = ['Search', { ...queryKeyParams }]
return useQuery(queryKey, queryFunction, options)
return useQuery(queryKey, queryFunction, { ...options, staleTime: 3600, cacheTime: 3600 })
}
export const searchFetchToot = (uri: Mastodon.Status['uri']): Promise<Mastodon.Status | void> =>
apiInstance<SearchResult>({
version: 'v2',
method: 'get',
url: 'search',
params: {
q: uri,
type: 'statuses',
limit: 1,
resolve: true
}
})
.then(res => res.body.statuses[0])
.catch(err => console.warn(err))
export const searchLocalStatus = async (uri: Mastodon.Status['uri']): Promise<Mastodon.Status> => {
const queryKey: QueryKeySearch = ['Search', { type: 'statuses', term: uri, limit: 1 }]
return await queryClient
.fetchQuery(queryKey, queryFunction, { staleTime: 3600, cacheTime: 3600 })
.then(res =>
res.statuses[0].uri === uri || res.statuses[0].url === uri
? res.statuses[0]
: Promise.reject()
)
}
export const searchLocalAccount = async (
url: Mastodon.Account['url']
): Promise<Mastodon.Account> => {
const queryKey: QueryKeySearch = ['Search', { type: 'accounts', term: url, limit: 1 }]
return await queryClient
.fetchQuery(queryKey, queryFunction, { staleTime: 3600, cacheTime: 3600 })
.then(res => (res.accounts[0].url === url ? res.accounts[0] : Promise.reject()))
}
export { useSearchQuery }

View File

@ -1,26 +1,59 @@
import { QueryFunctionContext, useQuery, UseQueryOptions } from '@tanstack/react-query'
import apiGeneral from '@utils/api/general'
import apiInstance from '@utils/api/instance'
import { urlMatcher } from '@utils/helpers/urlMatcher'
import { AxiosError } from 'axios'
import { searchLocalStatus } from './search'
export type QueryKeyStatus = ['Status', { id: Mastodon.Status['id'] }]
export type QueryKeyStatus = [
'Status',
(Pick<Mastodon.Status, 'uri'> & Partial<Pick<Mastodon.Status, 'id' | '_remote'>>) | undefined
]
const queryFunction = async ({ queryKey }: QueryFunctionContext<QueryKeyStatus>) => {
const { id } = queryKey[1]
const key = queryKey[1]
if (!key) return Promise.reject()
const res = await apiInstance<Mastodon.Status>({
method: 'get',
url: `statuses/${id}`
})
return res.body
let matchedStatus: Mastodon.Status | undefined = undefined
const match = urlMatcher(key.uri)
const domain = match?.domain
const id = key.id || match?.status?.id
if (key._remote && domain && id) {
try {
matchedStatus = await apiGeneral<Mastodon.Status>({
method: 'get',
domain,
url: `api/v1/statuses/${id}`
}).then(res => ({ ...res.body, _remote: true }))
} catch {}
}
if (!matchedStatus && !key._remote && id) {
matchedStatus = await apiInstance<Mastodon.Status>({
method: 'get',
url: `statuses/${id}`
}).then(res => res.body)
}
if (!matchedStatus) {
matchedStatus = await searchLocalStatus(key.uri)
}
return matchedStatus
}
const useStatusQuery = ({
options,
...queryKeyParams
}: QueryKeyStatus[1] & {
status
}: { status?: QueryKeyStatus[1] } & {
options?: UseQueryOptions<Mastodon.Status, AxiosError>
}) => {
const queryKey: QueryKeyStatus = ['Status', { ...queryKeyParams }]
const queryKey: QueryKeyStatus = [
'Status',
status ? { id: status.id, uri: status.uri, _remote: status._remote } : undefined
]
return useQuery(queryKey, queryFunction, options)
}

View File

@ -1,34 +1,53 @@
import { QueryFunctionContext, useQuery, UseQueryOptions } from '@tanstack/react-query'
import apiGeneral from '@utils/api/general'
import apiInstance from '@utils/api/instance'
import { urlMatcher } from '@utils/helpers/urlMatcher'
import { AxiosError } from 'axios'
export type QueryKeyStatusesHistory = [
'StatusesHistory',
{ id: Mastodon.Status['id'] }
Pick<Mastodon.Status, 'id' | 'uri' | 'edited_at' | '_remote'> &
Partial<Pick<Mastodon.Status, 'edited_at'>>
]
const queryFunction = async ({
queryKey
}: QueryFunctionContext<QueryKeyStatusesHistory>) => {
const { id } = queryKey[1]
const res = await apiInstance<Mastodon.StatusHistory[]>({
const queryFunction = async ({ queryKey }: QueryFunctionContext<QueryKeyStatusesHistory>) => {
const { id, uri, _remote } = queryKey[1]
if (_remote) {
const match = urlMatcher(uri)
const domain = match?.domain
if (!domain) {
return Promise.reject('Cannot find remote domain to retrieve status histories')
}
return await apiGeneral<Mastodon.StatusHistory[]>({
method: 'get',
domain,
url: `api/v1/statuses/${id}/history`
}).then(res => res.body)
}
return await apiInstance<Mastodon.StatusHistory[]>({
method: 'get',
url: `statuses/${id}/history`
})
return res.body
}).then(res => res.body)
}
const useStatusHistory = ({
options,
...queryKeyParams
}: QueryKeyStatusesHistory[1] & {
status
}: { status: QueryKeyStatusesHistory[1] } & {
options?: UseQueryOptions<Mastodon.StatusHistory[], AxiosError>
}) => {
const queryKey: QueryKeyStatusesHistory = [
'StatusesHistory',
{ ...queryKeyParams }
{ id: status.id, uri: status.uri, edited_at: status.edited_at, _remote: status._remote }
]
return useQuery(queryKey, queryFunction, options)
return useQuery(queryKey, queryFunction, {
...options,
enabled: !!status.edited_at,
staleTime: 3600,
cacheTime: 3600
})
}
export { useStatusHistory }

View File

@ -9,11 +9,11 @@ import {
import { PagedResponse } from '@utils/api/helpers'
import apiInstance from '@utils/api/instance'
import { featureCheck } from '@utils/helpers/featureCheck'
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { getAccountStorage } from '@utils/storage/actions'
import { AxiosError } from 'axios'
import { uniqBy } from 'lodash'
import { searchFetchToot } from './search'
import { searchLocalStatus } from './search'
import deleteItem from './timeline/deleteItem'
import editItem from './timeline/editItem'
import updateStatusProperty from './timeline/updateStatusProperty'
@ -342,7 +342,7 @@ const mutationFunction = async (params: MutationVarsTimeline) => {
default:
let tootId = params.status.id
if (params.status._remote) {
const fetched = await searchFetchToot(params.status.uri)
const fetched = await searchLocalStatus(params.status.uri)
if (fetched) {
tootId = fetched.id
} else {

View File

@ -1,19 +1,13 @@
import { InfiniteData } from '@tanstack/react-query'
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { MutationVarsTimelineDeleteItem } from '../timeline'
const deleteItem = ({
queryKey,
rootQueryKey,
id
}: MutationVarsTimelineDeleteItem) => {
const deleteItem = ({ queryKey, rootQueryKey, id }: MutationVarsTimelineDeleteItem) => {
queryKey &&
queryClient.setQueryData<InfiniteData<any> | undefined>(queryKey, old => {
if (old) {
old.pages = old.pages.map(page => {
page.body = page.body.filter(
(item: Mastodon.Status) => item.id !== id
)
page.body = page.body.filter((item: Mastodon.Status) => item.id !== id)
return page
})
return old
@ -21,20 +15,15 @@ const deleteItem = ({
})
rootQueryKey &&
queryClient.setQueryData<InfiniteData<any> | undefined>(
rootQueryKey,
old => {
if (old) {
old.pages = old.pages.map(page => {
page.body = page.body.filter(
(item: Mastodon.Status) => item.id !== id
)
return page
})
return old
}
queryClient.setQueryData<InfiniteData<any> | undefined>(rootQueryKey, old => {
if (old) {
old.pages = old.pages.map(page => {
page.body = page.body.filter((item: Mastodon.Status) => item.id !== id)
return page
})
return old
}
)
})
}
export default deleteItem

View File

@ -1,12 +1,8 @@
import { InfiniteData } from '@tanstack/react-query'
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { MutationVarsTimelineEditItem } from '../timeline'
const editItem = ({
queryKey,
rootQueryKey,
status
}: MutationVarsTimelineEditItem) => {
const editItem = ({ queryKey, rootQueryKey, status }: MutationVarsTimelineEditItem) => {
queryKey &&
queryClient.setQueryData<InfiniteData<any> | undefined>(queryKey, old => {
if (old) {
@ -24,23 +20,20 @@ const editItem = ({
})
rootQueryKey &&
queryClient.setQueryData<InfiniteData<any> | undefined>(
rootQueryKey,
old => {
if (old) {
old.pages = old.pages.map(page => {
page.body = page.body.map((item: Mastodon.Status) => {
if (item.id === status.id) {
item = status
}
return item
})
return page
queryClient.setQueryData<InfiniteData<any> | undefined>(rootQueryKey, old => {
if (old) {
old.pages = old.pages.map(page => {
page.body = page.body.map((item: Mastodon.Status) => {
if (item.id === status.id) {
item = status
}
return item
})
return old
}
return page
})
return old
}
)
})
}
export default editItem

View File

@ -1,5 +1,5 @@
import { InfiniteData } from '@tanstack/react-query'
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { MutationVarsTimelineUpdateStatusProperty, TimelineData } from '../timeline'
const updateStatusProperty = ({
@ -9,7 +9,7 @@ const updateStatusProperty = ({
payload,
poll
}: MutationVarsTimelineUpdateStatusProperty & { poll?: Mastodon.Poll }) => {
for (const key of [queryKey]) {
for (const key of [queryKey, rootQueryKey]) {
if (!key) continue
queryClient.setQueryData<InfiniteData<TimelineData> | undefined>(key, old => {

View File

@ -1,22 +1,18 @@
import {
QueryFunctionContext,
useInfiniteQuery,
UseInfiniteQueryOptions
QueryFunctionContext,
useInfiniteQuery,
UseInfiniteQueryOptions
} from '@tanstack/react-query'
import apiGeneral from '@utils/api/general'
import { PagedResponse } from '@utils/api/helpers'
import apiInstance from '@utils/api/instance'
import { getHost } from '@utils/helpers/urlMatcher'
import { urlMatcher } from '@utils/helpers/urlMatcher'
import { TabSharedStackParamList } from '@utils/navigation/navigators'
import { AxiosError } from 'axios'
export type QueryKeyUsers = ['Users', TabSharedStackParamList['Tab-Shared-Users']]
const queryFunction = async ({
queryKey,
pageParam,
meta
}: QueryFunctionContext<QueryKeyUsers>) => {
const queryFunction = async ({ queryKey, pageParam }: QueryFunctionContext<QueryKeyUsers>) => {
const page = queryKey[1]
let params: { [key: string]: string } = { ...pageParam }
@ -24,7 +20,7 @@ const queryFunction = async ({
case 'statuses':
return apiInstance<Mastodon.Account[]>({
method: 'get',
url: `${page.reference}/${page.status.id}/${page.type}`,
url: `statuses/${page.status.id}/${page.type}`,
params
})
case 'accounts':
@ -32,14 +28,14 @@ const queryFunction = async ({
if (localInstance) {
return apiInstance<Mastodon.Account[]>({
method: 'get',
url: `${page.reference}/${page.account.id}/${page.type}`,
url: `accounts/${page.account.id}/${page.type}`,
params
})
} else {
let res: PagedResponse<Mastodon.Account[]>
try {
const domain = getHost(page.account.url)
const domain = urlMatcher(page.account.url)?.domain
if (!domain?.length) {
throw new Error()
}
@ -54,7 +50,7 @@ const queryFunction = async ({
res = await apiGeneral<Mastodon.Account[]>({
method: 'get',
domain,
url: `api/v1/${page.reference}/${resLookup.body.id}/${page.type}`,
url: `api/v1/accounts/${resLookup.body.id}/${page.type}`,
params
})
return { ...res, remoteData: true }

12
src/utils/startup/dev.ts Normal file
View File

@ -0,0 +1,12 @@
import { queryClient } from '@utils/queryHooks'
import log from './log'
export const dev = () => {
if (__DEV__) {
log('log', 'dev', 'loading tools')
// @ts-ignore
import('react-query-native-devtools').then(({ addPlugin }) => {
addPlugin({ queryClient })
})
}
}

View File

@ -1,4 +1,4 @@
import queryClient from '@utils/queryHooks'
import { queryClient } from '@utils/queryHooks'
import { storage } from '@utils/storage'
import {
MMKV,

View File

@ -3449,6 +3449,13 @@ __metadata:
languageName: node
linkType: hard
"@types/url-parse@npm:^1":
version: 1.4.8
resolution: "@types/url-parse@npm:1.4.8"
checksum: 44a5e96ed4b579c43750f3578bfa9165f97a359c3b2a85ee126e9c16db964f6ea105e152afd3d1adbd15850a8b812043215f3820112177bb4255a60b432dbd85
languageName: node
linkType: hard
"@types/use-sync-external-store@npm:^0.0.3":
version: 0.0.3
resolution: "@types/use-sync-external-store@npm:0.0.3"
@ -3456,13 +3463,6 @@ __metadata:
languageName: node
linkType: hard
"@types/valid-url@npm:^1.0.3":
version: 1.0.3
resolution: "@types/valid-url@npm:1.0.3"
checksum: bd527221b4f839c440600520f9bfbdb340f473543ea5ee25215f35155ae52fd2cc5c39086cab2ffa67a54a7c303de937fcc8a58edf9bc5b7000169d7a7aa8d42
languageName: node
linkType: hard
"@types/yargs-parser@npm:*":
version: 21.0.0
resolution: "@types/yargs-parser@npm:21.0.0"
@ -11262,7 +11262,7 @@ __metadata:
"@types/react-dom": ^18.0.10
"@types/react-native": ^0.70.8
"@types/react-native-share-menu": ^5.0.2
"@types/valid-url": ^1.0.3
"@types/url-parse": ^1
axios: ^1.2.1
babel-plugin-module-resolver: ^4.1.0
babel-plugin-transform-remove-console: ^6.9.4
@ -11320,7 +11320,7 @@ __metadata:
react-redux: ^8.0.5
rn-placeholder: ^3.0.3
typescript: ^4.9.4
valid-url: ^1.0.9
url-parse: ^1.5.10
zeego: ^1.0.2
languageName: unknown
linkType: soft
@ -11623,7 +11623,7 @@ __metadata:
languageName: node
linkType: hard
"url-parse@npm:^1.5.9":
"url-parse@npm:^1.5.10, url-parse@npm:^1.5.9":
version: 1.5.10
resolution: "url-parse@npm:1.5.10"
dependencies:
@ -11753,7 +11753,7 @@ __metadata:
languageName: node
linkType: hard
"valid-url@npm:^1.0.9, valid-url@npm:~1.0.9":
"valid-url@npm:~1.0.9":
version: 1.0.9
resolution: "valid-url@npm:1.0.9"
checksum: 3ecb030559404441c2cf104cbabab8770efb0f36d117db03d1081052ef133015a68806148ce954bb4dd0b5c42c14b709a88783c93d66b0916cb67ba771c98702