Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import {msg} from '@lingui/core/macro'import {useLingui} from '@lingui/react'import {useMutation, useQueryClient} from '@tanstack/react-query'
import {isSpaceRecordUri} from '#/lib/api/space-uri'import {logger} from '#/logger'import {RQKEY as FEED_RQKEY} from '#/state/queries/post-feed'import * as Toast from '#/components/Toast'import {updatePostShadow} from '../cache/post-shadow'import {useAgent, useSession} from '../session'import {useProfileUpdateMutation} from './profile'
export function usePinnedPostMutation() { const {_} = useLingui() const {currentAccount} = useSession() const agent = useAgent() const queryClient = useQueryClient() const {mutateAsync: profileUpdateMutate} = useProfileUpdateMutation()
return useMutation({ mutationFn: async ({ postUri, postCid, action, }: { postUri: string postCid: string action: 'pin' | 'unpin' }) => { const pinCurrentPost = action === 'pin' // The pin lands in the public profile record, so a space URI here would // publish a private post's existence and author. The menu already hides // the control; this is the invariant at the write. if (isSpaceRecordUri(postUri)) { throw new Error('A post in a private space cannot be pinned') } let prevPinnedPost: string | undefined try { updatePostShadow(queryClient, postUri, {pinned: pinCurrentPost})
// get the currently pinned post so we can optimistically remove the pin from it if (!currentAccount) throw new Error('Not signed in') const {data: profile} = await agent.getProfile({ actor: currentAccount.did, }) prevPinnedPost = profile.pinnedPost?.uri if (prevPinnedPost && prevPinnedPost !== postUri) { updatePostShadow(queryClient, prevPinnedPost, {pinned: false}) }
await profileUpdateMutate({ profile, updates: existing => { existing.pinnedPost = pinCurrentPost ? {uri: postUri, cid: postCid} : undefined return existing }, checkCommitted: res => pinCurrentPost ? res.data.pinnedPost?.uri === postUri : !res.data.pinnedPost, })
if (pinCurrentPost) { Toast.show(_(msg({message: 'Post pinned', context: 'toast'}))) } else { Toast.show(_(msg({message: 'Post unpinned', context: 'toast'}))) }
queryClient.invalidateQueries({ queryKey: FEED_RQKEY( `author|${currentAccount.did}|posts_and_author_threads`, ), }) queryClient.invalidateQueries({ queryKey: FEED_RQKEY( `author|${currentAccount.did}|posts_with_replies`, ), }) } catch (e: any) { Toast.show(_(msg`Failed to pin post`)) logger.error('Failed to pin post', {message: String(e)}) // revert optimistic update updatePostShadow(queryClient, postUri, { pinned: !pinCurrentPost, }) if (prevPinnedPost && prevPinnedPost !== postUri) { updatePostShadow(queryClient, prevPinnedPost, {pinned: true}) } } }, })}