import { useEffect , useRef } from 'react' ; const LONG_TAP_TIMEOUT = 1000 ; const useTooltipHandlers = ( open , close , isOpen ) => { const longTapTimeoutRef = useRef ( 0 ) ; const ignoreFocusRef = useRef ( false ) ; const ignoreNonTouchEventsRef = useRef ( false ) ; const ignoreNonTouchEventsTimeoutRef = useRef ( 0 ) ; const handleCloseTooltip = ( ) => { clearTimeout ( longTapTimeoutRef . current ) ; longTapTimeoutRef . current = 0 ; clearTimeout ( ignoreNonTouchEventsTimeoutRef . current ) ; ignoreNonTouchEventsTimeoutRef . current = window . setTimeout ( ( ) => { ignoreNonTouchEventsRef . current = false ; } , 100 ) ; close ( ) ; } ; useEffect ( ( ) => { if ( ! isOpen ) { return ; } document . addEventListener ( 'touchstart' , close ) ; return ( ) => { document . removeEventListener ( 'touchstart' , close ) ; } ; } , [ isOpen , close ] ) ; const handleTouchStart = ( ) => { clearTimeout ( ignoreNonTouchEventsTimeoutRef . current ) ; ignoreNonTouchEventsTimeoutRef . current = 0 ; clearTimeout ( longTapTimeoutRef . current ) ; longTapTimeoutRef . current = window . setTimeout ( ( ) => { open ( ) ; longTapTimeoutRef . current = 0 ; } , LONG_TAP_TIMEOUT ) ; ignoreNonTouchEventsRef . current = true ; } ; const handleTouchEnd = ( ) => { if ( isOpen && ! longTapTimeoutRef . current ) { return ; } clearTimeout ( longTapTimeoutRef . current ) ; longTapTimeoutRef . current = 0 ; handleCloseTooltip ( ) ; } ; const handleMouseEnter = ( ) => { if ( ignoreNonTouchEventsRef . current ) { return ; } open ( ) ; } ; const handleMouseDown = ( ) => { if ( ignoreNonTouchEventsRef . current ) { return ; } ignoreFocusRef . current = true ; close ( ) ; } ; const handleMouseLeave = ( ) => { ignoreFocusRef . current = false ; if ( ignoreNonTouchEventsRef . current ) { return ; } close ( ) ; } ; const handleFocus = ( ) => { if ( ignoreNonTouchEventsRef . current || ignoreFocusRef . current ) { ignoreFocusRef . current = false ; return ; } open ( ) ; } ; return { onTouchEnd : handleTouchEnd , onTouchStart : handleTouchStart , onMouseDown : handleMouseDown , onMouseEnter : handleMouseEnter , onMouseLeave : handleMouseLeave , onFocus : handleFocus , onBlur : handleCloseTooltip , } ; } ; export default useTooltipHandlers ;