-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathindex.tsx
49 lines (42 loc) · 1.25 KB
/
index.tsx
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
45
46
47
48
49
import { Popover } from '@wordpress/components';
import { useState, useCallback, useMemo } from '@wordpress/element';
import type { FC } from 'react';
import { useOnClickOutside } from '../use-on-click-outside';
interface PopoverComponentProps {
children: React.ReactNode;
}
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: FC<PopoverComponentProps> = useMemo(
() =>
({ 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,
};
};