import React from 'react' ; import { useRouter } from 'next/router' ; import { ChildrenType } from '@/utils/globalTypes' ; interface IContextProps { open ? : boolean ; toggle ? : ( ) => void ; ref ? : React . Ref < HTMLElement > ; } const Context = React . createContext < IContextProps > ( { } ) ; export default function LayoutProvider ( { children } ) { const [ open , setOpen ] = React . useState ( false ) ; const ref = React . useRef < HTMLElement > ( null ) ; const router = useRouter ( ) ; const toggle = React . useCallback ( ( ) => { setOpen ( ! open ) ; } , [ open ] ) ; React . useEffect ( ( ) => { if ( open && window . innerWidth < 1024 ) { router . events . on ( 'routeChangeStart' , ( ) => setOpen ( false ) ) ; document . documentElement . style . overflow = 'hidden' ; } return ( ) => { if ( open && window . innerWidth < 1024 ) { router . events . off ( 'routeChangeStart' , ( ) => setOpen ( false ) ) ; document . documentElement . style . overflow = '' ; } } ; } , [ open , router ] ) ; React . useEffect ( ( ) => { const handleOutsideClick = ( event ) => { if ( ! ref . current ?. contains ( event . target ) ) { if ( ! open ) return ; setOpen ( false ) ; } } ; window . addEventListener ( 'click' , handleOutsideClick ) ; return ( ) => window . removeEventListener ( 'click' , handleOutsideClick ) ; } , [ open , ref ] ) ; return ( < Context . Provider value = { { open , ref , toggle } } > { children } < /Context.Provider>); } export function useToggle ( ) { return React . useContext ( Context ) ; }