An open source design system that's fully customizable and agent ready
TypeScript
fix(DropdownMenu): return focus to the trigger after a pointer dismissal, without a ring (#6825)
Christopher Chedeau2b5efc961aa8
diff --git a/.changeset/menu-close-focus.md b/.changeset/menu-close-focus.mdnew file mode 100644index 0000000000..a0ad9dfde4--- /dev/null+++ b/.changeset/menu-close-focus.md@@ -0,0 +1,14 @@+---+'@astryxdesign/core': patch+---++[fix] A DropdownMenu returns focus to its trigger after a pointer dismissal, without painting a focus ring.++`DropdownMenu` used to blur its trigger after a pointer pick or an outside+press, dropping focus to the page so the next arrow key went nowhere. Focus+now returns to the trigger with the focus ring suppressed after pointer+input, as the bottom-sheet presentation already did, and stays visible after+a keyboard pick. A press outside that landed on a focusable control keeps+focus there.++@vjeuxdiff --git a/packages/core/src/DropdownMenu/DropdownMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.mdindex aa84e23adc..488addd58c 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md@@ -86,13 +86,14 @@ subcomponents, and presentation policy remain documented in## Behavioral and layout contract-| ID | Candidate invariant | Basis | Draft review state |-| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | -------------------------------------------------- |-| FR1 | Every current render contains a Trigger button. Pointer presentation renders a Pointer menu surface with pointer-owned rows and optional pointer headings, dividers, indicators, and nested flyouts. Touch presentation renders a Touch sheet frame containing a Touch menu surface, Touch heading, Touch action list, and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |-| FR2 | The six current local targets are `dropdown-menu`, `dropdown-menu-item`, `dropdown-menu-radio`, `dropdown-menu-section-heading`, `dropdown-menu-divider`, and `dropdown-menu-indicator-icon`; every target remains on its current painted element. | Current source, docs, and tests | Verified current inventory; no target change |-| FR3 | Button owns the Trigger button, BottomSheet owns the Touch sheet frame, List owns the Touch action list and Touch action rows, Indicator owns checkbox chrome, and Icon owns ordinary rendered icons. | Current source and owner docs | Verified current delegation; no ownership change |-| FR4 | The same `dropdown-menu` target reaches the alternative Pointer menu surface and Touch menu surface. Pointer action rows retain `dropdown-menu-item`; touch action rows instead use List's `list-item` target. | Current source and tests | Verified modality split; no target change |-| FR5 | Both menu surfaces carry `data-astryx-menu-press` and follow `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the browser's stray click never acts, and the Pointer menu surface declares `touch-action` by overflow. Trigger opening and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom and real Chromium |+| ID | Candidate invariant | Basis | Draft review state |+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |+| FR1 | Every current render contains a Trigger button. Pointer presentation renders a Pointer menu surface with pointer-owned rows and optional pointer headings, dividers, indicators, and nested flyouts. Touch presentation renders a Touch sheet frame containing a Touch menu surface, Touch heading, Touch action list, and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |+| FR2 | The six current local targets are `dropdown-menu`, `dropdown-menu-item`, `dropdown-menu-radio`, `dropdown-menu-section-heading`, `dropdown-menu-divider`, and `dropdown-menu-indicator-icon`; every target remains on its current painted element. | Current source, docs, and tests | Verified current inventory; no target change |+| FR3 | Button owns the Trigger button, BottomSheet owns the Touch sheet frame, List owns the Touch action list and Touch action rows, Indicator owns checkbox chrome, and Icon owns ordinary rendered icons. | Current source and owner docs | Verified current delegation; no ownership change |+| FR4 | The same `dropdown-menu` target reaches the alternative Pointer menu surface and Touch menu surface. Pointer action rows retain `dropdown-menu-item`; touch action rows instead use List's `list-item` target. | Current source and tests | Verified modality split; no target change |+| FR5 | Both menu surfaces carry `data-astryx-menu-press` and follow `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the browser's stray click never acts, and the Pointer menu surface declares `touch-action` by overflow. Trigger opening and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom and real Chromium |+| FR6 | When the pointer menu closes, focus returns to the Trigger button with a visible ring only when the menu was driven by keyboard; a press outside that landed on a focusable control keeps focus there. | `architecture:interaction-modality` INV1; proposed in this change; `DropdownMenu.test.tsx` closing suite | Proposed; verified in jsdom, pending owner review |### Allowed variation@@ -127,9 +128,11 @@ subcomponents, and presentation policy remain documented in## Accessibility contractThis draft does not change DropdownMenu's trigger naming, menu and dialog-roles, keyboard navigation, item semantics, focus return, or dismissal-ordering. While a pointer is held, the highlight is DOM focus per-`module:DropdownMenu/useMenuPress` AR1.+roles, keyboard navigation, item semantics, or dismissal ordering. While a+pointer is held, the highlight is DOM focus per+`module:DropdownMenu/useMenuPress` AR1. Focus return on close follows FR6 and+`architecture:interaction-modality` INV1 through the shared focus-return+visibility helper.## Design relationships@@ -228,20 +231,30 @@ 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` |-| 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` |+| 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` |+| 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` |## Decision log-None component-local. The press model decision lives in-`module:DropdownMenu/useMenuPress` DEC-3; this record introduces no design,-theming, or layer-system decision of its own.+### DEC-1 — Pointer dismissal returns focus to the trigger, ring suppressed++**Reference:** `component:DropdownMenu/DEC-1`+**Decider:** pending owner review++The shipped behavior blurred the trigger after a pointer dismissal so Safari+would not paint a ring after a touch pick. Focus falling to the page loses a+keyboard user who reaches for the arrows next. Focus now returns to the+trigger and the shared focus-return visibility helper suppresses the ring+after pointer input (`architecture:interaction-modality` INV1), as the+bottom-sheet presentation already did. The press model's own decisions remain+in `module:DropdownMenu/useMenuPress`.## Open questionsdiff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex 1ba7a63bc4..85181b517d 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -734,7 +734,7 @@ describe('DropdownMenu', () => {}});- it('does not leave focus on the trigger after pointer dismissal', async () => {+ it('returns focus to the trigger after pointer dismissal without a focus ring', async () => {const raf = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {@@ -759,14 +759,56 @@ describe('DropdownMenu', () => {.getByRole('menu', {hidden: true}).closest('[popover]');expect(popoverEl).not.toBeNull();- // Simulate native popover focus restoration occurring before React's- // toggle handler; pointer dismissal should remove that focus again.- trigger.focus();+ // A press on nothing focusable dismissed the menu: focus goes back to+ // the trigger, and the pointer modality suppresses the ring Safari+ // would otherwise paint after a touch pick.+ trigger.blur();const toggleEvent = new Event('toggle');Object.defineProperty(toggleEvent, 'newState', {value: 'closed'});fireEvent(popoverEl as HTMLElement, toggleEvent);- expect(trigger).not.toHaveFocus();+ expect(trigger).toHaveFocus();+ await waitFor(() =>+ expect(trigger).toHaveClass(+ stylex.props(focusOutlineStyles.suppressed).className!,+ ),+ );+ } finally {+ raf.mockRestore();+ }+ });++ it('leaves focus on the control a press outside landed on', () => {+ const raf = vi+ .spyOn(window, 'requestAnimationFrame')+ .mockImplementation(callback => {+ callback(0);+ return 0;+ });++ try {+ render(+ <>+ <DropdownMenu button={{label: 'Actions'}} items={[{label: 'Edit'}]} />+ <button type="button">Elsewhere</button>+ </>,+ );++ const trigger = screen.getByRole('button', {name: /Actions/});+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});+ fireEvent.click(trigger, {detail: 1});+ const popoverEl = screen+ .getByRole('menu', {hidden: true})+ .closest('[popover]');++ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});+ fireEvent.pointerDown(elsewhere, {pointerType: 'mouse', button: 0});+ elsewhere.focus();+ const toggleEvent = new Event('toggle');+ Object.defineProperty(toggleEvent, 'newState', {value: 'closed'});+ fireEvent(popoverEl as HTMLElement, toggleEvent);++ expect(elsewhere).toHaveFocus();} finally {raf.mockRestore();}@@ -2265,6 +2307,7 @@ describe('DropdownMenu press model', () => {const item = (name: string) =>screen.getByRole('menuitem', {name, hidden: true});+it('a finger that lands on one row and lifts on another acts on the second, once', async () => {const onPick = vi.fn();const user = userEvent.setup();@@ -2312,3 +2355,31 @@ describe('DropdownMenu press model', () => {expect(menu).not.toHaveClass(hash(touchStyles.panY));});});++describe('DropdownMenu focus return after a pointer pick', () => {+ function renderMenu(onPick: (label: string) => void = () => {}) {+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuItem label="Edit" onClick={() => onPick('Edit')} />+ <DropdownMenuItem label="Delete" onClick={() => onPick('Delete')} />+ </DropdownMenu>,+ );+ return screen.getByRole('button', {name: /Actions/});+ }++ const item = (name: string) =>+ screen.getByRole('menuitem', {name, hidden: true});++ it('returns focus to the trigger after a pointer pick without a ring', async () => {+ const user = userEvent.setup();+ const trigger = renderMenu();+ await user.click(trigger);+ await user.click(item('Edit'));+ expect(trigger).toHaveFocus();+ await waitFor(() =>+ expect(trigger).toHaveClass(+ stylex.props(focusOutlineStyles.suppressed).className!,+ ),+ );+ });+});diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex 443a757912..d418082e10 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -80,10 +80,7 @@ import {import {mergeProps, rtlStyles} from '../utils';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';-import {- getInteractionModality,- useInteractionModalityTracking,-} from '../utils/interactionModality';+import {useInteractionModalityTracking} from '../utils/interactionModality';import {useTranslator} from '../i18n';import {focusOutlineStyles} from '../utils/focusOutline.stylex';@@ -626,14 +623,23 @@ function DropdownMenuPopover({const suppressControlledRollbackHideRef = useRef(false);useInteractionModalityTracking();+ const {+ isFocusRingSuppressed,+ onFocusReturnTargetFocus,+ prepareFocusReturn,+ resetFocusReturn,+ } = useFocusReturnVisibility();+ const contentRef = useRef<HTMLDivElement | null>(null);// The press model is mounted below (it needs the popover); the hide path// above it ends the gesture in flight through this ref.const cancelMenuPressRef = useRef<() => void>(() => {});- // Keyboard dismissal returns focus to the trigger. Pointer dismissal leaves- // focus where the browser put it; Safari can otherwise paint a focus-visible- // ring on the trigger after a touch selection. Native popover restoration- // can happen before `toggle`, so explicitly blur that pointer-restored case.+ // 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+ // the trigger, with a visible ring only when the menu was driven by+ // keyboard (the modality tracker decides; the suppressed style hides the+ // pointer case, which Safari would otherwise paint after a touch pick).const handleLayerHide = useCallback(() => {if (suppressControlledRollbackHideRef.current) {suppressControlledRollbackHideRef.current = false;@@ -646,12 +652,21 @@ function DropdownMenuPopover({setInternalIsOpen(false);}const trigger = buttonRef.current;- if (getInteractionModality() === 'keyboard') {- trigger?.focus();- } else if (document.activeElement === trigger) {- trigger?.blur();+ if (!trigger) {+ return;+ }+ const active = document.activeElement;+ const focusLandedElsewhere =+ active instanceof HTMLElement &&+ active !== document.body &&+ active !== trigger &&+ !contentRef.current?.contains(active);+ if (focusLandedElsewhere) {+ return;}- }, [isControlled, onOpenChange]);+ prepareFocusReturn();+ trigger.focus({preventScroll: true});+ }, [isControlled, onOpenChange, prepareFocusReturn]);// Defer item focus until the layer has committed open, so focus restore// captures the trigger instead of the first menu item.@@ -666,6 +681,7 @@ function DropdownMenuPopover({const handleLayerShow = useCallback(() => {acceptedOpenRef.current = true;+ resetFocusReturn();if (notifyClickOnShowRef.current) {notifyClickOnShowRef.current = false;onClick?.();@@ -674,7 +690,7 @@ function DropdownMenuPopover({if (!isControlled) {setInternalIsOpen(true);}- }, [isControlled, onClick, onOpenChange]);+ }, [isControlled, onClick, onOpenChange, resetFocusReturn]);const popover = usePopover({onHide: handleLayerHide,@@ -952,11 +968,19 @@ function DropdownMenuPopover({/* eslint-enable react-compiler/react-compiler */}}}- xstyle={[isOpen && styles.triggerOpen, button.xstyle]}+ xstyle={[+ isOpen && styles.triggerOpen,+ button.xstyle,+ isFocusRingSuppressed && focusOutlineStyles.suppressed,+ ]}tooltip={isOpen ? undefined : button.tooltip}endContent={resolvedEndContent}onClick={handleButtonClick}onKeyDown={handleButtonKeyDown}+ onFocus={event => {+ button.onFocus?.(event);+ onFocusReturnTargetFocus();+ }}aria-haspopup="menu"aria-expanded={isOpen}aria-controls={menuId}@@ -966,7 +990,11 @@ function DropdownMenuPopover({{popover.render(<div{...rest}- ref={listRef}+ ref={el => {+ listRef.current = el;+ contentRef.current =+ el?.closest<HTMLDivElement>('[popover]') ?? null;+ }}id={menuId}role="menu"// Pointer opens focus the container so arrows, typeahead, Escape and