Bluesky app fork with some witchin' additions 馃挮
witchsky.app
bluesky
fork
client
1import {useCallback, useState} from 'react'
2import {msg} from '@lingui/core/macro'
3import {useLingui} from '@lingui/react'
4
5import {logger} from '#/logger'
6import {type SessionAccount, useSessionApi} from '#/state/session'
7import {canAttemptSessionResume} from '#/state/session/util'
8import {useLoggedOutViewControls} from '#/state/shell/logged-out'
9import * as Toast from '#/components/Toast'
10import {useAnalytics} from '#/analytics'
11import {type Metrics} from '#/analytics/metrics'
12import {storeNavigationStateForAccountSwitch} from '#/Navigation'
13
14export function useAccountSwitcher() {
15 const ax = useAnalytics()
16 const [pendingDid, setPendingDid] = useState<string | null>(null)
17 const {_} = useLingui()
18 const {resumeSession} = useSessionApi()
19 const {requestSwitchToAccount} = useLoggedOutViewControls()
20
21 const onPressSwitchAccount = useCallback(
22 async (
23 account: SessionAccount,
24 logContext: Metrics['account:loggedIn']['logContext'],
25 ) => {
26 if (pendingDid) {
27 // The session API isn't resilient to race conditions so let's just ignore this.
28 return
29 }
30 try {
31 setPendingDid(account.did)
32 if (canAttemptSessionResume(account)) {
33 // Store navigation state before switching so user stays on the same page
34 storeNavigationStateForAccountSwitch()
35 await resumeSession(account, true)
36 ax.metric('account:loggedIn', {logContext, withPassword: false})
37 Toast.show(_(msg`Signed in as @${account.handle}`))
38 } else {
39 requestSwitchToAccount({requestedAccount: account.did})
40 Toast.show(_(msg`Please sign in as @${account.handle}`), {
41 type: 'warning',
42 })
43 }
44 } catch (e: any) {
45 logger.error(`switch account: selectAccount failed`, {
46 message: e instanceof Error ? e.message : String(e),
47 })
48 requestSwitchToAccount({requestedAccount: account.did})
49 Toast.show(_(msg`Please sign in as @${account.handle}`), {
50 type: 'warning',
51 })
52 } finally {
53 setPendingDid(null)
54 }
55 },
56 [_, ax, resumeSession, requestSwitchToAccount, pendingDid],
57 )
58
59 return {onPressSwitchAccount, pendingDid}
60}