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