mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import {useCallback} from 'react'
2
3import {isWeb} from '#/platform/detection'
4import {useAnalytics} from '#/lib/analytics/analytics'
5import {useSessionApi, SessionAccount} from '#/state/session'
6import * as Toast from '#/view/com/util/Toast'
7import {useCloseAllActiveElements} from '#/state/util'
8import {useLoggedOutViewControls} from '#/state/shell/logged-out'
9import {LogEvents} from '../statsig/statsig'
10
11export function useAccountSwitcher() {
12 const {track} = useAnalytics()
13 const {selectAccount, clearCurrentAccount} = useSessionApi()
14 const closeAllActiveElements = useCloseAllActiveElements()
15 const {requestSwitchToAccount} = useLoggedOutViewControls()
16
17 const onPressSwitchAccount = useCallback(
18 async (
19 account: SessionAccount,
20 logContext: LogEvents['account:loggedIn']['logContext'],
21 ) => {
22 track('Settings:SwitchAccountButtonClicked')
23
24 try {
25 if (account.accessJwt) {
26 closeAllActiveElements()
27 if (isWeb) {
28 // We're switching accounts, which remounts the entire app.
29 // On mobile, this gets us Home, but on the web we also need reset the URL.
30 // We can't change the URL via a navigate() call because the navigator
31 // itself is about to unmount, and it calls pushState() too late.
32 // So we change the URL ourselves. The navigator will pick it up on remount.
33 history.pushState(null, '', '/')
34 }
35 await selectAccount(account, logContext)
36 setTimeout(() => {
37 Toast.show(`Signed in as @${account.handle}`)
38 }, 100)
39 } else {
40 closeAllActiveElements()
41 requestSwitchToAccount({requestedAccount: account.did})
42 Toast.show(
43 `Please sign in as @${account.handle}`,
44 'circle-exclamation',
45 )
46 }
47 } catch (e) {
48 Toast.show('Sorry! We need you to enter your password.')
49 clearCurrentAccount() // back user out to login
50 }
51 },
52 [
53 track,
54 clearCurrentAccount,
55 selectAccount,
56 closeAllActiveElements,
57 requestSwitchToAccount,
58 ],
59 )
60
61 return {onPressSwitchAccount}
62}