forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
1import React from 'react'
2import {View} from 'react-native'
3import {msg, Trans} from '@lingui/macro'
4import {useLingui} from '@lingui/react'
5
6import {logger} from '#/logger'
7import {type SessionAccount, useSession, useSessionApi} from '#/state/session'
8import {useLoggedOutViewControls} from '#/state/shell/logged-out'
9import * as Toast from '#/view/com/util/Toast'
10import {atoms as a, web} from '#/alf'
11import {AccountList} from '#/components/AccountList'
12import {Button, ButtonText} from '#/components/Button'
13import * as TextField from '#/components/forms/TextField'
14import {useAnalytics} from '#/analytics'
15import {FormContainer} from './FormContainer'
16
17export const ChooseAccountForm = ({
18 onSelectAccount,
19 onPressBack,
20}: {
21 onSelectAccount: (account?: SessionAccount) => void
22 onPressBack: () => void
23}) => {
24 const [pendingDid, setPendingDid] = React.useState<string | null>(null)
25 const {_} = useLingui()
26 const ax = useAnalytics()
27 const {currentAccount} = useSession()
28 const {resumeSession} = useSessionApi()
29 const {setShowLoggedOut} = useLoggedOutViewControls()
30
31 const onSelect = React.useCallback(
32 async (account: SessionAccount) => {
33 if (pendingDid) {
34 // The session API isn't resilient to race conditions so let's just ignore this.
35 return
36 }
37 if (!account.accessJwt) {
38 // Move to login form.
39 onSelectAccount(account)
40 return
41 }
42 if (account.did === currentAccount?.did) {
43 setShowLoggedOut(false)
44 Toast.show(_(msg`Already signed in as @${account.handle}`))
45 return
46 }
47 try {
48 setPendingDid(account.did)
49 await resumeSession(account, true)
50 ax.metric('account:loggedIn', {
51 logContext: 'ChooseAccountForm',
52 withPassword: false,
53 })
54 Toast.show(_(msg`Signed in as @${account.handle}`))
55 } catch (e: any) {
56 logger.error('choose account: initSession failed', {
57 message: e.message,
58 })
59 // Move to login form.
60 onSelectAccount(account)
61 } finally {
62 setPendingDid(null)
63 }
64 },
65 [
66 currentAccount,
67 resumeSession,
68 pendingDid,
69 onSelectAccount,
70 setShowLoggedOut,
71 _,
72 ],
73 )
74
75 return (
76 <FormContainer
77 testID="chooseAccountForm"
78 titleText={<Trans>Select account</Trans>}
79 style={web([a.py_2xl])}>
80 <View>
81 <TextField.LabelText>
82 <Trans>Sign in as...</Trans>
83 </TextField.LabelText>
84 <AccountList
85 onSelectAccount={onSelect}
86 onSelectOther={() => onSelectAccount()}
87 pendingDid={pendingDid}
88 />
89 </View>
90 <View style={[a.flex_row]}>
91 <Button
92 label={_(msg`Back`)}
93 variant="solid"
94 color="secondary"
95 size="large"
96 onPress={onPressBack}>
97 <ButtonText>{_(msg`Back`)}</ButtonText>
98 </Button>
99 <View style={[a.flex_1]} />
100 </View>
101 </FormContainer>
102 )
103}