From d8c5e56b7d6bf7dbec971489c866cfba833507dd Mon Sep 17 00:00:00 2001 From: KingRainbow44 Date: Tue, 5 Sep 2023 22:34:12 -0400 Subject: [PATCH] Better context menu UI --- src/css/components/ContextMenu.scss | 3 ++- src/ui/components/common/ContextMenu.tsx | 4 ++++ src/utils/context.ts | 30 ++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 src/utils/context.ts diff --git a/src/css/components/ContextMenu.scss b/src/css/components/ContextMenu.scss index 42c0e7f..c378dc7 100644 --- a/src/css/components/ContextMenu.scss +++ b/src/css/components/ContextMenu.scss @@ -1,5 +1,5 @@ .ContextMenu { - @apply absolute hidden; + @apply absolute hidden flex-col; padding: 5px; border-radius: 5px; @@ -17,6 +17,7 @@ border-radius: 5px; &:hover { + user-select: none; background-color: #0c0c0c; } } diff --git a/src/ui/components/common/ContextMenu.tsx b/src/ui/components/common/ContextMenu.tsx index 3954a06..4bda246 100644 --- a/src/ui/components/common/ContextMenu.tsx +++ b/src/ui/components/common/ContextMenu.tsx @@ -1,5 +1,7 @@ import React from "react"; +import { openContext } from "@utils/context"; + import "@css/components/ContextMenu.scss"; export type ContextOption = { @@ -34,6 +36,8 @@ export function showMenu(id: string, x: number, y: number): void { menu.style.display = "flex"; menu.style.left = x + "px"; menu.style.top = y + "px"; + + openContext(menu); } } diff --git a/src/utils/context.ts b/src/utils/context.ts new file mode 100644 index 0000000..604d0f8 --- /dev/null +++ b/src/utils/context.ts @@ -0,0 +1,30 @@ +let currentContext: HTMLElement | null = null; +window.addEventListener("click", closeContext); + +/** + * Handles clicking around the page. + * + * @param e The event. + */ +export function closeContext(e: MouseEvent): void { + // Check if the click was within the confines of the context menu. + if (currentContext && !currentContext.contains(e.target as Node)) { + currentContext.style.display = "none"; + currentContext = null; + } +} + +/** + * Sets the current context menu. + * + * @param element The context menu to set. + */ +export function openContext(element: HTMLElement): void { + // Close any open context menus. + if (currentContext) { + currentContext.style.display = "none"; + } + + // Set the current context menu. + currentContext = element; +}