forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
1import {
2 createContext,
3 type ReactNode,
4 useContext,
5 useMemo,
6 useState,
7} from 'react'
8
9import {useSession} from '#/state/session'
10import {POLICY_UPDATE_IS_ENABLED} from '#/components/PolicyUpdateOverlay/config'
11import {Provider as PortalProvider} from '#/components/PolicyUpdateOverlay/Portal'
12import {
13 type PolicyUpdateState,
14 usePolicyUpdateState,
15} from '#/components/PolicyUpdateOverlay/usePolicyUpdateState'
16import {ENV} from '#/env'
17
18const Context = createContext<{
19 state: PolicyUpdateState
20 setIsReadyToShowOverlay: () => void
21}>({
22 state: {
23 completed: true,
24 complete: () => {},
25 },
26 /**
27 * Although our data will be ready to go when the app shell mounts, we don't
28 * want to show the overlay until we actually render it, which happens after
29 * sigin/signup/onboarding in `createNativeStackNavigatorWithAuth`.
30 */
31 setIsReadyToShowOverlay: () => {},
32})
33Context.displayName = 'PolicyUpdateOverlayContext'
34
35export function usePolicyUpdateContext() {
36 const context = useContext(Context)
37 if (!context) {
38 throw new Error(
39 'usePolicyUpdateContext must be used within a PolicyUpdateProvider',
40 )
41 }
42 return context
43}
44
45export function Provider({children}: {children?: ReactNode}) {
46 const {hasSession} = useSession()
47 const [isReadyToShowOverlay, setIsReadyToShowOverlay] = useState(false)
48 const state = usePolicyUpdateState({
49 enabled:
50 // if the feature is enabled
51 POLICY_UPDATE_IS_ENABLED &&
52 // once shell has rendered
53 isReadyToShowOverlay &&
54 // only once logged in
55 hasSession &&
56 // only enabled in non-test environments
57 ENV !== 'e2e',
58 })
59
60 const ctx = useMemo(
61 () => ({
62 state,
63 setIsReadyToShowOverlay() {
64 if (isReadyToShowOverlay) return
65 setIsReadyToShowOverlay(true)
66 },
67 }),
68 [state, isReadyToShowOverlay, setIsReadyToShowOverlay],
69 )
70
71 return (
72 <PortalProvider>
73 <Context.Provider value={ctx}>{children}</Context.Provider>
74 </PortalProvider>
75 )
76}