forked from 10up/block-components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (39 loc) · 1.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { Popover } from '@wordpress/components';
import { useState, useCallback, useMemo } from '@wordpress/element';
import { useOnClickOutside } from '../use-on-click-outside';
export const usePopover = () => {
// Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [popoverAnchor, setPopoverAnchor] = useState();
const [isVisible, setIsVisible] = useState(false);
const toggleVisible = useCallback(() => {
setIsVisible((visible) => !visible);
}, []);
const toggleProps = {
onClick: toggleVisible,
'aria-expanded': isVisible,
ref: setPopoverAnchor,
};
const ref = useOnClickOutside(() => setIsVisible(false));
const PopoverComponent = useMemo(
() =>
// eslint-disable-next-line react/prop-types
({ children }) => {
if (!isVisible) {
return null;
}
return (
<Popover ref={ref} anchor={popoverAnchor} focusOnMount={false} animate={false}>
<div style={{ padding: '16px', minWidth: '250px' }}>{children}</div>
</Popover>
);
},
[isVisible, popoverAnchor, ref],
);
return {
setPopoverAnchor,
toggleVisible,
toggleProps,
Popover: PopoverComponent,
};
};