refactor(webui): share outside-dismiss behavior

This commit is contained in:
2026-07-21 13:35:09 +02:00
parent 7526c5ebb2
commit 2ac1e64daa
3 changed files with 38 additions and 47 deletions

View File

@@ -0,0 +1,30 @@
import { useEffect, useRef } from "react";
export default function useOutsideDismiss<TElement extends HTMLElement = HTMLDivElement>(
active: boolean,
onDismiss: () => void,
) {
const rootRef = useRef<TElement | null>(null);
useEffect(() => {
if (!active) return;
function handlePointerDown(event: PointerEvent) {
if (!rootRef.current || rootRef.current.contains(event.target as Node)) return;
onDismiss();
}
function handleKeyDown(event: KeyboardEvent) {
if (event.key === "Escape") onDismiss();
}
document.addEventListener("pointerdown", handlePointerDown);
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("pointerdown", handlePointerDown);
document.removeEventListener("keydown", handleKeyDown);
};
}, [active, onDismiss]);
return rootRef;
}