tooot/src/utils/queryHooks/timeline.ts

505 lines
14 KiB
TypeScript
Raw Normal View History

2021-01-11 21:36:57 +01:00
import haptics from '@components/haptics'
import {
2022-12-31 00:07:28 +01:00
MutationOptions,
QueryFunctionContext,
useInfiniteQuery,
UseInfiniteQueryOptions,
useMutation,
useQuery,
UseQueryOptions
} from '@tanstack/react-query'
import { PagedResponse } from '@utils/api/helpers'
import apiInstance from '@utils/api/instance'
import { featureCheck } from '@utils/helpers/featureCheck'
import queryClient from '@utils/queryHooks'
import { getAccountStorage } from '@utils/storage/actions'
import { AxiosError } from 'axios'
import { uniqBy } from 'lodash'
2021-01-11 21:36:57 +01:00
import deleteItem from './timeline/deleteItem'
2022-04-30 17:44:39 +02:00
import editItem from './timeline/editItem'
2021-01-11 21:36:57 +01:00
import updateStatusProperty from './timeline/updateStatusProperty'
2021-01-07 19:13:09 +01:00
2022-12-31 00:07:28 +01:00
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
}
2022-12-31 14:00:52 +01:00
return { pages: [{ body: statuses }], highlightIndex }
2022-12-31 00:07:28 +01:00
}
const useTootQuery = ({
options,
...queryKeyParams
}: QueryKeyTimeline[1] & {
options?: UseQueryOptions<
{
2022-12-31 14:00:52 +01:00
pages: { body: (Mastodon.Status & { _level: number })[] }[]
2022-12-31 00:07:28 +01:00
highlightIndex: number
},
AxiosError
>
}) => {
const queryKey: QueryKeyTimeline = ['Timeline', { ...queryKeyParams }]
return useQuery(queryKey, queryFunctionToot, {
staleTime: 0,
refetchOnMount: true,
...options
})
}
/* ----- */
2021-01-07 19:13:09 +01:00
export type QueryKeyTimeline = [
'Timeline',
2022-12-14 23:37:41 +01:00
(
| {
page: Exclude<App.Pages, 'Following' | 'Hashtag' | 'List' | 'Toot' | 'Account'>
}
| {
page: 'Following'
showBoosts: boolean
showReplies: boolean
}
| {
page: 'Hashtag'
hashtag: Mastodon.Tag['name']
}
| {
page: 'List'
list: Mastodon.List['id']
}
| {
page: 'Account'
account: Mastodon.Account['id']
exclude_reblogs: boolean
only_media: boolean
}
2022-12-31 00:07:28 +01:00
| {
page: 'Toot'
toot: Mastodon.Status['id']
}
2022-12-14 23:37:41 +01:00
)
2021-01-07 19:13:09 +01:00
]
2022-12-03 20:47:11 +01:00
const queryFunction = async ({ queryKey, pageParam }: QueryFunctionContext<QueryKeyTimeline>) => {
2022-12-14 23:37:41 +01:00
const page = queryKey[1]
2022-12-18 22:01:02 +01:00
let params: { [key: string]: string } = { limit: 40, ...pageParam }
2021-01-07 19:13:09 +01:00
2022-12-14 23:37:41 +01:00
switch (page.page) {
2021-01-07 19:13:09 +01:00
case 'Following':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Status[]>({
2021-01-07 19:13:09 +01:00
method: 'get',
url: 'timelines/home',
params
2022-12-14 23:37:41 +01:00
}).then(res => {
if (!page.showBoosts || !page.showReplies) {
return {
...res,
body: res.body
.filter(status => {
if (!page.showBoosts && status.reblog) {
return null
}
if (!page.showReplies && status.in_reply_to_id?.length) {
return null
}
return status
})
.filter(s => s)
}
} else {
return res
}
2021-01-07 19:13:09 +01:00
})
case 'Local':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Status[]>({
2021-01-07 19:13:09 +01:00
method: 'get',
url: 'timelines/public',
2021-01-11 21:36:57 +01:00
params: {
...params,
local: 'true'
}
2021-01-07 19:13:09 +01:00
})
case 'LocalPublic':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Status[]>({
2021-01-07 19:13:09 +01:00
method: 'get',
url: 'timelines/public',
params
})
case 'Trending':
return apiInstance<Mastodon.Status[]>({
method: 'get',
url: 'trends/statuses',
params
})
2021-01-07 19:13:09 +01:00
case 'Notifications':
const notificationsFilter = getAccountStorage.object('notifications')
const usePositiveFilter = featureCheck('notification_types_positive_filter')
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Notification[]>({
2021-01-07 19:13:09 +01:00
method: 'get',
url: 'notifications',
2021-03-17 15:30:28 +01:00
params: {
...params,
...(notificationsFilter &&
(usePositiveFilter
? {
types: Object.keys(notificationsFilter)
// @ts-ignore
.filter(filter => notificationsFilter[filter] === true)
}
: {
exclude_types: Object.keys(notificationsFilter)
// @ts-ignore
.filter(filter => notificationsFilter[filter] === false)
}))
2021-03-17 15:30:28 +01:00
}
2021-01-07 19:13:09 +01:00
})
2022-12-14 23:37:41 +01:00
case 'Account':
if (page.exclude_reblogs) {
if (pageParam && pageParam.hasOwnProperty('max_id')) {
return apiInstance<Mastodon.Status[]>({
method: 'get',
url: `accounts/${page.account}/statuses`,
params: {
exclude_replies: 'true',
...params
}
})
} else {
const res1 = await apiInstance<(Mastodon.Status & { _pinned: boolean })[]>({
method: 'get',
url: `accounts/${page.account}/statuses`,
params: {
pinned: 'true'
}
})
res1.body = res1.body.map(status => {
status._pinned = true
return status
})
const res2 = await apiInstance<Mastodon.Status[]>({
method: 'get',
url: `accounts/${page.account}/statuses`,
params: {
exclude_replies: 'true'
}
})
return {
body: uniqBy([...res1.body, ...res2.body], 'id'),
...(res2.links.next && { links: { next: res2.links.next } })
2021-01-07 19:13:09 +01:00
}
2022-12-14 23:37:41 +01:00
}
2021-01-07 19:13:09 +01:00
} else {
2022-12-14 23:37:41 +01:00
return apiInstance<Mastodon.Status[]>({
2021-03-29 00:22:30 +02:00
method: 'get',
2022-12-14 23:37:41 +01:00
url: `accounts/${page.account}/statuses`,
2021-03-29 00:22:30 +02:00
params: {
2022-12-14 23:37:41 +01:00
...params,
exclude_replies: page.exclude_reblogs.toString(),
only_media: page.only_media.toString()
2021-02-11 01:33:31 +01:00
}
2021-01-07 19:13:09 +01:00
})
}
case 'Hashtag':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Status[]>({
2021-01-07 19:13:09 +01:00
method: 'get',
2022-12-14 23:37:41 +01:00
url: `timelines/tag/${page.hashtag}`,
2021-01-07 19:13:09 +01:00
params
})
case 'Conversations':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Conversation[]>({
2021-01-07 19:13:09 +01:00
method: 'get',
url: `conversations`,
params
})
case 'Bookmarks':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Status[]>({
2021-01-07 19:13:09 +01:00
method: 'get',
url: `bookmarks`,
params
})
case 'Favourites':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Status[]>({
2021-01-07 19:13:09 +01:00
method: 'get',
url: `favourites`,
params
})
case 'List':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Status[]>({
2021-01-07 19:13:09 +01:00
method: 'get',
2022-12-14 23:37:41 +01:00
url: `timelines/list/${page.list}`,
2021-01-07 19:13:09 +01:00
params
})
default:
return Promise.reject()
}
}
type Unpromise<T extends Promise<any>> = T extends Promise<infer U> ? U : never
2021-01-11 21:36:57 +01:00
export type TimelineData = Unpromise<ReturnType<typeof queryFunction>>
2021-12-18 19:59:38 +01:00
const useTimelineQuery = ({
2021-01-07 19:13:09 +01:00
options,
...queryKeyParams
}: QueryKeyTimeline[1] & {
2022-12-15 14:28:36 +01:00
options?: UseInfiniteQueryOptions<PagedResponse<Mastodon.Status[]>, AxiosError>
2021-01-07 19:13:09 +01:00
}) => {
const queryKey: QueryKeyTimeline = ['Timeline', { ...queryKeyParams }]
2021-03-14 00:47:55 +01:00
return useInfiniteQuery(queryKey, queryFunction, {
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
...options
})
2021-01-07 19:13:09 +01:00
}
2021-01-11 21:36:57 +01:00
// --- Separator ---
enum MapPropertyToUrl {
bookmarked = 'bookmark',
favourited = 'favourite',
muted = 'mute',
pinned = 'pin',
reblogged = 'reblog'
}
export type MutationVarsTimelineUpdateStatusProperty = {
// This is status in general, including "status" inside conversation and notification
type: 'updateStatusProperty'
queryKey: QueryKeyTimeline
2021-02-13 01:26:02 +01:00
rootQueryKey?: QueryKeyTimeline
2021-01-11 21:36:57 +01:00
id: Mastodon.Status['id'] | Mastodon.Poll['id']
2022-12-03 20:47:11 +01:00
isReblog?: boolean
2021-01-11 21:36:57 +01:00
payload:
| {
2021-01-23 02:41:50 +01:00
property: 'bookmarked' | 'muted' | 'pinned'
2021-01-11 21:36:57 +01:00
currentValue: boolean
2022-12-24 01:59:18 +01:00
propertyCount?: undefined
countValue?: undefined
2021-01-23 02:41:50 +01:00
}
| {
2022-10-31 23:43:42 +01:00
property: 'favourited'
2021-01-23 02:41:50 +01:00
currentValue: boolean
propertyCount: 'favourites_count' | 'reblogs_count'
countValue: number
2021-01-11 21:36:57 +01:00
}
2022-10-31 23:43:42 +01:00
| {
property: 'reblogged'
currentValue: boolean
propertyCount: 'favourites_count' | 'reblogs_count'
countValue: number
visibility: 'public' | 'unlisted'
}
2021-01-11 21:36:57 +01:00
| {
property: 'poll'
id: Mastodon.Poll['id']
type: 'vote' | 'refresh'
options?: boolean[]
data?: Mastodon.Poll
}
}
export type MutationVarsTimelineUpdateAccountProperty = {
// This is status in general, including "status" inside conversation and notification
type: 'updateAccountProperty'
queryKey?: QueryKeyTimeline
id: Mastodon.Account['id']
payload: {
property: 'mute' | 'block' | 'reports'
currentValue?: boolean
2021-01-11 21:36:57 +01:00
}
}
2022-04-30 17:44:39 +02:00
export type MutationVarsTimelineEditItem = {
// This is for editing status
type: 'editItem'
queryKey?: QueryKeyTimeline
rootQueryKey?: QueryKeyTimeline
status: Mastodon.Status
}
2021-01-11 21:36:57 +01:00
export type MutationVarsTimelineDeleteItem = {
// This is for deleting status and conversation
type: 'deleteItem'
source: 'statuses' | 'conversations'
2021-02-13 01:26:02 +01:00
queryKey?: QueryKeyTimeline
rootQueryKey?: QueryKeyTimeline
2022-04-30 17:44:39 +02:00
id: Mastodon.Status['id']
2021-01-11 21:36:57 +01:00
}
export type MutationVarsTimelineDomainBlock = {
// This is for deleting status and conversation
type: 'domainBlock'
queryKey: QueryKeyTimeline
domain: string
}
export type MutationVarsTimeline =
| MutationVarsTimelineUpdateStatusProperty
| MutationVarsTimelineUpdateAccountProperty
2022-04-30 17:44:39 +02:00
| MutationVarsTimelineEditItem
2021-01-11 21:36:57 +01:00
| MutationVarsTimelineDeleteItem
| MutationVarsTimelineDomainBlock
const mutationFunction = async (params: MutationVarsTimeline) => {
switch (params.type) {
case 'updateStatusProperty':
switch (params.payload.property) {
case 'poll':
const formData = new FormData()
params.payload.type === 'vote' &&
2021-01-22 01:34:20 +01:00
params.payload.options?.forEach((option, index) => {
2021-01-11 21:36:57 +01:00
if (option) {
formData.append('choices[]', index.toString())
}
})
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Poll>({
2021-01-11 21:36:57 +01:00
method: params.payload.type === 'vote' ? 'post' : 'get',
url:
params.payload.type === 'vote'
? `polls/${params.payload.id}/votes`
: `polls/${params.payload.id}`,
...(params.payload.type === 'vote' && { body: formData })
})
default:
2022-10-31 23:43:42 +01:00
const body = new FormData()
if (params.payload.property === 'reblogged') {
body.append('visibility', params.payload.visibility)
}
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Status>({
2021-01-11 21:36:57 +01:00
method: 'post',
2022-12-03 20:47:11 +01:00
url: `statuses/${params.id}/${params.payload.currentValue ? 'un' : ''}${
MapPropertyToUrl[params.payload.property]
}`,
...(params.payload.property === 'reblogged' && { body })
2021-01-11 21:36:57 +01:00
})
}
case 'updateAccountProperty':
switch (params.payload.property) {
case 'block':
case 'mute':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Account>({
2021-01-11 21:36:57 +01:00
method: 'post',
2022-12-03 20:47:11 +01:00
url: `accounts/${params.id}/${params.payload.currentValue ? 'un' : ''}${
params.payload.property
}`
2021-01-11 21:36:57 +01:00
})
case 'reports':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Account>({
2021-01-11 21:36:57 +01:00
method: 'post',
url: `reports`,
params: {
account_id: params.id
}
})
}
2022-04-30 17:44:39 +02:00
case 'editItem':
return { body: params.status }
2021-01-11 21:36:57 +01:00
case 'deleteItem':
2021-02-20 19:12:44 +01:00
return apiInstance<Mastodon.Conversation>({
2021-01-11 21:36:57 +01:00
method: 'delete',
url: `${params.source}/${params.id}`
})
case 'domainBlock':
2021-02-20 19:12:44 +01:00
return apiInstance<any>({
2021-01-11 21:36:57 +01:00
method: 'post',
url: `domain_blocks`,
params: {
domain: params.domain
}
})
}
}
type MutationOptionsTimeline = MutationOptions<
2021-02-11 01:33:31 +01:00
{ body: Mastodon.Conversation | Mastodon.Notification | Mastodon.Status },
2021-01-11 21:36:57 +01:00
AxiosError,
MutationVarsTimeline
>
const useTimelineMutation = ({
onError,
onMutate,
onSettled,
onSuccess
}: {
onError?: MutationOptionsTimeline['onError']
onMutate?: boolean
onSettled?: MutationOptionsTimeline['onSettled']
2021-02-13 01:26:02 +01:00
onSuccess?: MutationOptionsTimeline['onSuccess']
2021-01-11 21:36:57 +01:00
}) => {
return useMutation<
2021-02-11 01:33:31 +01:00
{ body: Mastodon.Conversation | Mastodon.Notification | Mastodon.Status },
2021-01-11 21:36:57 +01:00
AxiosError,
MutationVarsTimeline
>(mutationFunction, {
onError,
onSettled,
2021-02-13 01:26:02 +01:00
onSuccess,
2021-01-11 21:36:57 +01:00
...(onMutate && {
onMutate: params => {
queryClient.cancelQueries(params.queryKey)
2022-12-03 20:47:11 +01:00
const oldData = params.queryKey && queryClient.getQueryData(params.queryKey)
2021-01-11 21:36:57 +01:00
2021-02-27 16:33:54 +01:00
haptics('Light')
2021-01-11 21:36:57 +01:00
switch (params.type) {
case 'updateStatusProperty':
updateStatusProperty(params)
2021-01-11 21:36:57 +01:00
break
2022-04-30 17:44:39 +02:00
case 'editItem':
editItem(params)
break
2021-01-11 21:36:57 +01:00
case 'deleteItem':
deleteItem(params)
2021-01-11 21:36:57 +01:00
break
}
return oldData
}
})
})
}
2022-12-31 00:07:28 +01:00
export { useTootQuery, useTimelineQuery, useTimelineMutation }