Attempt to fix nav menu not closable when click outside

This commit is contained in:
Lim Chee Aun 2023-04-26 13:23:54 +08:00
parent 211e4ff74d
commit 960ce07501

View file

@ -1,4 +1,11 @@
import { Menu, MenuDivider, MenuItem } from '@szhsin/react-menu';
import {
ControlledMenu,
MenuDivider,
MenuItem,
useClick,
useMenuState,
} from '@szhsin/react-menu';
import { useRef } from 'preact/hooks';
import { useLongPress } from 'use-long-press';
import { useSnapshot } from 'valtio';
@ -39,23 +46,20 @@ function NavMenu(props) {
},
);
const buttonRef = useRef();
const [menuState, toggleMenu] = useMenuState();
const anchorProps = useClick(menuState.state, toggleMenu);
return (
<Menu
portal={{
target: document.body,
}}
{...props}
overflow="auto"
viewScroll="close"
boundingBoxPadding="8 8 8 8"
unmountOnClose
menuButton={({ open }) => (
<>
<button
ref={buttonRef}
type="button"
class={`button plain nav-menu-button ${
moreThanOneAccount ? 'with-avatar' : ''
} ${open ? 'active' : ''}`}
style={{ position: 'relative' }}
{...anchorProps}
onContextMenu={(e) => {
e.preventDefault();
states.showAccounts = true;
@ -65,8 +69,7 @@ function NavMenu(props) {
{moreThanOneAccount && (
<Avatar
url={
currentAccount?.info?.avatar ||
currentAccount?.info?.avatarStatic
currentAccount?.info?.avatar || currentAccount?.info?.avatarStatic
}
size="l"
squircle={currentAccount?.info?.bot}
@ -74,7 +77,25 @@ function NavMenu(props) {
)}
<Icon icon="menu" size={moreThanOneAccount ? 's' : 'l'} />
</button>
)}
<ControlledMenu
{...menuState}
anchorRef={buttonRef}
onClose={() => {
toggleMenu(false);
}}
containerProps={{
onClick: () => {
toggleMenu(false);
},
}}
portal={{
target: document.body,
}}
{...props}
overflow="auto"
viewScroll="close"
boundingBoxPadding="8 8 8 8"
unmountOnClose
>
{!!snapStates.appVersion?.commitHash &&
__COMMIT_HASH__ !== snapStates.appVersion.commitHash && (
@ -179,7 +200,8 @@ function NavMenu(props) {
</MenuItem>
</>
)}
</Menu>
</ControlledMenu>
</>
);
}