Skip to content

Commit

Permalink
[Session] Extract resumeSession out (bluesky-social#3811)
Browse files Browse the repository at this point in the history
  • Loading branch information
gaearon authored May 2, 2024
1 parent dadf27f commit 5ec945b
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 36 deletions.
32 changes: 24 additions & 8 deletions src/App.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {useLingui} from '@lingui/react'
import {useQueryClient} from '@tanstack/react-query'

import {Provider as StatsigProvider} from '#/lib/statsig/statsig'
import {logger} from '#/logger'
import {init as initPersistedState} from '#/state/persisted'
import {Provider as LabelDefsProvider} from '#/state/preferences/label-defs'
import {Provider as ModerationOptsProvider} from '#/state/preferences/moderation-opts'
Expand All @@ -34,6 +35,7 @@ import {Provider as PrefsStateProvider} from 'state/preferences'
import {Provider as UnreadNotifsProvider} from 'state/queries/notifications/unread'
import {
Provider as SessionProvider,
SessionAccount,
useSession,
useSessionApi,
} from 'state/session'
Expand All @@ -53,27 +55,41 @@ import {listenSessionDropped} from './state/events'
SplashScreen.preventAutoHideAsync()

function InnerApp() {
const {isInitialLoad, currentAccount} = useSession()
const {resumeSession} = useSessionApi()
const [isReady, setIsReady] = React.useState(false)
const {currentAccount} = useSession()
const {initSession} = useSessionApi()
const theme = useColorModeTheme()
const {_} = useLingui()

useIntentHandler()

// init
useEffect(() => {
listenSessionDropped(() => {
Toast.show(_(msg`Sorry! Your session expired. Please log in again.`))
})

async function resumeSession(account?: SessionAccount) {
try {
if (account) {
await initSession(account)
}
} catch (e) {
logger.error(`session: resumeSession failed`, {message: e})
} finally {
setIsReady(true)
}
}
const account = readLastActiveAccount()
resumeSession(account)
}, [resumeSession, _])
}, [initSession])

useEffect(() => {
return listenSessionDropped(() => {
Toast.show(_(msg`Sorry! Your session expired. Please log in again.`))
})
}, [_])

return (
<SafeAreaProvider initialMetrics={initialWindowMetrics}>
<Alf theme={theme}>
<Splash isReady={!isInitialLoad}>
<Splash isReady={isReady}>
<React.Fragment
// Resets the entire tree below when it changes:
key={currentAccount?.did}>
Expand Down
22 changes: 18 additions & 4 deletions src/App.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {RootSiblingParent} from 'react-native-root-siblings'
import {SafeAreaProvider} from 'react-native-safe-area-context'

import {Provider as StatsigProvider} from '#/lib/statsig/statsig'
import {logger} from '#/logger'
import {init as initPersistedState} from '#/state/persisted'
import {Provider as LabelDefsProvider} from '#/state/preferences/label-defs'
import {Provider as ModerationOptsProvider} from '#/state/preferences/moderation-opts'
Expand All @@ -22,6 +23,7 @@ import {Provider as PrefsStateProvider} from 'state/preferences'
import {Provider as UnreadNotifsProvider} from 'state/queries/notifications/unread'
import {
Provider as SessionProvider,
SessionAccount,
useSession,
useSessionApi,
} from 'state/session'
Expand All @@ -36,19 +38,31 @@ import {Provider as PortalProvider} from '#/components/Portal'
import I18nProvider from './locale/i18nProvider'

function InnerApp() {
const {isInitialLoad, currentAccount} = useSession()
const {resumeSession} = useSessionApi()
const [isReady, setIsReady] = React.useState(false)
const {currentAccount} = useSession()
const {initSession} = useSessionApi()
const theme = useColorModeTheme()
useIntentHandler()

// init
useEffect(() => {
async function resumeSession(account?: SessionAccount) {
try {
if (account) {
await initSession(account)
}
} catch (e) {
logger.error(`session: resumeSession failed`, {message: e})
} finally {
setIsReady(true)
}
}
const account = readLastActiveAccount()
resumeSession(account)
}, [resumeSession])
}, [initSession])

// wait for session to resume
if (isInitialLoad) return null
if (!isReady) return null

return (
<Alf theme={theme}>
Expand Down
23 changes: 1 addition & 22 deletions src/state/session/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ const PUBLIC_BSKY_AGENT = new BskyAgent({service: PUBLIC_BSKY_SERVICE})
configureModerationForGuest()

const StateContext = React.createContext<SessionStateContext>({
isInitialLoad: true,
isSwitchingAccounts: false,
accounts: [],
currentAccount: undefined,
Expand All @@ -47,7 +46,6 @@ const ApiContext = React.createContext<SessionApiContext>({
login: async () => {},
logout: async () => {},
initSession: async () => {},
resumeSession: async () => {},
removeAccount: () => {},
selectAccount: async () => {},
updateCurrentAccount: () => {},
Expand All @@ -67,7 +65,6 @@ type State = {
}

export function Provider({children}: React.PropsWithChildren<{}>) {
const [isInitialLoad, setIsInitialLoad] = React.useState(true)
const [isSwitchingAccounts, setIsSwitchingAccounts] = React.useState(false)
const [state, setState] = React.useState<State>({
accounts: persisted.get('session').accounts,
Expand Down Expand Up @@ -389,21 +386,6 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
[upsertAccount, clearCurrentAccount, createPersistSessionHandler],
)

const resumeSession = React.useCallback<SessionApiContext['resumeSession']>(
async account => {
try {
if (account) {
await initSession(account)
}
} catch (e) {
logger.error(`session: resumeSession failed`, {message: e})
} finally {
setIsInitialLoad(false)
}
},
[initSession],
)

const removeAccount = React.useCallback<SessionApiContext['removeAccount']>(
account => {
setState(s => {
Expand Down Expand Up @@ -547,11 +529,10 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
currentAccount: state.accounts.find(
a => a.did === state.currentAccountDid,
),
isInitialLoad,
isSwitchingAccounts,
hasSession: !!state.currentAccountDid,
}),
[state, isInitialLoad, isSwitchingAccounts],
[state, isSwitchingAccounts],
)

const api = React.useMemo(
Expand All @@ -560,7 +541,6 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
login,
logout,
initSession,
resumeSession,
removeAccount,
selectAccount,
updateCurrentAccount,
Expand All @@ -571,7 +551,6 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
login,
logout,
initSession,
resumeSession,
removeAccount,
selectAccount,
updateCurrentAccount,
Expand Down
2 changes: 0 additions & 2 deletions src/state/session/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ export type SessionAccount = PersistedAccount
export type SessionStateContext = {
accounts: SessionAccount[]
currentAccount: SessionAccount | undefined
isInitialLoad: boolean
isSwitchingAccounts: boolean
hasSession: boolean
}
Expand Down Expand Up @@ -46,7 +45,6 @@ export type SessionApiContext = {
*/
clearCurrentAccount: () => void
initSession: (account: SessionAccount) => Promise<void>
resumeSession: (account?: SessionAccount) => Promise<void>
removeAccount: (account: SessionAccount) => void
selectAccount: (
account: SessionAccount,
Expand Down

0 comments on commit 5ec945b

Please sign in to comment.