import { useState , useEffect , useContext } from 'react' ; import { ThemeContext } from '../support/ThemeProvider' ; import { platform } from './env' ; import { useTheme as useSCTheme } from 'styled-components' ; export const useKeyPress = ( targetKey ) => { const [ keyPressed , setKeyPressed ] = useState ( false ) ; const downHandler = ( event ) => { if ( event . key === targetKey ) { setKeyPressed ( true ) ; } } ; const upHandler = ( event ) => { if ( event . key === targetKey ) { setKeyPressed ( false ) ; } } ; useEffect ( ( ) => { window . addEventListener ( 'keydown' , downHandler ) ; window . addEventListener ( 'keyup' , upHandler ) ; return ( ) => { window . removeEventListener ( 'keydown' , downHandler ) ; window . removeEventListener ( 'keyup' , upHandler ) ; } ; } , [ ] ) ; return keyPressed ; } ; export const useOnClickOutside = ( elementRefs , callback ) => { useEffect ( ( ) => { if ( ! elementRefs ?. length ) return ; const listener = ( event ) => { let clickInsideElements = false ; elementRefs . forEach ( elRef => { if ( ! elRef . current || elRef . current . contains ( event . target as Node ) ) { clickInsideElements = true ; } } ) ; if ( clickInsideElements ) return ; callback ( event ) ; } ; document . addEventListener ( 'mousedown' , listener ) ; document . addEventListener ( 'touchstart' , listener ) ; return ( ) => { document . removeEventListener ( 'mousedown' , listener ) ; document . removeEventListener ( 'touchstart' , listener ) ; } ; } , [ elementRefs , callback ] ) ; } ; export const useTheme = ( ) => { const contextTheme = useContext ( ThemeContext ) ; const scTheme = useSCTheme ( ) ; return platform === 'web' ? scTheme : contextTheme ; } ;