mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import {useCallback, useState} from 'react'
2import {msg} from '@lingui/macro'
3import {useLingui} from '@lingui/react'
4
5import {useAnalytics} from '#/lib/analytics/analytics'
6import {logger} from '#/logger'
7import {isWeb} from '#/platform/detection'
8import {SessionAccount, useSessionApi} from '#/state/session'
9import {useLoggedOutViewControls} from '#/state/shell/logged-out'
10import * as Toast from '#/view/com/util/Toast'
11import {logEvent} from '../statsig/statsig'
12import {LogEvents} from '../statsig/statsig'
13
14export function useAccountSwitcher() {
15 const [pendingDid, setPendingDid] = useState<string | null>(null)
16 const {_} = useLingui()
17 const {track} = useAnalytics()
18 const {resumeSession} = useSessionApi()
19 const {requestSwitchToAccount} = useLoggedOutViewControls()
20
21 const onPressSwitchAccount = useCallback(
22 async (
23 account: SessionAccount,
24 logContext: LogEvents['account:loggedIn']['logContext'],
25 ) => {
26 track('Settings:SwitchAccountButtonClicked')
27 if (pendingDid) {
28 // The session API isn't resilient to race conditions so let's just ignore this.
29 return
30 }
31 try {
32 setPendingDid(account.did)
33 if (account.accessJwt) {
34 if (isWeb) {
35 // We're switching accounts, which remounts the entire app.
36 // On mobile, this gets us Home, but on the web we also need reset the URL.
37 // We can't change the URL via a navigate() call because the navigator
38 // itself is about to unmount, and it calls pushState() too late.
39 // So we change the URL ourselves. The navigator will pick it up on remount.
40 history.pushState(null, '', '/')
41 }
42 await resumeSession(account)
43 logEvent('account:loggedIn', {logContext, withPassword: false})
44 Toast.show(_(msg`Signed in as @${account.handle}`))
45 } else {
46 requestSwitchToAccount({requestedAccount: account.did})
47 Toast.show(
48 _(msg`Please sign in as @${account.handle}`),
49 'circle-exclamation',
50 )
51 }
52 } catch (e: any) {
53 logger.error(`switch account: selectAccount failed`, {
54 message: e.message,
55 })
56 requestSwitchToAccount({requestedAccount: account.did})
57 Toast.show(
58 _(msg`Please sign in as @${account.handle}`),
59 'circle-exclamation',
60 )
61 } finally {
62 setPendingDid(null)
63 }
64 },
65 [_, track, resumeSession, requestSwitchToAccount, pendingDid],
66 )
67
68 return {onPressSwitchAccount, pendingDid}
69}