mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import React from 'react'
2import * as persisted from '#/state/persisted'
3import {EmbedPlayerSource} from 'lib/strings/embed-player'
4
5type StateContext = persisted.Schema['externalEmbeds']
6type SetContext = (source: EmbedPlayerSource, value: 'show' | 'hide') => void
7
8const stateContext = React.createContext<StateContext>(
9 persisted.defaults.externalEmbeds,
10)
11const setContext = React.createContext<SetContext>({} as SetContext)
12
13export function Provider({children}: React.PropsWithChildren<{}>) {
14 const [state, setState] = React.useState(persisted.get('externalEmbeds'))
15
16 const setStateWrapped = React.useCallback(
17 (source: EmbedPlayerSource, value: 'show' | 'hide') => {
18 setState(prev => {
19 persisted.write('externalEmbeds', {
20 ...prev,
21 [source]: value,
22 })
23
24 return {
25 ...prev,
26 [source]: value,
27 }
28 })
29 },
30 [setState],
31 )
32
33 React.useEffect(() => {
34 return persisted.onUpdate(() => {
35 setState(persisted.get('externalEmbeds'))
36 })
37 }, [setStateWrapped])
38
39 return (
40 <stateContext.Provider value={state}>
41 <setContext.Provider value={setStateWrapped}>
42 {children}
43 </setContext.Provider>
44 </stateContext.Provider>
45 )
46}
47
48export function useExternalEmbedsPrefs() {
49 return React.useContext(stateContext)
50}
51
52export function useSetExternalEmbedPref() {
53 return React.useContext(setContext)
54}