Skip to content

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

TypeScript

feat(DropdownMenuSubMenu): keep the flyout open inside the safe triangle; a press on the row never closes it (#6824)

Christopher Chedeau2618c4dd98e0
diff --git a/.changeset/submenu-safe-triangle.md b/.changeset/submenu-safe-triangle.md
new file mode 100644
index 0000000000..f00a479012
--- /dev/null
+++ b/.changeset/submenu-safe-triangle.md
@@ -0,0 +1,16 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Sub-menu flyouts stay open while the pointer travels toward them, and a press on a sub-menu row opens it without ever closing the menu.
+
+In `DropdownMenuSubMenu` the flyout now stays open while the mouse moves
+from the row toward the flyout inside the triangle to its near edge, and
+closes after the existing delay once the pointer has left both the row and
+that triangle, so a diagonal path to the flyout no longer folds it. A click
+or release on a sub-menu row opens its flyout; on an open one it confirms the
+flyout and moves focus into it instead of toggling it shut, as macOS sub-menu
+rows do. `useMenuHover` gains `flyoutRef` and passes the leave event to
+`onMouseLeave`.
+
+@vjeux
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
index fa0c7fd715..1484bdce85 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md
+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
@@ -111,6 +111,7 @@ released default.
| Sub-menu presentation | `presentation` on a sub-menu row: `flyout`, `drill-in`, `adaptive` | Whether a sub-menu opens beside its row or replaces the menu's rows with its own and a Back row, in the same box. `adaptive` drills in when a coarse pointer opened the menu. | Pointer presentation, compound and data mode | `adaptive` | `component:DropdownMenu` | stable | An unknown value reads as `adaptive`. |
| FR11 | When a compact touch display opened the pointer menu (`COMPACT_TOUCH_PRESENTATION_QUERY`, the same query the root presentation uses for its bottom sheet, sampled once as it opens) an `adaptive` sub-menu row MUST drill in: its rows and a leading Back row named "Back to <parent>" replace the menu's rows in the same Pointer menu surface, no flyout opens, the drilled list is a `menu` named by the row's label, and Back, Escape and ArrowLeft MUST return to the row with focus on it; a pick inside closes the whole menu. Roving focus and typeahead scope to the shown rows; sibling rows and dividers need no knowledge of it. `presentation="flyout"` keeps the flyout; `"drill-in"` drills in on any pointer. | `component:DropdownMenu/DEC-2`; `architecture:interaction-modality` | Proposed; verified in jsdom and Chromium (coarse pointer); owner to confirm DEC-5 |
| FR12 | In the pointer menu ArrowDown on the last enabled row wraps to the first and ArrowUp on the first to the last; PageDown and PageUp move to the last and first fully visible enabled row and, pressed there again, one viewport further without wrapping; ArrowUp on the trigger opens with the last enabled row highlighted; the key that opened the menu and its auto-repeats do not activate; typeahead matches the row's label element alone and ignores Control/Command chords and input-method composition. | Proposed in this change; `DropdownMenu.test.tsx` keyboard suite, `useListFocus.test.tsx`, `useTypeahead.test.tsx` | Proposed; verified in jsdom, pending owner review |
+| FR13 | On a mouse, a nested flyout stays open while the pointer is inside the triangle from where it left its row to the flyout's near edge — including while the pointer is paused there — and closes after the existing delay once the pointer has left both the row and that triangle. The row's click toggle and its guard window are unchanged. | Proposed in this change; `DropdownMenuSubMenu.test.tsx` safe-triangle suite, `useMenuHover.test.tsx` | Proposed; verified in jsdom, pending owner review |
### Allowed variation
@@ -258,20 +259,21 @@ than adding a DropdownMenu-owned heading target.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
-| FR1, FR4 | `DropdownMenu.test.tsx` pointer, bottom-sheet, adaptive, section, divider, and drill-in suites | Root pointer, nested pointer, root touch, drill-in | Collapsing presentation-specific parts or owners fails structure, target, or role assertions. | `audit:DropdownMenu/anatomy` |
-| FR2 | DropdownMenu target suites, source inspection, and theming target inventories | All six local targets | Removing, renaming, or assigning a current target to the wrong part fails evidence or inventory. | `audit:DropdownMenu/theming` |
-| FR3 | `DropdownMenuSelectable.test.tsx` plus BottomSheet, List, Indicator, Icon, and Divider owner tests | Trigger, touch actions, icons, checkbox, radio | A composed part loses its owner target or is documented as a new local target. | `audit:DropdownMenu/theming` |
-| Layer relationships | `DropdownMenu.test.tsx`, `DropdownMenuSubMenu.test.tsx`, and current layer/dismissal architecture records | Light dismiss, nested flyout, sheet dismissal | Documentation claims a shared owner where current source retains local behavior, or the reverse. | `audit:DropdownMenu/behavior` |
-| FR5 | `DropdownMenu.test.tsx` press model suite; the module record's own map | Finger slide across rows, outside release by mouse and finger, `touch-action`, root marker | A row acting on the press or the stray click, a lost `touch-action`, or a finger release that closes fails. | `audit:DropdownMenu/behavior` |
-| FR6 | `DropdownMenu.test.tsx` dismissal and closing suites | keyboard dismissal, pointer dismissal, press outside on a control, pointer pick, closed menu | Focus left on the body after a pointer pick, or a ring after pointer input, fails. | `audit:DropdownMenu/behavior` |
-| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:DropdownMenu/theming` |
-| FR8 | `DropdownMenu.test.tsx` press model suite (trigger cases) | Press-open + drag-release, unsettled opening release, trigger toggle, held touch, tap | A menu that does not open on a mouse press, an unsettled release that acts, or a trigger that reopens in the same gesture fails. | `audit:DropdownMenu/behavior` |
-| FR9 | `DropdownMenu.test.tsx` custom trigger suite | Icon button, chip, list row; open, toggle, keyboard open, name | A rendered control missing `aria-haspopup`, `aria-expanded` or `aria-controls`, an unnamed menu, or a lost keyboard open, fails. | `audit:DropdownMenu/anatomy` |
-| FR8, AR2 | `DropdownMenu.test.tsx` "DropdownMenuItem href" suite (pointer menu and bottom sheet) | Plain click, ⌘-click, Enter with modifiers, disabled link row | A row rendering an inner anchor, running `onClick` on a modified click, or a synthesized click dropping the modifiers fails. | `audit:DropdownMenu/behavior` |
-| FR12, AR3 | `DropdownMenuSubMenu.test.tsx` "drill-in on a phone" suite; `__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts` (real Chromium, coarse pointer) | Drill in, Back, Escape, ArrowLeft, nested level, scoped typeahead, forced presentations, close resets | A flyout opening on a coarse pointer, a missing Back row, sibling rows staying in the order, or focus not returning to the row fails. | `audit:DropdownMenu/behavior` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
+| FR1, FR4 | `DropdownMenu.test.tsx` pointer, bottom-sheet, adaptive, section, divider, and drill-in suites | Root pointer, nested pointer, root touch, drill-in | Collapsing presentation-specific parts or owners fails structure, target, or role assertions. | `audit:DropdownMenu/anatomy` |
+| FR2 | DropdownMenu target suites, source inspection, and theming target inventories | All six local targets | Removing, renaming, or assigning a current target to the wrong part fails evidence or inventory. | `audit:DropdownMenu/theming` |
+| FR3 | `DropdownMenuSelectable.test.tsx` plus BottomSheet, List, Indicator, Icon, and Divider owner tests | Trigger, touch actions, icons, checkbox, radio | A composed part loses its owner target or is documented as a new local target. | `audit:DropdownMenu/theming` |
+| Layer relationships | `DropdownMenu.test.tsx`, `DropdownMenuSubMenu.test.tsx`, and current layer/dismissal architecture records | Light dismiss, nested flyout, sheet dismissal | Documentation claims a shared owner where current source retains local behavior, or the reverse. | `audit:DropdownMenu/behavior` |
+| FR5 | `DropdownMenu.test.tsx` press model suite; the module record's own map | Finger slide across rows, outside release by mouse and finger, `touch-action`, root marker | A row acting on the press or the stray click, a lost `touch-action`, or a finger release that closes fails. | `audit:DropdownMenu/behavior` |
+| FR6 | `DropdownMenu.test.tsx` dismissal and closing suites | keyboard dismissal, pointer dismissal, press outside on a control, pointer pick, closed menu | Focus left on the body after a pointer pick, or a ring after pointer input, fails. | `audit:DropdownMenu/behavior` |
+| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:DropdownMenu/theming` |
+| FR8 | `DropdownMenu.test.tsx` press model suite (trigger cases) | Press-open + drag-release, unsettled opening release, trigger toggle, held touch, tap | A menu that does not open on a mouse press, an unsettled release that acts, or a trigger that reopens in the same gesture fails. | `audit:DropdownMenu/behavior` |
+| FR9 | `DropdownMenu.test.tsx` custom trigger suite | Icon button, chip, list row; open, toggle, keyboard open, name | A rendered control missing `aria-haspopup`, `aria-expanded` or `aria-controls`, an unnamed menu, or a lost keyboard open, fails. | `audit:DropdownMenu/anatomy` |
+| FR8, AR2 | `DropdownMenu.test.tsx` "DropdownMenuItem href" suite (pointer menu and bottom sheet) | Plain click, ⌘-click, Enter with modifiers, disabled link row | A row rendering an inner anchor, running `onClick` on a modified click, or a synthesized click dropping the modifiers fails. | `audit:DropdownMenu/behavior` |
+| FR12, AR3 | `DropdownMenuSubMenu.test.tsx` "drill-in on a phone" suite; `__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts` (real Chromium, coarse pointer) | Drill in, Back, Escape, ArrowLeft, nested level, scoped typeahead, forced presentations, close resets | A flyout opening on a coarse pointer, a missing Back row, sibling rows staying in the order, or focus not returning to the row fails. | `audit:DropdownMenu/behavior` |
+| FR10 | `DropdownMenuSubMenu.test.tsx` safe-triangle suite; `useMenuHover.test.tsx` `isPointInSafeTriangle` and click-guard suites | diagonal path toward the flyout, a pause inside it, path away, click-opened and hover-opened guard windows | A flyout that closes while the pointer is inside the triangle or paused in it, one that never closes after leaving it, or a changed guard-window rule, fails. | `audit:DropdownMenu/behavior` |
## Decision log
@@ -292,6 +294,8 @@ in `module:DropdownMenu/useMenuPress`.
### DEC-2 — `menuMaxHeight` is a number of pixels
+### DEC-3 — A safe triangle protects the diagonal to a flyout
+
**Reference:** `component:DropdownMenu/DEC-2`
**Decider:** `cixzhang`, `2026-10-02`
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
index b936042001..c33c179f9d 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
@@ -955,6 +955,110 @@ describe('DropdownMenuSubMenu press model', () => {
});
});
+describe('DropdownMenuSubMenu safe triangle', () => {
+ const flyoutRect = {
+ top: 0,
+ bottom: 200,
+ left: 300,
+ right: 500,
+ width: 200,
+ height: 200,
+ x: 300,
+ y: 0,
+ toJSON: () => ({}),
+ } as DOMRect;
+
+ async function openByHover() {
+ vi.useFakeTimers({shouldAdvanceTime: true});
+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});
+ render(<MoveMenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await user.hover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const flyout = screen.getByRole('menu', {name: /Move to/, hidden: true});
+ vi.spyOn(flyout, 'getBoundingClientRect').mockReturnValue(flyoutRect);
+ return {trigger, flyout};
+ }
+
+ it('a diagonal path toward the flyout keeps it open past the close delay', async () => {
+ const {trigger} = await openByHover();
+ // The pointer leaves the row at (250, 100), heading for the flyout's near
+ // (left) edge; every move inside the triangle restarts the close delay.
+ fireEvent.mouseLeave(trigger, {clientX: 250, clientY: 100});
+ for (const [x, y] of [
+ [260, 90],
+ [270, 80],
+ [280, 60],
+ [290, 40],
+ ]) {
+ act(() => {
+ vi.advanceTimersByTime(150);
+ });
+ fireEvent.pointerMove(document.body, {clientX: x, clientY: y});
+ }
+ act(() => {
+ vi.advanceTimersByTime(150);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ vi.useRealTimers();
+ });
+
+ it('leaving both the row and the triangle closes after the delay', async () => {
+ const {trigger} = await openByHover();
+ fireEvent.mouseLeave(trigger, {clientX: 250, clientY: 100});
+ // Straight down, away from the flyout: outside the triangle.
+ fireEvent.pointerMove(document.body, {clientX: 250, clientY: 400});
+ act(() => {
+ vi.advanceTimersByTime(250);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ vi.useRealTimers();
+ });
+
+ it('a pointer that pauses inside the triangle keeps the flyout open', async () => {
+ const {trigger} = await openByHover();
+ // The pointer leaves the row mid-diagonal and then STOPS, aiming at a
+ // row: no further pointermove fires. Pausing is not leaving, and this is
+ // the exact moment the triangle exists to protect — the close delay used
+ // to run out underneath it.
+ fireEvent.mouseLeave(trigger, {clientX: 250, clientY: 100});
+ fireEvent.pointerMove(document.body, {clientX: 275, clientY: 95});
+
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ vi.useRealTimers();
+ });
+
+ it('a pause inside the triangle still closes once the pointer leaves it', async () => {
+ const {trigger} = await openByHover();
+ fireEvent.mouseLeave(trigger, {clientX: 250, clientY: 100});
+ fireEvent.pointerMove(document.body, {clientX: 275, clientY: 95});
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // Re-arming is not the same as never closing: the first move out of the
+ // triangle lets the delay run.
+ fireEvent.pointerMove(document.body, {clientX: 250, clientY: 400});
+ act(() => {
+ vi.advanceTimersByTime(250);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ vi.useRealTimers();
+ });
+});
+
describe('DropdownMenuSubMenu drill-in on a phone', () => {
const originalMatchMedia = window.matchMedia;
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
index 9f89e4fb0d..3aed46eb43 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
@@ -438,6 +438,9 @@ export function DropdownMenuSubMenu(
hide: hideLayer,
isOpen: isFlyoutOpen,
isEnabled: canOpen && !isDrillIn,
+ // 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,
});
// Where focus lands once a pushed view shows: the first row after Back for
diff --git a/packages/core/src/hooks/useMenuHover.test.tsx b/packages/core/src/hooks/useMenuHover.test.tsx
index 3ede3f452b..9c7185c32a 100644
--- a/packages/core/src/hooks/useMenuHover.test.tsx
+++ b/packages/core/src/hooks/useMenuHover.test.tsx
@@ -13,7 +13,7 @@ import {describe, it, expect, vi, afterEach} from 'vitest';
import {render, screen, act, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {TopNavMenu} from '../TopNav/TopNavMenu';
-import {useMenuHover} from './useMenuHover';
+import {isPointInSafeTriangle, useMenuHover} from './useMenuHover';
const items = [
{title: 'Analytics', description: 'Track user behavior', href: '/analytics'},
@@ -364,6 +364,112 @@ describe('useMenuHover — native invoker wiring', () => {
});
});
+describe('isPointInSafeTriangle', () => {
+ const flyout = {top: 0, bottom: 200, left: 300, right: 500};
+
+ it('accepts a point between the apex and the near (left) edge of a flyout to the right', () => {
+ const apex = {x: 250, y: 100};
+ expect(isPointInSafeTriangle({x: 275, y: 100}, apex, flyout)).toBe(true);
+ expect(isPointInSafeTriangle({x: 290, y: 30}, apex, flyout)).toBe(true);
+ expect(isPointInSafeTriangle({x: 290, y: 180}, apex, flyout)).toBe(true);
+ });
+
+ it('rejects a point that leaves the triangle', () => {
+ const apex = {x: 250, y: 100};
+ expect(isPointInSafeTriangle({x: 250, y: 400}, apex, flyout)).toBe(false);
+ expect(isPointInSafeTriangle({x: 200, y: 100}, apex, flyout)).toBe(false);
+ expect(isPointInSafeTriangle({x: 260, y: 300}, apex, flyout)).toBe(false);
+ });
+
+ it('uses the right edge when the flyout flipped to the left of the pointer', () => {
+ const apex = {x: 550, y: 100};
+ expect(isPointInSafeTriangle({x: 525, y: 100}, apex, flyout)).toBe(true);
+ expect(isPointInSafeTriangle({x: 600, y: 100}, apex, flyout)).toBe(false);
+ });
+
+ it('uses the top or bottom edge when the pointer left above or below the flyout', () => {
+ expect(
+ isPointInSafeTriangle({x: 400, y: -20}, {x: 400, y: -40}, flyout),
+ ).toBe(true);
+ expect(
+ isPointInSafeTriangle({x: 400, y: 220}, {x: 400, y: 240}, flyout),
+ ).toBe(true);
+ });
+
+ it('has no triangle when the pointer left from over the flyout itself', () => {
+ expect(
+ isPointInSafeTriangle({x: 400, y: 100}, {x: 400, y: 100}, flyout),
+ ).toBe(false);
+ });
+});
+
+describe('useMenuHover — the click guard and its consumers', () => {
+ it('closes immediately on a second click when the menu was opened BY click', async () => {
+ // The guard window keys off the hover-open timestamp, so a menu that was
+ // never hover-opened has no window at all: the next click is a second,
+ // deliberate press on something visibly open, and closes it.
+ const user = userEvent.setup();
+ const trigger = renderMenu();
+
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('confirms a hover-open on the click inside the guard window, and closes after it', async () => {
+ vi.useFakeTimers({shouldAdvanceTime: true});
+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});
+ const trigger = renderMenu();
+
+ await user.hover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // Inside the window the click confirms: you were reaching for the row
+ // you already meant to open, so it must not slam shut under you.
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // Past the window it is a deliberate press on something visibly open.
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ vi.useRealTimers();
+ });
+
+ it('leaves no document pointermove listener behind after a close', async () => {
+ // Every consumer of this hook now gets triangle tracking, which attaches
+ // a document-level listener on leave. One surviving a close would run
+ // for the life of the page.
+ vi.useFakeTimers({shouldAdvanceTime: true});
+ const user = userEvent.setup({advanceTimers: vi.advanceTimersByTime});
+ const add = vi.spyOn(document, 'addEventListener');
+ const remove = vi.spyOn(document, 'removeEventListener');
+ const trigger = renderMenu();
+
+ await user.hover(trigger);
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ fireEvent.mouseLeave(trigger, {clientX: 10, clientY: 10});
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+
+ const attached = add.mock.calls.filter(([type]) => type === 'pointermove');
+ const detached = remove.mock.calls.filter(
+ ([type]) => type === 'pointermove',
+ );
+ expect(detached.length).toBeGreaterThanOrEqual(attached.length);
+ vi.useRealTimers();
+ });
+});
+
// =============================================================================
// Disabling a trigger with a hover already in flight
// =============================================================================
diff --git a/packages/core/src/hooks/useMenuHover.ts b/packages/core/src/hooks/useMenuHover.ts
index 2591e63f7c..a2e229b2d5 100644
--- a/packages/core/src/hooks/useMenuHover.ts
+++ b/packages/core/src/hooks/useMenuHover.ts
@@ -54,6 +54,70 @@ const DEFAULT_CLICK_GUARD_MS = 500;
*/
const REOPEN_SUPPRESS_MS = 300;
+/**
+ * Slack added to the flyout's near edge when building the safe triangle, so a
+ * pointer skimming the edge's corners still counts as heading for the flyout.
+ */
+const SAFE_TRIANGLE_PADDING_PX = 8;
+
+interface Point {
+ x: number;
+ y: number;
+}
+
+interface EdgeRect {
+ top: number;
+ bottom: number;
+ left: number;
+ right: number;
+}
+
+function sign(p1: Point, p2: Point, p3: Point): number {
+ return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
+}
+
+function isPointInTriangle(p: Point, a: Point, b: Point, c: Point): boolean {
+ const d1 = sign(p, a, b);
+ const d2 = sign(p, b, c);
+ const d3 = sign(p, c, a);
+ const hasNegative = d1 < 0 || d2 < 0 || d3 < 0;
+ const hasPositive = d1 > 0 || d2 > 0 || d3 > 0;
+ return !(hasNegative && hasPositive);
+}
+
+/**
+ * Whether `point` lies inside the safe triangle from `origin` (where the
+ * pointer left the trigger row) to the flyout's NEAR edge — the edge of
+ * `flyout` facing the origin. A pointer travelling inside it is heading for
+ * the flyout, so the flyout must stay open. Exported for unit tests.
+ */
+export function isPointInSafeTriangle(
+ point: Point,
+ origin: Point,
+ flyout: EdgeRect,
+): boolean {
+ const pad = SAFE_TRIANGLE_PADDING_PX;
+ let edgeStart: Point;
+ let edgeEnd: Point;
+ if (origin.x <= flyout.left) {
+ edgeStart = {x: flyout.left, y: flyout.top - pad};
+ edgeEnd = {x: flyout.left, y: flyout.bottom + pad};
+ } else if (origin.x >= flyout.right) {
+ edgeStart = {x: flyout.right, y: flyout.top - pad};
+ edgeEnd = {x: flyout.right, y: flyout.bottom + pad};
+ } else if (origin.y <= flyout.top) {
+ edgeStart = {x: flyout.left - pad, y: flyout.top};
+ edgeEnd = {x: flyout.right + pad, y: flyout.top};
+ } else if (origin.y >= flyout.bottom) {
+ edgeStart = {x: flyout.left - pad, y: flyout.bottom};
+ edgeEnd = {x: flyout.right + pad, y: flyout.bottom};
+ } else {
+ // The origin is over the flyout itself: nothing to travel toward.
+ return false;
+ }
+ return isPointInTriangle(point, origin, edgeStart, edgeEnd);
+}
+
export interface UseMenuHoverOptions {
show: (options?: {skipAutoFocus?: boolean}) => void;
hide: () => void;
@@ -87,19 +151,29 @@ export interface UseMenuHoverOptions {
* collapsed flyout) has no items for the hook to focus. @default true
*/
ownsFocus?: boolean;
+ /**
+ * The flyout element, for consumers that manage their own list and do not
+ * attach the hook's `menuRef`. The safe triangle toward the flyout's near
+ * edge is built from it; without it the triangle is off.
+ */
+ flyoutRef?: React.RefObject<HTMLElement | null>;
}
export interface UseMenuHoverReturn<T extends HTMLElement = HTMLElement> {
triggerProps: {
onClick: (event?: React.MouseEvent) => void;
onMouseEnter: () => void;
- onMouseLeave: () => void;
+ /**
+ * Pass the event through: the pointer's position when it leaves the
+ * trigger is the apex of the safe triangle toward the flyout.
+ */
+ onMouseLeave: (event?: React.MouseEvent) => void;
/** Present only when `popoverId` is supplied. */
popoverTarget?: string;
};
contentProps: {
onMouseEnter: () => void;
- onMouseLeave: () => void;
+ onMouseLeave: (event?: React.MouseEvent) => void;
onKeyDown: (e: React.KeyboardEvent) => void;
};
menuRef: React.RefObject<T | null>;
@@ -139,6 +213,7 @@ export function useMenuHover<T extends HTMLElement = HTMLElement>(
itemSelector,
popoverId,
ownsFocus = true,
+ flyoutRef,
} = options;
const hasHover = useMediaQuery('(hover: hover)');
@@ -146,6 +221,8 @@ export function useMenuHover<T extends HTMLElement = HTMLElement>(
const showTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const triggerElRef = useRef<HTMLElement | null>(null);
+ /** Removes the document pointer listener that watches the safe triangle. */
+ const safeTriangleCleanupRef = useRef<(() => void) | null>(null);
/** Menu was hover-opened, so mouseleave may close it. */
const hoverModeRef = useRef(false);
const closedAtRef = useRef(0);
@@ -175,6 +252,8 @@ export function useMenuHover<T extends HTMLElement = HTMLElement>(
clearTimeout(hideTimerRef.current);
hideTimerRef.current = null;
}
+ safeTriangleCleanupRef.current?.();
+ safeTriangleCleanupRef.current = null;
}, []);
// useListFocus needs an onEscape that is defined in terms of its own listRef;
@@ -337,18 +416,76 @@ export function useMenuHover<T extends HTMLElement = HTMLElement>(
}
}, [hasHover, isOpen, clearTimeouts, show, showDelay]);
- const handleMouseLeave = useCallback(() => {
- // A real leave ends the stationary-pointer case the suppression window
- // exists for, so the next enter is deliberate whenever it arrives.
- closedAtRef.current = 0;
- if (!hoverModeRef.current) {
- return;
- }
- clearTimeouts();
- hideTimerRef.current = setTimeout(() => {
- hide();
- }, hideDelay);
- }, [clearTimeouts, hide, hideDelay]);
+ const handleMouseLeave = useCallback(
+ (event?: React.MouseEvent) => {
+ // A real leave ends the stationary-pointer case the suppression window
+ // exists for, so the next enter is deliberate whenever it arrives.
+ closedAtRef.current = 0;
+ if (!hoverModeRef.current) {
+ return;
+ }
+ clearTimeouts();
+ // Where the pointer was last seen, so the delay can ask whether it is
+ // still heading for the flyout rather than only reacting to movement.
+ let lastPoint: Point | null = null;
+ let isTracking = false;
+ let isInside: (point: Point) => boolean = () => false;
+ const scheduleHide = () => {
+ if (hideTimerRef.current) {
+ clearTimeout(hideTimerRef.current);
+ }
+ hideTimerRef.current = setTimeout(() => {
+ // A pointer that stopped mid-diagonal, aiming at a row, is still
+ // heading for the flyout: pausing is not leaving, and that pause
+ // is the exact moment the triangle exists to protect. Re-arm
+ // instead of closing underneath it. A pointer parked here holds
+ // the flyout open the same way a pointer parked on the row does;
+ // the first move outside the triangle ends it.
+ if (isTracking && lastPoint != null && isInside(lastPoint)) {
+ scheduleHide();
+ return;
+ }
+ hide();
+ }, hideDelay);
+ };
+ scheduleHide();
+
+ // The safe triangle: while the pointer travels from where it left
+ // the trigger toward the flyout's near edge, it is heading for the
+ // flyout, and every move inside the triangle restarts the hide delay.
+ // The first move outside it lets the delay run out.
+ const menu = flyoutRef?.current ?? menuRef.current;
+ const apex: Point | null =
+ event != null ? {x: event.clientX, y: event.clientY} : null;
+ if (menu == null || apex == null || !isOpen) {
+ return;
+ }
+ const rect = menu.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0) {
+ return;
+ }
+ const doc = menu.ownerDocument;
+ isInside = point => isPointInSafeTriangle(point, apex, rect);
+ isTracking = true;
+ lastPoint = apex;
+ const onPointerMove = (move: PointerEvent) => {
+ const point = {x: move.clientX, y: move.clientY};
+ lastPoint = point;
+ if (isInside(point)) {
+ scheduleHide();
+ return;
+ }
+ isTracking = false;
+ safeTriangleCleanupRef.current?.();
+ safeTriangleCleanupRef.current = null;
+ };
+ doc.addEventListener('pointermove', onPointerMove, true);
+ safeTriangleCleanupRef.current = () => {
+ doc.removeEventListener('pointermove', onPointerMove, true);
+ };
+ },
+ [clearTimeouts, hide, hideDelay, isOpen, menuRef, flyoutRef],
+ );
const handleContentMouseEnter = useCallback(() => {
clearTimeouts();