Menu will always close when clicking outside the menu, press Escape to close open menu

This commit is contained in:
Martin Berg Alstad 2023-01-14 15:03:31 +01:00
parent 996f9fac8c
commit d2d75721d9

View File

@ -40,24 +40,32 @@ const MyMenu: Component<MenuProps> = (
} }
} }
function keypress(e: KeyboardEvent): void {
if (e.key === "Escape") {
closeMenu();
}
}
if (isOpen()) { if (isOpen()) {
document.addEventListener("click", click); document.addEventListener("click", click);
document.addEventListener("keyup", keypress);
} }
else { else {
document.removeEventListener("click", click); document.removeEventListener("click", click);
document.removeEventListener("keyup", keypress);
} }
}); });
return ( // TODO transition return ( // TODO transition
<div class={ `${ className }` } id={ id }> <div class={ `${ className }` } id={ id }>
<Button title={ title ?? undefined } <Button title={ title }
onClick={ toggleMenu } onClick={ toggleMenu }
className={ `flex-row-center ${ buttonClassName }` }> className={ `flex-row-center ${ buttonClassName }` }>
{ button } { button }
</Button> </Button>
<Show when={isOpen()} keyed> <Show when={ isOpen() } keyed>
<div <div
class={ `absolute bg-default-bg border border-gray-500 rounded-b-xl mt-1 w-max z-50 ${ itemsClassName }` }> class={ `absolute bg-default-bg border border-gray-500 rounded-b-xl mt-1 w-max z-50 ${ itemsClassName }` }>
<div class={ "mx-1" }>{ children }</div> <div class={ "mx-1" }>{ children }</div>