import React from 'react' import {type EmbedPlayerSource} from '#/lib/strings/embed-player' import * as persisted from '#/state/persisted' type StateContext = persisted.Schema['externalEmbeds'] type SetContext = ( source: EmbedPlayerSource, value: 'show' | 'hide' | undefined, ) => void const stateContext = React.createContext( persisted.defaults.externalEmbeds, ) stateContext.displayName = 'ExternalEmbedsPrefsStateContext' const setContext = React.createContext({} as SetContext) setContext.displayName = 'ExternalEmbedsPrefsSetContext' export function Provider({children}: React.PropsWithChildren<{}>) { const [state, setState] = React.useState(persisted.get('externalEmbeds')) const setStateWrapped = React.useCallback( (source: EmbedPlayerSource, value: 'show' | 'hide' | undefined) => { setState(prev => { persisted.write('externalEmbeds', { ...prev, [source]: value, }) return { ...prev, [source]: value, } }) }, [setState], ) React.useEffect(() => { return persisted.onUpdate('externalEmbeds', nextExternalEmbeds => { setState(nextExternalEmbeds) }) }, [setStateWrapped]) return ( {children} ) } export function useExternalEmbedsPrefs() { return React.useContext(stateContext) } export function useSetExternalEmbedPref() { return React.useContext(setContext) }