From b702aa04015bf96f76441892bffc203ab721040b Mon Sep 17 00:00:00 2001 From: daniel31x13 Date: Sat, 20 Apr 2024 10:49:06 -0400 Subject: [PATCH] small improvement --- components/ClickAwayHandler.tsx | 31 +++++++++++++++++++++++++------ pages/_app.tsx | 1 + 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/components/ClickAwayHandler.tsx b/components/ClickAwayHandler.tsx index 63378a1d..e8e88784 100644 --- a/components/ClickAwayHandler.tsx +++ b/components/ClickAwayHandler.tsx @@ -8,19 +8,38 @@ type Props = { onMount?: (rect: DOMRect) => void; }; +function getZIndex(element: HTMLElement): number { + let zIndex = 0; + while (element) { + const zIndexStyle = window + .getComputedStyle(element) + .getPropertyValue("z-index"); + const numericZIndex = Number(zIndexStyle); + if (zIndexStyle !== "auto" && !isNaN(numericZIndex)) { + zIndex = numericZIndex; + break; + } + element = element.parentElement as HTMLElement; + } + return zIndex; +} + function useOutsideAlerter( ref: RefObject, onClickOutside: Function ) { useEffect(() => { - function handleClickOutside(event: Event) { - if ( - ref.current && - !ref.current.contains(event.target as HTMLInputElement) - ) { - onClickOutside(event); + function handleClickOutside(event: MouseEvent) { + const clickedElement = event.target as HTMLElement; + if (ref.current && !ref.current.contains(clickedElement)) { + const refZIndex = getZIndex(ref.current); + const clickedZIndex = getZIndex(clickedElement); + if (clickedZIndex <= refZIndex) { + onClickOutside(event); + } } } + document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); diff --git a/pages/_app.tsx b/pages/_app.tsx index 3cdd0f50..0ece19db 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -75,6 +75,7 @@ export default function App({ {message} {t.type !== "loading" && (