forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
1import {
2 createContext,
3 useCallback,
4 useContext,
5 useEffect,
6 useState,
7} from 'react'
8import type {PropsWithChildren} from 'react'
9
10import * as persisted from '#/state/persisted'
11
12type StateContext = persisted.Schema['constellationEnabled']
13type SetContext = (v: persisted.Schema['constellationEnabled']) => void
14
15const stateContext = createContext<StateContext>(
16 persisted.defaults.constellationEnabled,
17)
18const setContext = createContext<SetContext>(
19 (_: persisted.Schema['constellationEnabled']) => {},
20)
21
22export function Provider({children}: PropsWithChildren<{}>) {
23 const [state, setState] = useState(persisted.get('constellationEnabled'))
24
25 const setStateWrapped = useCallback(
26 (constellationEnabled: persisted.Schema['constellationEnabled']) => {
27 setState(constellationEnabled)
28 persisted.write('constellationEnabled', constellationEnabled)
29 },
30 [setState],
31 )
32
33 useEffect(() => {
34 return persisted.onUpdate(
35 'constellationEnabled',
36 nextConstellationEnabled => {
37 setState(nextConstellationEnabled)
38 },
39 )
40 }, [setStateWrapped])
41
42 return (
43 <stateContext.Provider value={state}>
44 <setContext.Provider value={setStateWrapped}>
45 {children}
46 </setContext.Provider>
47 </stateContext.Provider>
48 )
49}
50
51export function useConstellationEnabled() {
52 return useContext(stateContext)
53}
54
55export function useSetConstellationEnabled() {
56 return useContext(setContext)
57}