refactor: Remove neutral contrast theme adjustment and improve floating menu event handling by delaying listeners and checking for unmounted elements.

This commit is contained in:
2025-11-25 14:12:53 +01:00
parent 30602e6b66
commit 2c42e63bab
4 changed files with 27 additions and 95 deletions
+21 -7
View File
@@ -218,8 +218,8 @@ const useFloatingMenu = ({
const raf = window.requestAnimationFrame;
const rafId = raf
? raf(() => {
ignoreFocusEvents = false;
})
ignoreFocusEvents = false;
})
: null;
if (!anchorRef?.current) {
@@ -231,9 +231,18 @@ const useFloatingMenu = ({
if (event.type === 'focusin' && ignoreFocusEvents) {
return;
}
const target = event.target;
// If the target is no longer in the document, it means it was unmounted
// (e.g. due to a re-render caused by the open action).
// In this case, we should ignore the event.
if (target instanceof Node && !document.contains(target)) {
return;
}
const menu = menuRef.current;
const anchor = anchorRef?.current;
if ((anchor && anchor.contains(event.target)) || (menu && menu.contains(event.target))) {
if ((anchor && anchor.contains(target)) || (menu && menu.contains(target))) {
return;
}
close();
@@ -245,11 +254,16 @@ const useFloatingMenu = ({
}
};
document.addEventListener('mousedown', handlePointer);
document.addEventListener('touchstart', handlePointer, { passive: true });
document.addEventListener('focusin', handlePointer);
document.addEventListener('keydown', handleKeyDown);
// Delay adding listeners to avoid capturing the event that opened the menu
const timer = setTimeout(() => {
document.addEventListener('mousedown', handlePointer);
document.addEventListener('touchstart', handlePointer, { passive: true });
document.addEventListener('focusin', handlePointer);
document.addEventListener('keydown', handleKeyDown);
}, 0);
return () => {
clearTimeout(timer);
if (rafId != null) {
window.cancelAnimationFrame(rafId);
}