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