Skip to content

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

TypeScript

fix(DropdownMenu): close submenu flyouts when the menu is light-dismissed (#6912)

Pushpak Siva Saie40ce5a0612d
diff --git a/.changeset/submenu-light-dismiss.md b/.changeset/submenu-light-dismiss.md
new file mode 100644
index 0000000000..ee2551fb87
--- /dev/null
+++ b/.changeset/submenu-light-dismiss.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] DropdownMenu submenu flyouts close with their menu when it is light-dismissed: previously a submenu opened by tap or a fast click stayed open (and re-anchored to the viewport corner) after the menu was dismissed and reopened. A hover-open scheduled on a submenu trigger before the menu closed from elsewhere is also cancelled, so it can no longer reopen a flyout behind the dismissed menu
+@Pushpak731
diff --git a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
index db173da75f..479465e78d 100644
--- a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
+++ b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
@@ -56,6 +56,7 @@ import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {renderDropdownItems} from '../DropdownMenu/renderDropdownItems';
import {
DropdownMenuContext,
+ DropdownMenuRootOpenContext,
type DropdownMenuContextValue,
type DropdownMenuSize,
} from '../DropdownMenu/DropdownMenuContext';
@@ -673,7 +674,9 @@ function BreadcrumbMenuTrigger({
stylex.props(menuStyles.menu),
)}>
<DropdownMenuContext value={contextValue}>
- {menuContent}
+ <DropdownMenuRootOpenContext value={popover.isOpen}>
+ {menuContent}
+ </DropdownMenuRootOpenContext>
</DropdownMenuContext>
</div>,
{
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index b86a2d8304..e35fe9134e 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -56,6 +56,7 @@ import {MenuBottomSheetActionList} from '../DropdownMenu/MenuBottomSheetActionLi
import {renderDropdownItems} from '../DropdownMenu/renderDropdownItems';
import {
DropdownMenuContext,
+ DropdownMenuRootOpenContext,
type DropdownMenuContextValue,
} from '../DropdownMenu/DropdownMenuContext';
import {
@@ -701,7 +702,9 @@ export function ContextMenu({
style,
)}>
<DropdownMenuContext value={contextValue}>
- {resolvedMenuContent}
+ <DropdownMenuRootOpenContext value={isOpen}>
+ {resolvedMenuContent}
+ </DropdownMenuRootOpenContext>
</DropdownMenuContext>
</div>
);
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 8e4f4aaad1..f937210990 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -60,6 +60,7 @@ import {
} from './menuItemRoles';
import {
DropdownMenuContext,
+ DropdownMenuRootOpenContext,
type DropdownMenuContextValue,
} from './DropdownMenuContext';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
@@ -987,6 +988,43 @@ function DropdownMenuPopover({
// above it ends the gesture in flight through this ref.
const cancelMenuPressRef = useRef<() => void>(() => {});
+ // Submenu flyouts are `popover="manual"` elements nested inside the menu's
+ // `popover="auto"` element, so the browser's light dismiss of the menu never
+ // reaches them: without a sweep they keep their open state and their
+ // top-layer entry while the menu is hidden, and re-anchor to the viewport
+ // corner when the menu reopens (#6893). Closing them through the popover
+ // API lets useLayer's toggle handling reset their state. Only flyouts that
+ // are actually open are touched: `:popover-open` ships wherever
+ // `hidePopover` does (they are one API), and the display fallback keeps its
+ // own open signal (`display: block`) so it is guarded the same way.
+ const hideOpenFlyouts = useCallback(() => {
+ const menuPopover = contentRef.current;
+ if (!menuPopover) {
+ return;
+ }
+ // Innermost first: hiding a flyout may unmount the flyouts nested inside
+ // it, and a detached element no longer has the toggle listener that
+ // resets its open state.
+ const flyouts = [
+ ...menuPopover.querySelectorAll<HTMLElement>('[popover]'),
+ ].reverse();
+ for (const flyout of flyouts) {
+ if (typeof flyout.hidePopover === 'function') {
+ if (flyout.matches(':popover-open')) {
+ flyout.hidePopover();
+ }
+ } else if (flyout.style.display === 'block') {
+ flyout.style.display = 'none';
+ const toggle = new Event('toggle', {bubbles: false});
+ Object.defineProperty(toggle, 'newState', {
+ value: 'closed',
+ configurable: true,
+ });
+ flyout.dispatchEvent(toggle);
+ }
+ }
+ }, []);
+
// Focus lands somewhere stated when the menu closes. A press outside that
// landed on a focusable control has already moved focus there; leave it.
// Otherwise — a row acted, Escape, a press on nothing — focus returns to
@@ -994,6 +1032,9 @@ function DropdownMenuPopover({
// keyboard (the modality tracker decides; the suppressed style hides the
// pointer case, which Safari would otherwise paint after a touch pick).
const handleLayerHide = useCallback(() => {
+ // Whatever closed the menu — light dismiss, the dismissal stack, Escape
+ // or a controlled close — its flyouts close with it.
+ hideOpenFlyouts();
if (suppressControlledRollbackHideRef.current) {
suppressControlledRollbackHideRef.current = false;
return;
@@ -1024,7 +1065,7 @@ function DropdownMenuPopover({
// also reaches a control the caller renders, which the browser would
// otherwise ring (Chromium after a mouse pick, WebKit after a touch).
focusForLastInput(trigger, {preventScroll: true});
- }, [isControlled, onOpenChange, prepareFocusReturn]);
+ }, [hideOpenFlyouts, isControlled, onOpenChange, prepareFocusReturn]);
// Defer item focus until the layer has committed open, so focus restore
// captures the trigger instead of the first menu item.
@@ -1694,7 +1735,9 @@ function DropdownMenuPopover({
)}>
<MenuRegionsContext value={hasRegions}>
<DropdownMenuContext value={contextValue}>
- {menuContent}
+ <DropdownMenuRootOpenContext value={isOpen}>
+ {menuContent}
+ </DropdownMenuRootOpenContext>
</DropdownMenuContext>
</MenuRegionsContext>
</div>,
diff --git a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx b/packages/core/src/DropdownMenu/DropdownMenuContext.tsx
index c287f2dce8..0a2f9c69fd 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuContext.tsx
@@ -65,6 +65,30 @@ export interface DropdownMenuContextValue {
menuLabel?: string;
}
+/**
+ * Whether the root menu of this layer tree is open; internal companion to
+ * `DropdownMenuContext`, on its own unexported context so the public
+ * `DropdownMenuContextValue` surface stays unchanged. A sub-menu's hover
+ * intent must die with the menu: a hover-open scheduled on its trigger
+ * before the menu closed from elsewhere would otherwise fire into the
+ * hidden menu and reopen the flyout behind it (#6893). `null` means no
+ * signal, treated as open, matching providers that have no state to give.
+ * @internal
+ */
+export const DropdownMenuRootOpenContext = createLayerScopedContext<
+ boolean | null
+>(null);
+DropdownMenuRootOpenContext.displayName = 'DropdownMenuRootOpenContext';
+
+/**
+ * Whether the root menu backing these compound items is open. True when no
+ * provider gave a signal.
+ * @internal
+ */
+export function useDropdownMenuRootOpen(): boolean {
+ return use(DropdownMenuRootOpenContext) !== false;
+}
+
export const DropdownMenuContext =
createLayerScopedContext<DropdownMenuContextValue | null>(null);
DropdownMenuContext.displayName = 'DropdownMenuContext';
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
index de12813a35..f890c351bd 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
@@ -1494,3 +1494,188 @@ describe('DropdownMenuSubMenu drill-in on a phone', () => {
screen.getAllByRole('menu', {name, ...h}).find(isShown);
});
});
+
+describe('DropdownMenuSubMenu light dismiss of the root menu (#6893)', () => {
+ // The browser closes the root `popover=\"auto\"` element itself on an outside
+ // tap; that path never reaches the submenu, whose flyout is
+ // `popover=\"manual\"`. Simulate it by hiding the root popover element
+ // directly, exactly what light dismiss does to it.
+ function lightDismissRootMenu() {
+ const menu = screen.getByRole('menu', {name: /Actions/, hidden: true});
+ const rootPopover = menu.closest<HTMLElement>('[popover]');
+ expect(rootPopover).not.toBeNull();
+ act(() => {
+ rootPopover!.hidePopover();
+ });
+ }
+
+ function getFlyoutPopover(name: RegExp) {
+ const flyout = screen.getByRole('menu', {name, hidden: true});
+ return flyout.closest<HTMLElement>('[popover]');
+ }
+
+ it('closes an open flyout when the root menu is light-dismissed', async () => {
+ const user = userEvent.setup();
+ render(<MoveMenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await user.click(trigger);
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+ const flyoutPopover = getFlyoutPopover(/Move to/);
+ expect(flyoutPopover).toHaveAttribute('popover-open', '');
+
+ lightDismissRootMenu();
+
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(flyoutPopover).not.toHaveAttribute('popover-open');
+ });
+
+ it('leaves the submenu collapsed when the menu reopens after a light dismiss', async () => {
+ const user = userEvent.setup();
+ render(<MoveMenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await user.click(trigger);
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ lightDismissRootMenu();
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(getFlyoutPopover(/Move to/)).not.toHaveAttribute('popover-open');
+ });
+
+ it('closes an open flyout when the root menu closes via controlled isMenuOpen', async () => {
+ const user = userEvent.setup();
+ function ControlledMenu() {
+ const [open, setOpen] = useState(true);
+ return (
+ <>
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ isMenuOpen={open}
+ onOpenChange={setOpen}>
+ <DropdownMenuSubMenu label="Move to">
+ <DropdownMenuItem label="Folder A" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>
+ <button type="button" onClick={() => setOpen(false)}>
+ close it
+ </button>
+ </>
+ );
+ }
+ render(<ControlledMenu />);
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await user.click(trigger);
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+ const flyoutPopover = getFlyoutPopover(/Move to/);
+
+ await user.click(screen.getByRole('button', {name: /close it/}));
+
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(flyoutPopover).not.toHaveAttribute('popover-open');
+ });
+
+ it('closes flyouts nested two levels deep on light dismiss', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuSubMenu label="Move to">
+ <DropdownMenuSubMenu label="Deeper">
+ <DropdownMenuItem label="Leaf" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenuSubMenu>
+ </DropdownMenu>,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const first = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await user.click(first);
+ await waitFor(() => {
+ expect(first).toHaveAttribute('aria-expanded', 'true');
+ });
+ const deeper = screen.getByRole('menuitem', {
+ name: /Deeper/,
+ hidden: true,
+ });
+ await user.click(deeper);
+ await waitFor(() => {
+ expect(deeper).toHaveAttribute('aria-expanded', 'true');
+ });
+ const firstPopover = getFlyoutPopover(/Move to/);
+ const deeperPopover = getFlyoutPopover(/Deeper/);
+
+ lightDismissRootMenu();
+
+ await waitFor(() => {
+ expect(first).toHaveAttribute('aria-expanded', 'false');
+ });
+ await waitFor(() => {
+ expect(deeper).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(firstPopover).not.toHaveAttribute('popover-open');
+ expect(deeperPopover).not.toHaveAttribute('popover-open');
+ });
+
+ // Regression for the stale hover timer: a hover over the submenu trigger
+ // schedules an open after the show delay. A press on the same trigger
+ // cancels its own scheduled hover-open (that is the click guard), so the
+ // way a timer is still pending at close time is a close that comes from
+ // elsewhere — here the root menu's light dismiss, the #6893 case. The
+ // close must cancel the scheduled hover-open: once the delay elapses the
+ // flyout stays closed instead of reopening behind the dismissed menu.
+ // Time is driven manually so the dismiss lands inside the show delay;
+ // auto-advancing timers would let the hover-open fire before it.
+ it('cancels a hover-open scheduled before the menu was closed from elsewhere', async () => {
+ vi.useFakeTimers();
+ try {
+ render(<MoveMenu />);
+ fireEvent.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ // Schedules the hover-open (default show delay 150ms).
+ fireEvent.mouseEnter(trigger);
+
+ // Close from elsewhere while the hover-open is still pending.
+ lightDismissRootMenu();
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ // The scheduled delay passes; the flyout must stay closed.
+ await act(async () => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(getFlyoutPopover(/Move to/)).not.toHaveAttribute('popover-open');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
index f36b9fff66..87edca09ef 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
@@ -97,7 +97,9 @@ import {
} from './menuItemRoles';
import {
DropdownMenuContext,
+ DropdownMenuRootOpenContext,
useDropdownMenuContext,
+ useDropdownMenuRootOpen,
type DropdownMenuContextValue,
} from './DropdownMenuContext';
import {focusMenuItemOnHover} from './menuItemHover';
@@ -451,13 +453,17 @@ export function DropdownMenuSubMenu(
// Hover intent and the shared hover→click guard only: this level owns its own
// click handling, roving focus and typeahead. popover="manual", so the
// invoker wiring other consumers need does not apply. A drill-in row has no
- // hover: a finger drives it, and a press opens it.
+ // hover: a finger drives it, and a press opens it. Hover is also gated on
+ // the root menu being open, so a hover-open scheduled before the menu
+ // closed from elsewhere is cancelled instead of firing into the hidden
+ // menu (#6893).
+ const isRootMenuOpen = useDropdownMenuRootOpen();
const {triggerProps, contentProps, confirmHoverOpen} =
useMenuHover<HTMLDivElement>({
show: showLayer,
hide: hideLayer,
isOpen: isFlyoutOpen,
- isEnabled: canOpen && !isDrillIn,
+ isEnabled: canOpen && !isDrillIn && isRootMenuOpen,
// The safe triangle toward the flyout's near edge is built from the
// flyout this component renders, not the hook's own list ref.
flyoutRef: menuRef,
@@ -770,7 +776,7 @@ export function DropdownMenuSubMenu(
: flyoutStyles.popoverCustomWidth(resolvedMenuWidth.value)
: flyoutStyles.popover;
- const nestedContent = (
+ const nestedRows = (
<DropdownMenuContext value={nestedMenuContext}>
{isDrillIn && (
<DropdownMenuItem
@@ -790,6 +796,14 @@ export function DropdownMenuSubMenu(
{children}
</DropdownMenuContext>
);
+ // Nested rows live in this level's flyout, a layer of their own where the
+ // layer-scoped signal resets; re-provide it so their pending hover intent
+ // dies with the root menu too.
+ const nestedContent = (
+ <DropdownMenuRootOpenContext value={isRootMenuOpen}>
+ {nestedRows}
+ </DropdownMenuRootOpenContext>
+ );
return (
<>
diff --git a/packages/core/src/hooks/useMenuHover.ts b/packages/core/src/hooks/useMenuHover.ts
index a2e229b2d5..7afcbf9c77 100644
--- a/packages/core/src/hooks/useMenuHover.ts
+++ b/packages/core/src/hooks/useMenuHover.ts
@@ -230,19 +230,6 @@ export function useMenuHover<T extends HTMLElement = HTMLElement>(
const hoverOpenedAtRef = useRef(0);
const prevIsOpenRef = useRef(isOpen);
- // Catches every close, whatever caused it. A layout effect, not render: it
- // must land before the browser hit-tests the vanished panel and fires the
- // mouseenter REOPEN_SUPPRESS_MS exists to swallow.
- useIsomorphicLayoutEffect(() => {
- const wasOpen = prevIsOpenRef.current;
- prevIsOpenRef.current = isOpen;
- if (wasOpen && !isOpen) {
- hoverModeRef.current = false;
- hoverOpenedAtRef.current = 0;
- closedAtRef.current = Date.now();
- }
- }, [isOpen]);
-
const clearTimeouts = useCallback(() => {
if (showTimerRef.current) {
clearTimeout(showTimerRef.current);
@@ -256,6 +243,24 @@ export function useMenuHover<T extends HTMLElement = HTMLElement>(
safeTriangleCleanupRef.current = null;
}, []);
+ // Catches every close, whatever caused it. A layout effect, not render: it
+ // must land before the browser hit-tests the vanished panel and fires the
+ // mouseenter REOPEN_SUPPRESS_MS exists to swallow.
+ useIsomorphicLayoutEffect(() => {
+ const wasOpen = prevIsOpenRef.current;
+ prevIsOpenRef.current = isOpen;
+ if (wasOpen && !isOpen) {
+ // A hover-open scheduled before the close must not fire afterwards and
+ // reopen what just closed from elsewhere — e.g. the root menu's light
+ // dismiss closing a submenu flyout mid hover-intent (#6893). A fresh
+ // mouseenter still opens; only the stale timer is cancelled.
+ clearTimeouts();
+ hoverModeRef.current = false;
+ hoverOpenedAtRef.current = 0;
+ closedAtRef.current = Date.now();
+ }
+ }, [isOpen, clearTimeouts]);
+
// useListFocus needs an onEscape that is defined in terms of its own listRef;
// the indirection avoids the use-before-declare.
const escapeHandlerRef = useRef<() => void>(() => {});