@@ -19,6 +19,7 @@ const Tooltip = ({
1919 place = 'top' ,
2020 offset = 10 ,
2121 events = [ 'hover' ] ,
22+ openOnClick = false ,
2223 positionStrategy = 'absolute' ,
2324 middlewares,
2425 wrapper : WrapperElement ,
@@ -60,6 +61,8 @@ const Tooltip = ({
6061 const [ anchorsBySelect , setAnchorsBySelect ] = useState < HTMLElement [ ] > ( [ ] )
6162 const mounted = useRef ( false )
6263
64+ const shouldOpenOnClick = openOnClick || events . includes ( 'click' )
65+
6366 /**
6467 * useLayoutEffect runs before useEffect,
6568 * but should be used carefully because of caveats
@@ -255,10 +258,11 @@ const Tooltip = ({
255258
256259 const handleClickOutsideAnchors = ( event : MouseEvent ) => {
257260 const anchorById = document . querySelector < HTMLElement > ( `[id='${ anchorId } ']` )
258- if ( anchorById ?. contains ( event . target as HTMLElement ) ) {
261+ const anchors = [ anchorById , ...anchorsBySelect ]
262+ if ( anchors . some ( ( anchor ) => anchor ?. contains ( event . target as HTMLElement ) ) ) {
259263 return
260264 }
261- if ( anchorsBySelect . some ( ( anchor ) => anchor . contains ( event . target as HTMLElement ) ) ) {
265+ if ( tooltipRef . current ? .contains ( event . target as HTMLElement ) ) {
262266 return
263267 }
264268 handleShow ( false )
@@ -294,12 +298,10 @@ const Tooltip = ({
294298
295299 const enabledEvents : { event : string ; listener : ( event ?: Event ) => void } [ ] = [ ]
296300
297- if ( events . find ( ( event : string ) => event === 'click' ) ) {
301+ if ( shouldOpenOnClick ) {
298302 window . addEventListener ( 'click' , handleClickOutsideAnchors )
299303 enabledEvents . push ( { event : 'click' , listener : handleClickTooltipAnchor } )
300- }
301-
302- if ( events . find ( ( event : string ) => event === 'hover' ) ) {
304+ } else {
303305 enabledEvents . push (
304306 { event : 'mouseenter' , listener : debouncedHandleShowTooltip } ,
305307 { event : 'mouseleave' , listener : debouncedHandleHideTooltip } ,
@@ -322,7 +324,7 @@ const Tooltip = ({
322324 handleHideTooltip ( )
323325 }
324326
325- if ( clickable ) {
327+ if ( clickable && ! shouldOpenOnClick ) {
326328 tooltipRef . current ?. addEventListener ( 'mouseenter' , handleMouseEnterTooltip )
327329 tooltipRef . current ?. addEventListener ( 'mouseleave' , handleMouseLeaveTooltip )
328330 }
@@ -334,13 +336,13 @@ const Tooltip = ({
334336 } )
335337
336338 return ( ) => {
337- if ( events . find ( ( event : string ) => event === 'click' ) ) {
339+ if ( shouldOpenOnClick ) {
338340 window . removeEventListener ( 'click' , handleClickOutsideAnchors )
339341 }
340342 if ( closeOnEsc ) {
341343 window . removeEventListener ( 'keydown' , handleEsc )
342344 }
343- if ( clickable ) {
345+ if ( clickable && ! shouldOpenOnClick ) {
344346 tooltipRef . current ?. removeEventListener ( 'mouseenter' , handleMouseEnterTooltip )
345347 tooltipRef . current ?. removeEventListener ( 'mouseleave' , handleMouseLeaveTooltip )
346348 }
0 commit comments