import useIsomorphicLayoutEffect from '../../../hooks/useIsomorphicLayoutEffect' ; import { createContext , useState , useEffect , ReactElement , FunctionComponent , ReactNode , } from 'react' ; import theme , { Size } from '../../../views/themes/default' ; type AppContextProps = { isEnhanced : boolean ; isKeyboard : boolean ; isFullSupportBrowser : boolean ; windowSize : Size ; } ; const appContextDefaults = { isEnhanced : false , isKeyboard : true , isFullSupportBrowser : false , windowSize : 'small' as Size , } ; export const AppContext = createContext < AppContextProps > ( appContextDefaults ) ; type AppContextProviderProps = { children : ReactNode ; } ; function getWindowSize ( ) { switch ( true ) { case window . innerWidth < theme . sizes . medium : return 'small' ; case window . innerWidth < theme . sizes . large : return 'medium' ; case window . innerWidth < theme . sizes . xlarge : return 'large' ; default : return 'xlarge' ; } } export const AppContextProvider = ( { children , } ) : ReactElement < AppContextProviderProps > => { const [ isEnhanced , setIsEnhanced ] = useState ( appContextDefaults . isEnhanced ) ; const [ isKeyboard , setIsKeyboard ] = useState ( appContextDefaults . isKeyboard ) ; const [ isFullSupportBrowser , setIsFullSupportBrowser ] = useState ( appContextDefaults . isFullSupportBrowser ) ; const [ windowSize , setWindowSize ] = useState < Size > ( appContextDefaults . windowSize ) ; useEffect ( ( ) => { setIsEnhanced ( true ) ; } , [ ] ) ; function updateWindowSize ( ) { setWindowSize ( getWindowSize ( ) ) ; } useEffect ( ( ) => { window . addEventListener ( 'resize' , updateWindowSize ) ; return ( ) => window . removeEventListener ( 'resize' , updateWindowSize ) ; } , [ ] ) ; useIsomorphicLayoutEffect ( ( ) => { updateWindowSize ( ) ; } , [ ] ) ; useEffect ( ( ) => { setIsFullSupportBrowser ( 'IntersectionObserver' in window ) ; document . addEventListener ( 'mousedown' , setIsKeyboardFalse ) ; document . addEventListener ( 'keydown' , setIsKeyboardTrue ) ; return ( ) => { document . removeEventListener ( 'mousedown' , setIsKeyboardFalse ) ; document . removeEventListener ( 'keydown' , setIsKeyboardTrue ) ; } ; } , [ ] ) ; function setIsKeyboardFalse ( ) { document && document . documentElement && document . documentElement . classList . remove ( 'is-keyboard' ) ; setIsKeyboard ( false ) ; } function setIsKeyboardTrue ( ) { document && document . documentElement && document . documentElement . classList . add ( 'is-keyboard' ) ; setIsKeyboard ( true ) ; } return ( < AppContext . Provider value = { { isEnhanced , isKeyboard , isFullSupportBrowser , windowSize , } } > { children } < /AppContext.Provider>); } ;