feat: update context menu to use references
This commit is contained in:
parent
aa3c3df5da
commit
26ee4b84a9
@ -1,4 +1,4 @@
|
||||
import { MouseEventHandler, useEffect, useState } from "react";
|
||||
import { createRef, MouseEventHandler, useEffect, useState } from "react";
|
||||
import { useSession } from "./Session";
|
||||
|
||||
interface ContextMenuItem {
|
||||
@ -13,11 +13,12 @@ export default function Avatar() {
|
||||
mouseX: number;
|
||||
mouseY: number;
|
||||
}>({ open: false, mouseX: 0, mouseY: 0 });
|
||||
const contextMenuRef = createRef<HTMLUListElement>();
|
||||
const avatarRef = createRef<HTMLDivElement>();
|
||||
|
||||
const contextMenuItems: ContextMenuItem[] = [
|
||||
{ label: "View Profile", onClick: () => console.log("View Profile") },
|
||||
{ label: "Edit Profile", onClick: () => console.log("Edit Profile") },
|
||||
{ label: "Logout", onClick: () => onLogout() },
|
||||
{ label: "View Profile", onClick: handleViewProfile },
|
||||
{ label: "Logout", onClick: onLogout },
|
||||
];
|
||||
|
||||
const handleMenuClick: MouseEventHandler<HTMLDivElement> = (event) => {
|
||||
@ -40,29 +41,43 @@ export default function Avatar() {
|
||||
const handleMenuClose = () => {
|
||||
setContextMenu({ ...contextMenu, open: false });
|
||||
};
|
||||
const handleCloseContextMenuOutside: MouseEventHandler<Document> = (
|
||||
event
|
||||
) => {
|
||||
const handleCloseContextMenuOutside: (event: MouseEvent) => void = (ev) => {
|
||||
if (
|
||||
!event.target ||
|
||||
(!(event.target as Element).closest(".context-menu") &&
|
||||
!(event.target as Element).closest(".avatar"))
|
||||
!(
|
||||
contextMenuRef.current?.contains(ev.target as Node) ||
|
||||
avatarRef.current?.contains(ev.target as Node)
|
||||
)
|
||||
) {
|
||||
handleMenuClose();
|
||||
}
|
||||
};
|
||||
|
||||
const [dialog, setDialog] = useState(<></>);
|
||||
const dialogRef = createRef<HTMLDialogElement>();
|
||||
|
||||
function handleViewProfile() {
|
||||
handleMenuClose();
|
||||
dialogRef.current?.showModal();
|
||||
setDialog(
|
||||
<ul>
|
||||
<li>username: {user?.username}</li>
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="avatar"
|
||||
onContextMenu={handleMenuClick}
|
||||
style={{ display: user ? "block" : "none" }}
|
||||
onClick={handleMenuClick}
|
||||
ref={avatarRef}
|
||||
>
|
||||
{user?.username}
|
||||
👤 {user?.username}
|
||||
{contextMenu.open && (
|
||||
<ul
|
||||
className="context-menu"
|
||||
ref={contextMenuRef}
|
||||
style={{
|
||||
zIndex: 3,
|
||||
position: "absolute",
|
||||
@ -93,6 +108,15 @@ export default function Avatar() {
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<dialog
|
||||
id="AvatarDialog"
|
||||
ref={dialogRef}
|
||||
onClick={(event) => {
|
||||
event.currentTarget.close();
|
||||
}}
|
||||
>
|
||||
{dialog}
|
||||
</dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user