implement click outside post menu to close

This commit is contained in:
Tom
2023-05-25 17:48:55 +02:00
parent ada945054d
commit 9c537b6286
3 changed files with 258 additions and 162 deletions
+38 -5
View File
@@ -68,6 +68,8 @@ const Board = () => {
const linkRef = useRef();
const threadMenuRefs = useRef({});
const replyMenuRefs = useRef({});
const postMenuRef = useRef(null);
const postMenuCatalogRef = useRef(null);
const { feed, hasMore, loadMore } = useFeed({subplebbitAddresses: [`${selectedAddress}`], sortType: 'new'});
const subplebbit = useSubplebbit({subplebbitAddress: selectedAddress});
@@ -111,6 +113,25 @@ const Board = () => {
const handleOptionClick = () => {
setOpenMenuCid(null);
};
const handleOutsideClick = (e) => {
if (openMenuCid !== null && !postMenuRef.current.contains(e.target) && !postMenuCatalogRef.current.contains(e.target)) {
setOpenMenuCid(null);
}
};
useEffect(() => {
if (openMenuCid !== null) {
document.addEventListener('click', handleOutsideClick);
} else {
document.removeEventListener('click', handleOutsideClick);
}
return () => {
document.removeEventListener('click', handleOutsideClick);
};
}, [openMenuCid]);
const errorString = useMemo(() => {
@@ -829,10 +850,14 @@ const Board = () => {
<PostMenu
key={`pmb-${index}`}
title="Post menu"
ref={el => threadMenuRefs.current[thread.cid] = el}
ref={el => {
threadMenuRefs.current[thread.cid] = el;
postMenuRef.current = el;
}}
className='post-menu-button'
rotated={openMenuCid === thread.cid}
onClick={() => {
onClick={(event) => {
event.stopPropagation();
const rect = threadMenuRefs.current[thread.cid].getBoundingClientRect();
setMenuPosition({top: rect.top + window.scrollY, left: rect.left});
setOpenMenuCid(prevCid => (prevCid === thread.cid ? null : thread.cid));
@@ -842,6 +867,8 @@ const Board = () => {
</PostMenu>
{createPortal(
<PostMenuCatalog selectedStyle={selectedStyle}
ref={el => {postMenuCatalogRef.current = el}}
onClick={(event) => event.stopPropagation()}
style={{position: "absolute",
top: menuPosition.top + 7,
left: menuPosition.left}}>
@@ -1029,19 +1056,25 @@ const Board = () => {
<PostMenu
key={`pmb-${index}`}
title="Post menu"
ref={el => replyMenuRefs.current[reply.cid] = el}
ref={el => {
replyMenuRefs.current[reply.cid] = el;
postMenuRef.current = el;
}}
className='post-menu-button'
rotated={openMenuCid === reply.cid}
onClick={() => {
onClick={(event) => {
event.stopPropagation();
const rect = replyMenuRefs.current[reply.cid].getBoundingClientRect();
setMenuPosition({top: rect.top + window.scrollY, left: rect.left});
setOpenMenuCid(prevCid => (prevCid === reply.cid ? null : reply.cid));
}}
}}
>
</PostMenu>
{createPortal(
<PostMenuCatalog selectedStyle={selectedStyle}
ref={el => {postMenuCatalogRef.current = el}}
onClick={(event) => event.stopPropagation()}
style={{position: "absolute",
top: menuPosition.top + 7,
left: menuPosition.left}}>