import { useEffect , useState } from 'react' ; export const useDetectClickOrHoverWithinTargets = ( { targetEl , alwaysBlurOnClick , useClickInsteadOfHover } ) => { const [ isClickFocus , setIsClickFocus ] = useState ( false ) ; const [ isHover , setIsHover ] = useState ( false ) ; const handleMouseOver = ( ) => setIsHover ( true ) ; const handleMouseOut = ( ) => setIsHover ( false ) ; useEffect ( ( ) => { if ( targetEl && ! useClickInsteadOfHover ) { targetEl . addEventListener ( 'mouseover' , handleMouseOver ) ; targetEl . addEventListener ( 'mouseout' , handleMouseOut ) ; return ( ) => { targetEl . removeEventListener ( 'mouseover' , handleMouseOver ) ; targetEl . removeEventListener ( 'mouseout' , handleMouseOut ) ; } ; } if ( targetEl && useClickInsteadOfHover ) { const listener = ( event ) => { if ( ! targetEl || targetEl . contains ( event . target ) ) { return ; } document . removeEventListener ( 'click' , listener ) ; document . removeEventListener ( 'touchend' , listener ) ; setIsClickFocus ( false ) ; } ; const onClick = ( ) => { setIsClickFocus ( ( is ) => alwaysBlurOnClick ? ! is : true ) ; document . removeEventListener ( 'click' , listener ) ; document . removeEventListener ( 'touchend' , listener ) ; document . addEventListener ( 'click' , listener ) ; document . addEventListener ( 'touchend' , listener ) ; } ; targetEl ?. addEventListener ( 'click' , onClick ) ; if ( isClickFocus ) { document . addEventListener ( 'click' , listener ) ; document . addEventListener ( 'touchend' , listener ) ; } return ( ) => { targetEl ?. removeEventListener ( 'click' , onClick ) ; document . removeEventListener ( 'click' , listener ) ; document . removeEventListener ( 'touchend' , listener ) ; } ; } } , [ targetEl , alwaysBlurOnClick , useClickInsteadOfHover ] ) ; return useClickInsteadOfHover ? isClickFocus : isHover ; } ;