mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import React from 'react'
2
3import {isWeb} from '#/platform/detection'
4import {useSession} from '#/state/session'
5import {useActiveStarterPack} from '#/state/shell/starter-pack'
6
7type State = {
8 showLoggedOut: boolean
9 /**
10 * Account did used to populate the login form when the logged out view is
11 * shown.
12 */
13 requestedAccountSwitchTo?: string
14}
15
16type Controls = {
17 /**
18 * Show or hide the logged out view.
19 */
20 setShowLoggedOut: (show: boolean) => void
21 /**
22 * Shows the logged out view and drops the user into the login form using the
23 * requested account.
24 */
25 requestSwitchToAccount: (props: {
26 /**
27 * The did of the account to populate the login form with.
28 */
29 requestedAccount?: string | 'none' | 'new' | 'starterpack'
30 }) => void
31 /**
32 * Clears the requested account so that next time the logged out view is
33 * show, no account is pre-populated.
34 */
35 clearRequestedAccount: () => void
36}
37
38const StateContext = React.createContext<State>({
39 showLoggedOut: false,
40 requestedAccountSwitchTo: undefined,
41})
42
43const ControlsContext = React.createContext<Controls>({
44 setShowLoggedOut: () => {},
45 requestSwitchToAccount: () => {},
46 clearRequestedAccount: () => {},
47})
48
49export function Provider({children}: React.PropsWithChildren<{}>) {
50 const activeStarterPack = useActiveStarterPack()
51 const {hasSession} = useSession()
52 const shouldShowStarterPack = Boolean(activeStarterPack?.uri) && !hasSession
53 const [state, setState] = React.useState<State>({
54 showLoggedOut: shouldShowStarterPack,
55 requestedAccountSwitchTo: shouldShowStarterPack
56 ? isWeb
57 ? 'starterpack'
58 : 'new'
59 : undefined,
60 })
61
62 const controls = React.useMemo<Controls>(
63 () => ({
64 setShowLoggedOut(show) {
65 setState(s => ({
66 ...s,
67 showLoggedOut: show,
68 }))
69 },
70 requestSwitchToAccount({requestedAccount}) {
71 setState(s => ({
72 ...s,
73 showLoggedOut: true,
74 requestedAccountSwitchTo: requestedAccount,
75 }))
76 },
77 clearRequestedAccount() {
78 setState(s => ({
79 ...s,
80 requestedAccountSwitchTo: undefined,
81 }))
82 },
83 }),
84 [setState],
85 )
86
87 return (
88 <StateContext.Provider value={state}>
89 <ControlsContext.Provider value={controls}>
90 {children}
91 </ControlsContext.Provider>
92 </StateContext.Provider>
93 )
94}
95
96export function useLoggedOutView() {
97 return React.useContext(StateContext)
98}
99
100export function useLoggedOutViewControls() {
101 return React.useContext(ControlsContext)
102}