forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
1import React from 'react'
2
3import {useSession} from '#/state/session'
4import {useActiveStarterPack} from '#/state/shell/starter-pack'
5import {IS_WEB} from '#/env'
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})
42StateContext.displayName = 'LoggedOutStateContext'
43
44const ControlsContext = React.createContext<Controls>({
45 setShowLoggedOut: () => {},
46 requestSwitchToAccount: () => {},
47 clearRequestedAccount: () => {},
48})
49ControlsContext.displayName = 'LoggedOutControlsContext'
50
51export function Provider({children}: React.PropsWithChildren<{}>) {
52 const activeStarterPack = useActiveStarterPack()
53 const {hasSession} = useSession()
54 const shouldShowStarterPack = Boolean(activeStarterPack?.uri) && !hasSession
55 const [state, setState] = React.useState<State>({
56 showLoggedOut: shouldShowStarterPack,
57 requestedAccountSwitchTo: shouldShowStarterPack
58 ? IS_WEB
59 ? 'starterpack'
60 : 'new'
61 : undefined,
62 })
63
64 const controls = React.useMemo<Controls>(
65 () => ({
66 setShowLoggedOut(show) {
67 setState(s => ({
68 ...s,
69 showLoggedOut: show,
70 }))
71 },
72 requestSwitchToAccount({requestedAccount}) {
73 setState(s => ({
74 ...s,
75 showLoggedOut: true,
76 requestedAccountSwitchTo: requestedAccount,
77 }))
78 },
79 clearRequestedAccount() {
80 setState(s => ({
81 ...s,
82 requestedAccountSwitchTo: undefined,
83 }))
84 },
85 }),
86 [setState],
87 )
88
89 return (
90 <StateContext.Provider value={state}>
91 <ControlsContext.Provider value={controls}>
92 {children}
93 </ControlsContext.Provider>
94 </StateContext.Provider>
95 )
96}
97
98export function useLoggedOutView() {
99 return React.useContext(StateContext)
100}
101
102export function useLoggedOutViewControls() {
103 return React.useContext(ControlsContext)
104}