From 3e327e281268ccf4ac927c9c6c0fc5fcc8d8ee33 Mon Sep 17 00:00:00 2001 From: Flavia Moraes Date: Tue, 22 Aug 2023 10:27:21 -0300 Subject: [PATCH] fix: fix popover behavior to accept click (default) OR hover event --- packages/yoga/src/Popover/web/Popover.jsx | 41 ++++++++++++++++------- 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/packages/yoga/src/Popover/web/Popover.jsx b/packages/yoga/src/Popover/web/Popover.jsx index 4e8637c646..10d86e7b2e 100644 --- a/packages/yoga/src/Popover/web/Popover.jsx +++ b/packages/yoga/src/Popover/web/Popover.jsx @@ -1,5 +1,5 @@ -import React, { useState } from 'react'; -import { node, number, oneOf, string } from 'prop-types'; +import React, { useState, useEffect, useRef } from 'react'; +import { bool, node, number, oneOf, string } from 'prop-types'; import { Text } from '@gympass/yoga'; import { PopoverContainer, PopoverButton, Wrapper } from './styles'; @@ -13,10 +13,26 @@ function Popover({ height, zIndex, a11yId, + hover, ...props }) { + const ref = useRef(null); const [isPopoverOpen, setIsPopoverOpen] = useState(false); + useEffect(() => { + const handleClickOutside = event => { + if (ref.current && !ref.current.contains(event.target)) { + setIsPopoverOpen(false); + } + }; + + document.addEventListener('click', handleClickOutside, true); + + return () => { + document.removeEventListener('click', handleClickOutside, true); + }; + }, [setIsPopoverOpen]); + const handleShowPopover = () => { setIsPopoverOpen(true); }; @@ -25,6 +41,10 @@ function Popover({ setIsPopoverOpen(false); }; + const toggleOpenPopover = () => { + setIsPopoverOpen(!isPopoverOpen); + }; + return ( {isPopoverOpen && ( @@ -49,16 +69,11 @@ function Popover({ event.preventDefault()} - onKeyDown={event => { - if (event.key === 'Enter') { - setIsPopoverOpen(current => !current); - } - }} + ref={ref} + onMouseEnter={hover ? handleShowPopover : undefined} + onMouseLeave={hover ? handleHidePopover : undefined} + onClick={!hover ? toggleOpenPopover : undefined} + onKeyDown={event => event.key === 'Enter' && toggleOpenPopover} > {children} @@ -89,6 +104,7 @@ Popover.propTypes = { width: number, height: number, zIndex: number, + hover: bool, }; Popover.defaultProps = { @@ -98,6 +114,7 @@ Popover.defaultProps = { width: 265, height: 200, zIndex: 1, + hover: false, }; export default Popover;