Skip to content

Commit

Permalink
fix: fix popover behavior to accept click (default) OR hover event
Browse files Browse the repository at this point in the history
  • Loading branch information
flavia-moraes committed Aug 22, 2023
1 parent 37d07a5 commit 3e327e2
Showing 1 changed file with 29 additions and 12 deletions.
41 changes: 29 additions & 12 deletions packages/yoga/src/Popover/web/Popover.jsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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);
};
Expand All @@ -25,6 +41,10 @@ function Popover({
setIsPopoverOpen(false);
};

const toggleOpenPopover = () => {
setIsPopoverOpen(!isPopoverOpen);
};

return (
<Wrapper {...props}>
{isPopoverOpen && (
Expand All @@ -49,16 +69,11 @@ function Popover({

<PopoverButton
{...(a11yId && { 'aria-describedby': a11yId })}
onMouseEnter={handleShowPopover}
onMouseLeave={handleHidePopover}
onTouchStart={handleShowPopover}
onTouchEnd={handleHidePopover}
onClick={event => 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}
</PopoverButton>
Expand Down Expand Up @@ -89,6 +104,7 @@ Popover.propTypes = {
width: number,
height: number,
zIndex: number,
hover: bool,
};

Popover.defaultProps = {
Expand All @@ -98,6 +114,7 @@ Popover.defaultProps = {
width: 265,
height: 200,
zIndex: 1,
hover: false,
};

export default Popover;

0 comments on commit 3e327e2

Please sign in to comment.