Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(core): TopNavMegaMenu hover-then-click no longer dismisses the panel (#3121) (#4555)

Xinzi Zhoue19719c2a8ae
diff --git a/.changeset/topnav-mega-menu-click-guard.md b/.changeset/topnav-mega-menu-click-guard.md
new file mode 100644
index 0000000000..2ac4c204fc
--- /dev/null
+++ b/.changeset/topnav-mega-menu-click-guard.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] TopNavMegaMenu: fix the hover-then-click flicker where clicking a nav item after hovering dismissed the mega menu. The trigger is registered as the native invoker for its `popover="auto"` panel and uses a Vercel-style hover→click guard, so the click that naturally follows a hover confirms and pins the panel open instead of toggling it shut. Native outside-click, Escape dismissal, and sibling-popover exclusivity are preserved. Click/keyboard opens are pinned (persist past mouse-leave); hover opens stay transient. Keyboard activation (Enter/Space) always opens and moves focus into the panel, while touch/click without a preceding hover toggles cleanly (#3121)
+@imdreamrunner
diff --git a/packages/core/src/TopNav/TopNavMegaMenu.test.tsx b/packages/core/src/TopNav/TopNavMegaMenu.test.tsx
index e0aae0aec6..7939e999c3 100644
--- a/packages/core/src/TopNav/TopNavMegaMenu.test.tsx
+++ b/packages/core/src/TopNav/TopNavMegaMenu.test.tsx
@@ -9,13 +9,65 @@
* SYNC: When TopNavMegaMenu changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';
-import {render, screen} from '@testing-library/react';
+import {describe, it, expect, vi, beforeAll, afterAll, afterEach} from 'vitest';
+import {render, screen, act, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {TopNavMegaMenu} from './TopNavMegaMenu';
import {TopNavMegaMenuItem} from './TopNavMegaMenuItem';
import {TopNavRenderContext} from './TopNavRenderContext';
+// =============================================================================
+// Popover API mock — jsdom implements no Popover API, so default-mode tests
+// that actually open/close the panel install these shims on HTMLElement.
+// =============================================================================
+
+let originalMatches: typeof HTMLElement.prototype.matches;
+
+function installPopoverApiMock() {
+ originalMatches = HTMLElement.prototype.matches;
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ // Model the browser's auto-popover stack: opening one auto popover evicts
+ // any currently open auto popover before showing the new one.
+ if (this.getAttribute('popover') === 'auto') {
+ document
+ .querySelectorAll<HTMLElement>('[popover="auto"][popover-open]')
+ .forEach(openPopover => {
+ if (openPopover === this) {
+ return;
+ }
+ openPopover.removeAttribute('popover-open');
+ const closeEvent = new Event('toggle', {bubbles: false});
+ Object.defineProperty(closeEvent, 'newState', {value: 'closed'});
+ openPopover.dispatchEvent(closeEvent);
+ });
+ }
+ this.setAttribute('popover-open', '');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ const event = new Event('toggle', {bubbles: false});
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ return originalMatches.call(this, selector);
+ };
+}
+
+function restorePopoverApiMock() {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = originalMatches;
+}
+
// =============================================================================
// Default (desktop) mode
// =============================================================================
@@ -80,37 +132,8 @@ describe('TopNavMegaMenu — default mode', () => {
// =============================================================================
describe('TopNavMegaMenu — popup semantics', () => {
- // Mock the Popover API (not implemented in jsdom).
- const originalMatches = HTMLElement.prototype.matches;
-
- beforeAll(() => {
- HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
- this.setAttribute('popover-open', '');
- const event = new Event('toggle', {bubbles: false});
- Object.defineProperty(event, 'newState', {value: 'open'});
- this.dispatchEvent(event);
- });
- HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
- this.removeAttribute('popover-open');
- const event = new Event('toggle', {bubbles: false});
- Object.defineProperty(event, 'newState', {value: 'closed'});
- this.dispatchEvent(event);
- });
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (HTMLElement.prototype as any).matches = function (
- selector: string,
- ): boolean {
- if (selector === ':popover-open') {
- return this.hasAttribute('popover-open');
- }
- return originalMatches.call(this, selector);
- };
- });
-
- afterAll(() => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (HTMLElement.prototype as any).matches = originalMatches;
- });
+ beforeAll(installPopoverApiMock);
+ afterAll(restorePopoverApiMock);
it('trigger aria-controls resolves to the popup element', async () => {
const user = userEvent.setup();
@@ -223,6 +246,383 @@ describe('TopNavMegaMenu — popup semantics', () => {
});
});
+// =============================================================================
+// Hover → click guard (default mode) — issue #3121
+//
+// The trigger opens on hover and on click. A hover-open records a timestamp so
+// the click that naturally follows a hover confirms and pins the panel for
+// CLICK_GUARD_MS (the panel just appeared under the cursor) instead of toggling
+// it shut. Deliberate clicks outside that window still toggle.
+// =============================================================================
+
+describe('TopNavMegaMenu — hover/click guard (default mode)', () => {
+ beforeAll(installPopoverApiMock);
+ afterAll(restorePopoverApiMock);
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ function renderMenu() {
+ render(
+ <TopNavMegaMenu
+ label="Products"
+ items={<TopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />,
+ );
+ return screen.getByRole('button', {name: 'Products'});
+ }
+
+ it('keeps the panel open when a hover-open is immediately clicked', async () => {
+ vi.useFakeTimers({shouldAdvanceTime: true});
+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});
+ const trigger = renderMenu();
+
+ // Hover opens the panel after the show delay (150ms).
+ await user.hover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // The click that naturally follows the hover must NOT toggle it shut.
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // It is still a click interaction, so it pins the panel just like a
+ // click-open. Leaving the trigger must not dismiss it.
+ await user.unhover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('closes on a click that lands well after the hover-open (past the guard)', async () => {
+ vi.useFakeTimers({shouldAdvanceTime: true});
+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});
+ const trigger = renderMenu();
+
+ await user.hover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // Past the guard window, a click is a deliberate dismissal.
+ act(() => {
+ vi.advanceTimersByTime(600);
+ });
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('toggles cleanly for click-only interaction (no hover, no guard)', async () => {
+ const user = userEvent.setup();
+ const trigger = renderMenu();
+
+ // A click with no preceding hover opens...
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // ...and the next click closes — the guard only applies after a hover-open.
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('closes a hover-opened (transient) panel when the pointer leaves', async () => {
+ vi.useFakeTimers({shouldAdvanceTime: true});
+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});
+ const trigger = renderMenu();
+
+ await user.hover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // Leaving closes it after hideDelay (250ms) — hover opens are transient.
+ await user.unhover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('keeps a click-opened (pinned) panel open when the pointer leaves', async () => {
+ vi.useFakeTimers({shouldAdvanceTime: true});
+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});
+ const trigger = renderMenu();
+
+ // A click pins the panel open (a deliberate open should persist).
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ await user.unhover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(400);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('re-entering the trigger cancels a pending hide', async () => {
+ vi.useFakeTimers({shouldAdvanceTime: true});
+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});
+ const trigger = renderMenu();
+
+ await user.hover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // Leave (schedules a hide), then return before hideDelay elapses.
+ await user.unhover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(100);
+ });
+ await user.hover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('does not reopen when the pointer enters the panel after close', async () => {
+ vi.useFakeTimers({shouldAdvanceTime: true});
+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});
+ const trigger = renderMenu();
+ const panel = screen.getByRole('group', {
+ name: 'Products',
+ hidden: true,
+ });
+
+ await user.click(trigger);
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ // The exit transition can leave the closed panel briefly hit-testable.
+ fireEvent.mouseEnter(panel);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('re-hovering an open panel does not refresh the click guard', async () => {
+ vi.useFakeTimers({shouldAdvanceTime: true});
+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});
+ const trigger = renderMenu();
+
+ await user.hover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // Wait past the guard window, re-hovering along the way. The re-hover must
+ // NOT re-stamp the guard timestamp (only a fresh open may), so the click
+ // below is still judged a deliberate close.
+ act(() => {
+ vi.advanceTimersByTime(600);
+ });
+ await user.hover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('opening a sibling mega menu closes the pinned menu through the native auto-popover stack', async () => {
+ vi.useFakeTimers({shouldAdvanceTime: true});
+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});
+ render(
+ <>
+ <TopNavMegaMenu
+ label="Products"
+ items={<TopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />
+ <TopNavMegaMenu
+ label="Solutions"
+ items={<TopNavMegaMenuItem title="Enterprise" href="/enterprise" />}
+ />
+ </>,
+ );
+
+ const products = screen.getByRole('button', {name: 'Products'});
+ const solutions = screen.getByRole('button', {name: 'Solutions'});
+
+ await user.click(products);
+ expect(products).toHaveAttribute('aria-expanded', 'true');
+
+ await user.hover(solutions);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+
+ expect(products).toHaveAttribute('aria-expanded', 'false');
+ expect(solutions).toHaveAttribute('aria-expanded', 'true');
+ });
+});
+
+// =============================================================================
+// Dismissal (default mode) — issue #3121
+//
+// The panel stays an *auto* popover for native light dismiss and stack
+// exclusivity. `popoverTarget` makes the button its native invoker so trigger
+// activation is not treated as an outside click before the guard can run.
+// jsdom cannot exercise that native event ordering; these tests lock in the
+// required wiring, while the end-to-end interaction is browser-verified in the
+// PR's manual test plan.
+// =============================================================================
+
+describe('TopNavMegaMenu — dismissal (default mode)', () => {
+ beforeAll(installPopoverApiMock);
+ afterAll(restorePopoverApiMock);
+
+ function renderAndOpen() {
+ render(
+ <TopNavMegaMenu
+ label="Products"
+ items={<TopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />,
+ );
+ return screen.getByRole('button', {name: 'Products'});
+ }
+
+ it('renders an auto popover and registers the trigger as its native invoker', () => {
+ const trigger = renderAndOpen();
+ const popup = document.getElementById(
+ trigger.getAttribute('aria-controls') as string,
+ );
+ expect(popup).toHaveAttribute('popover', 'auto');
+ expect(trigger).toHaveAttribute('popovertarget', popup?.id);
+ });
+
+ it('prevents the native invoker toggle so the click guard owns activation', async () => {
+ const trigger = renderAndOpen();
+
+ const clickEvent = new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ detail: 1,
+ });
+ fireEvent(trigger, clickEvent);
+
+ expect(clickEvent.defaultPrevented).toBe(true);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('reconciles a browser-initiated native light dismiss', async () => {
+ const user = userEvent.setup();
+ const trigger = renderAndOpen();
+
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ const popup = document.getElementById(
+ trigger.getAttribute('aria-controls') as string,
+ ) as HTMLElement;
+ popup.removeAttribute('popover-open');
+ const toggleEvent = new Event('toggle', {bubbles: false});
+ Object.defineProperty(toggleEvent, 'newState', {value: 'closed'});
+ fireEvent(popup, toggleEvent);
+
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+});
+
+// =============================================================================
+// Keyboard (default mode) — issue #3121
+//
+// Keyboard activation always OPENS (never toggles the panel closed) and moves
+// focus into the panel; Escape closes it and returns focus to the trigger.
+// =============================================================================
+
+describe('TopNavMegaMenu — keyboard (default mode)', () => {
+ beforeAll(installPopoverApiMock);
+ afterAll(restorePopoverApiMock);
+
+ it('opens on Enter (keyboard activation)', async () => {
+ const user = userEvent.setup();
+ render(
+ <TopNavMegaMenu
+ label="Products"
+ items={<TopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />,
+ );
+ const trigger = screen.getByRole('button', {name: 'Products'});
+ trigger.focus();
+
+ await user.keyboard('{Enter}');
+
+ // aria-expanded is the observable signal. Enter also auto-focuses the first
+ // link (unlike pointer/hover opens, which keep focus on the trigger), but
+ // that focus landing is only verifiable in a real browser — jsdom renders
+ // the popover content display:none, so activeElement can't move onto it
+ // (browser-verified via the Playwright checks for #3121). Panel content
+ // presence is deliberately NOT asserted: useLayer renders it into the DOM
+ // even while closed, so such an assertion would be vacuous.
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('opens on Space', async () => {
+ const user = userEvent.setup();
+ render(
+ <TopNavMegaMenu
+ label="Products"
+ items={<TopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />,
+ );
+ const trigger = screen.getByRole('button', {name: 'Products'});
+ trigger.focus();
+
+ await user.keyboard(' ');
+
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('keyboard activation never toggles an open panel closed', async () => {
+ const user = userEvent.setup();
+ render(
+ <TopNavMegaMenu
+ label="Products"
+ items={<TopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />,
+ );
+ const trigger = screen.getByRole('button', {name: 'Products'});
+
+ // Open via pointer (focus stays on the trigger).
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // Enter on an already-open panel keeps it open — no toggle-close.
+ trigger.focus();
+ await user.keyboard('{Enter}');
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('closes on Escape and returns focus to the trigger', async () => {
+ const user = userEvent.setup();
+ render(
+ <TopNavMegaMenu
+ label="Products"
+ items={<TopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />,
+ );
+ const trigger = screen.getByRole('button', {name: 'Products'});
+
+ // Pointer open leaves focus on the trigger.
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ await user.keyboard('{Escape}');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger).toHaveFocus();
+ });
+});
+
// =============================================================================
// Mobile-bar mode — should be hidden
// =============================================================================
diff --git a/packages/core/src/TopNav/TopNavMegaMenu.tsx b/packages/core/src/TopNav/TopNavMegaMenu.tsx
index 8b1292ee01..f202e705fa 100644
--- a/packages/core/src/TopNav/TopNavMegaMenu.tsx
+++ b/packages/core/src/TopNav/TopNavMegaMenu.tsx
@@ -12,6 +12,13 @@
* eliminating z-index stacking. CSS anchor positioning places the panel below
* the nav wrapper.
*
+ * The default (desktop) trigger opens on hover and click. Hover opens are
+ * transient; click/keyboard opens are pinned. A click shortly after hover-open
+ * confirms and pins the panel instead of closing it. The panel remains an auto
+ * popover for native dismissal and sibling exclusivity; `popoverTarget`
+ * registers the trigger as its native invoker so the guard runs before any
+ * dismiss.
+ *
* Supports three render modes via TopNavRenderContext:
* - 'default': desktop popover mega menu (hover/click triggered)
* - 'mobile-bar': returns null (hidden in compact mobile bar)
@@ -132,7 +139,10 @@ const styles = stylex.create({
// own content, keeping the surface radius/shadow static at the edges.
// Internal scroll is a stopgap until the mobile bottom-sheet lands.
panelViewportFit: {
- display: 'flex',
+ display: {
+ default: 'none',
+ ':popover-open': 'flex',
+ },
flexDirection: 'column',
maxHeight: `calc(100% - ${spacingVars['--spacing-3']})`,
},
@@ -360,6 +370,8 @@ TopNavMegaMenu.displayName = 'TopNavMegaMenu';
// DefaultMegaMenu — desktop popover mode
// =============================================================================
+const CLICK_GUARD_MS = 500;
+
function DefaultMegaMenu({
ref,
label,
@@ -373,26 +385,36 @@ function DefaultMegaMenu({
const showTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const triggerButtonRef = useRef<HTMLButtonElement | null>(null);
- const clickLockedRef = useRef(false);
+ const hoverOpenedAtRef = useRef(0);
+ const stickyRef = useRef(false);
const handlePopoverShow = useCallback(() => {
onOpenChange?.(true);
}, [onOpenChange]);
const handlePopoverHide = useCallback(() => {
+ hoverOpenedAtRef.current = 0;
+ stickyRef.current = false;
onOpenChange?.(false);
}, [onOpenChange]);
const popover = usePopover({
// role: 'none' — the panel exposes its own role="group" labeled by
- // `label`. Focus stays on the trigger while the panel is open, so a
- // role="dialog" aria-modal="true" wrapper would announce an unnamed
- // modal dialog around a grid of links.
+ // `label`. Pointer/hover opens keep focus on the trigger; keyboard and
+ // assistive-tech opens move focus into the panel (a labeled group you exit
+ // with Escape or by tabbing out). Either way role="dialog"
+ // aria-modal="true" would be wrong: it announces an unnamed modal dialog
+ // around a grid of links (and, when focus stays on the trigger, marks the
+ // focused control inert).
role: 'none',
// hasSurface: false — mega menu provides its own surface (panelContainer)
// with border-top and custom overflow. Animation is applied via the
// render() call's xstyle prop (panelAnimation), not the hook options.
hasSurface: false,
+ // Keep native outside-click/Escape dismissal and sibling exclusivity.
+ // The trigger's popoverTarget association prevents its activation from
+ // being treated as an ordinary outside interaction.
+ hasLightDismiss: true,
onShow: handlePopoverShow,
onHide: handlePopoverHide,
});
@@ -422,40 +444,75 @@ function DefaultMegaMenu({
const scheduleShow = useCallback(() => {
clearTimeouts();
showTimeoutRef.current = setTimeout(() => {
+ hoverOpenedAtRef.current = Date.now();
popover.show({skipAutoFocus: true});
}, delay);
- }, [clearTimeouts, popover, delay]);
+ }, [clearTimeouts, delay, popover]);
const scheduleHide = useCallback(() => {
clearTimeouts();
hideTimeoutRef.current = setTimeout(() => {
popover.hide();
}, hideDelay);
- }, [clearTimeouts, popover, hideDelay]);
+ }, [clearTimeouts, hideDelay, popover]);
- const handleMouseEnter = useCallback(() => {
- if (!clickLockedRef.current) {
+ const focusFirstPanelItem = useCallback(() => {
+ popover.contentRef.current
+ ?.querySelector<HTMLElement>(
+ 'a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])',
+ )
+ ?.focus();
+ }, [popover.contentRef]);
+
+ const handleTriggerMouseEnter = useCallback(() => {
+ clearTimeouts();
+ if (!popover.isOpen) {
scheduleShow();
}
- }, [scheduleShow]);
+ }, [clearTimeouts, popover.isOpen, scheduleShow]);
+
+ const handlePanelMouseEnter = useCallback(() => {
+ clearTimeouts();
+ }, [clearTimeouts]);
const handleMouseLeave = useCallback(() => {
- if (!clickLockedRef.current) {
+ if (!stickyRef.current) {
scheduleHide();
}
}, [scheduleHide]);
- const handleClick = useCallback(() => {
- clearTimeouts();
- if (popover.isOpen) {
- clickLockedRef.current = false;
- popover.hide();
- triggerButtonRef.current?.focus();
- } else {
- clickLockedRef.current = true;
- popover.show();
- }
- }, [popover, clearTimeouts]);
+ const handleClick = useCallback(
+ (event: React.MouseEvent<HTMLButtonElement>) => {
+ // Cancel the native invoker toggle so this guard is the single source of
+ // truth for trigger activation. popoverTarget still establishes the
+ // invoker relationship used by native light-dismiss and stacking.
+ event.preventDefault();
+ clearTimeouts();
+
+ if (event.detail === 0) {
+ stickyRef.current = true;
+ hoverOpenedAtRef.current = 0;
+ if (popover.isOpen) {
+ focusFirstPanelItem();
+ } else {
+ popover.show();
+ }
+ } else if (!popover.isOpen) {
+ stickyRef.current = true;
+ popover.show({skipAutoFocus: true});
+ } else if (Date.now() - hoverOpenedAtRef.current < CLICK_GUARD_MS) {
+ // A click that naturally follows a hover-open confirms the open state
+ // instead of toggling the panel shut. From here it behaves like any
+ // other click-open and stays pinned until explicit dismissal.
+ stickyRef.current = true;
+ hoverOpenedAtRef.current = 0;
+ } else {
+ popover.hide();
+ triggerButtonRef.current?.focus();
+ }
+ },
+ [clearTimeouts, focusFirstPanelItem, popover],
+ );
useEffect(() => {
return () => {
@@ -469,8 +526,10 @@ function DefaultMegaMenu({
ref={mergeRefs(triggerButtonRef, ref)}
type="button"
{...popover.triggerProps}
+ // Native invoker prevents trigger light-dismiss.
+ popoverTarget={popover.id}
onClick={handleClick}
- onMouseEnter={handleMouseEnter}
+ onMouseEnter={handleTriggerMouseEnter}
onMouseLeave={handleMouseLeave}
{...mergeProps(
themeProps('top-nav-mega-menu'),
@@ -494,7 +553,7 @@ function DefaultMegaMenu({
// for action menus; link mega menus are the documented anti-case).
role="group"
aria-label={label}
- onMouseEnter={handleMouseEnter}
+ onMouseEnter={handlePanelMouseEnter}
onMouseLeave={handleMouseLeave}
{...stylex.props(styles.panelContainer)}>
<div {...stylex.props(styles.panelContent)}>