Bluesky app fork with some witchin' additions 馃挮
1import {useCallback} from 'react'
2import {type AppBskyActorDefs} from '@atproto/api'
3import {msg} from '@lingui/core/macro'
4import {useLingui} from '@lingui/react'
5
6import {sanitizeDisplayName} from '#/lib/strings/display-names'
7import {logger} from '#/logger'
8import {type Shadow} from '#/state/cache/types'
9import {type SessionAccount} from '#/state/session'
10import * as Toast from '#/components/Toast'
11import {type Metrics} from '#/analytics/metrics'
12import type * as bsky from '#/types/bsky'
13import {useRunWithEphemeralAgent} from './useRunWithEphemeralAgent'
14
15export function useEphemeralFollowAction({
16 profile,
17 logContext: _logContext,
18 onFollow,
19 onUnfollow,
20}: {
21 profile: Shadow<bsky.profile.AnyProfileView>
22 logContext: Metrics['profile:follow']['logContext'] &
23 Metrics['profile:unfollow']['logContext']
24 onFollow?: () => void
25 onUnfollow?: () => void
26}) {
27 const {_} = useLingui()
28 const runWithEphemeralAgent = useRunWithEphemeralAgent()
29
30 return useCallback(
31 async (account: SessionAccount) => {
32 try {
33 const result = await runWithEphemeralAgent(account, async agent => {
34 const res = await agent.getProfile({actor: profile.did})
35 const target =
36 res.data as AppBskyActorDefs.ProfileViewDetailed
37 const followingUri = target.viewer?.following
38
39 if (followingUri) {
40 await agent.deleteFollow(followingUri)
41 return {followed: false}
42 }
43
44 await agent.follow(profile.did)
45 return {followed: true}
46 })
47
48 if (result.followed) {
49 onFollow?.()
50 Toast.show(
51 _(
52 msg`Following ${sanitizeDisplayName(
53 profile.displayName || profile.handle,
54 )} as @${account.handle}`,
55 ),
56 )
57 } else {
58 onUnfollow?.()
59 Toast.show(
60 _(
61 msg`No longer following ${sanitizeDisplayName(
62 profile.displayName || profile.handle,
63 )} as @${account.handle}`,
64 ),
65 )
66 }
67 } catch (e) {
68 logger.error('useEphemeralFollowAction: failed to toggle follow', {
69 message: String(e),
70 targetDid: profile.did,
71 accountDid: account.did,
72 })
73 Toast.show(_(msg`An issue occurred, please try again.`), {
74 type: 'error',
75 })
76 }
77 },
78 [_, onFollow, onUnfollow, profile, runWithEphemeralAgent],
79 )
80}