Skip to content

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

TypeScript

fix(DropdownMenu): a trigger the caller renders gets no focus ring after a pointer pick (#7382)

Christopher Chedeaud6b973114256
diff --git a/.changeset/dropdown-menu-trigger-focus-return.md b/.changeset/dropdown-menu-trigger-focus-return.md
new file mode 100644
index 0000000000..99ef348a48
--- /dev/null
+++ b/.changeset/dropdown-menu-trigger-focus-return.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A `DropdownMenu` whose trigger the caller renders (`renderTrigger`) returns focus to it without a focus ring after a pointer pick (a mouse click in Chromium, a click or a tap in WebKit), as the built-in trigger already did: the menu now asks the browser not to treat that focus as keyboard focus, the way Dialog's focus moves do.
+
+@vjeux
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 0dc8a73920..d5440acd53 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -9,7 +9,7 @@
* SYNC: When DropdownMenu.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {readFileSync} from 'node:fs';
import {render, screen, fireEvent, waitFor, act} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -3040,6 +3040,102 @@ describe('DropdownMenu focus return after a pointer pick', () => {
),
);
});
+
+ it("asks the browser for no ring on the design system's Button too", async () => {
+ const user = userEvent.setup();
+ const trigger = renderMenu();
+ await user.click(trigger);
+ const focus = vi.spyOn(trigger, 'focus');
+ await user.click(item('Edit'));
+ expect(trigger).toHaveFocus();
+ expect(focus.mock.calls.at(-1)).toEqual([
+ {preventScroll: true, focusVisible: false},
+ ]);
+ });
+
+ describe('a trigger the caller renders', () => {
+ // The style that keeps the ring off the design system's Button cannot
+ // reach a caller's control, so the focus move itself has to: after
+ // pointer input the browser is asked not to match `:focus-visible`, which
+ // it otherwise does on the returned focus (Chromium after a mouse pick,
+ // WebKit after a touch).
+ function renderCustomMenu() {
+ render(
+ <DropdownMenu
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ More
+ </button>
+ )}>
+ <DropdownMenuItem label="Edit" onClick={() => {}} />
+ <DropdownMenuItem label="Delete" onClick={() => {}} />
+ </DropdownMenu>,
+ );
+ return screen.getByRole('button', {name: 'More'});
+ }
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('returns focus after a pointer pick with the browser asked for no ring', async () => {
+ const user = userEvent.setup();
+ const trigger = renderCustomMenu();
+ await user.click(trigger);
+ const focus = vi.spyOn(trigger, 'focus');
+ await user.click(item('Edit'));
+ expect(trigger).toHaveFocus();
+ expect(focus.mock.calls.at(-1)).toEqual([
+ {preventScroll: true, focusVisible: false},
+ ]);
+ });
+
+ it('returns focus after a keyboard pick with the ring left to the browser', async () => {
+ const user = userEvent.setup();
+ const trigger = renderCustomMenu();
+ trigger.focus();
+ await user.keyboard('{ArrowDown}');
+ await waitFor(() => expect(item('Edit')).toHaveFocus());
+ const focus = vi.spyOn(trigger, 'focus');
+ await user.keyboard('{Enter}');
+ await waitFor(() => expect(trigger).toHaveFocus());
+ expect(focus.mock.calls.at(-1)).toEqual([{preventScroll: true}]);
+ });
+
+ it('clears a ring the browser already drew before refocusing after a pointer pick', async () => {
+ const user = userEvent.setup();
+ const trigger = renderCustomMenu();
+ await user.click(trigger);
+ // WebKit's own popover focus restoration can focus the trigger, with a
+ // ring, before the menu moves focus, and focusing the focused element
+ // changes nothing.
+ const hidePopover = HTMLElement.prototype.hidePopover;
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ hidePopover.call(this);
+ trigger.focus();
+ });
+ const matches = HTMLElement.prototype.matches;
+ vi.spyOn(HTMLElement.prototype, 'matches').mockImplementation(function (
+ this: HTMLElement,
+ selector: string,
+ ) {
+ return selector === ':focus-visible'
+ ? this === trigger
+ : matches.call(this, selector);
+ });
+ const blur = vi.spyOn(trigger, 'blur');
+ const focus = vi.spyOn(trigger, 'focus');
+ await user.click(item('Edit'));
+ expect(blur).toHaveBeenCalledTimes(1);
+ expect(focus.mock.calls.at(-1)).toEqual([
+ {preventScroll: true, focusVisible: false},
+ ]);
+ expect(blur.mock.invocationCallOrder[0]).toBeLessThan(
+ focus.mock.invocationCallOrder.at(-1) ?? 0,
+ );
+ expect(trigger).toHaveFocus();
+ });
+ });
});
describe('DropdownMenuItem href', () => {
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 3720c10503..92f0d58250 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -68,6 +68,7 @@ import {useMenuPress} from '../hooks/useMenuPress';
import type {MenuPressPointerType} from '../hooks/menuPressGesture';
import {useTypeahead} from '../hooks/useTypeahead';
import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';
+import {focusForLastInput} from '../utils/focusReturn';
import {useMenuOverflow} from './useMenuOverflow';
import {MenuRegionsContext} from './menuRegionsContext';
import {getFocusableElements} from '../hooks/useFocusTrap';
@@ -932,7 +933,12 @@ function DropdownMenuPopover({
return;
}
prepareFocusReturn();
- trigger.focus({preventScroll: true});
+ // After pointer input the trigger takes focus without the focus-visible
+ // ring (`component:DropdownMenu/DEC-1`). The style the helper above adds
+ // reaches only the design system's own Button; the browser's focus option
+ // 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]);
// Defer item focus until the layer has committed open, so focus restore
@@ -1432,8 +1438,9 @@ function DropdownMenuPopover({
onPointerDown: menuPress.triggerProps.onPointerDown,
onContextMenu: menuPress.triggerProps.onContextMenu,
onKeyDown: handleButtonKeyDown,
- // The popover's focus-return hook is a separate change; until it lands
- // the control's focus needs no bookkeeping here.
+ // The caller's control paints its own ring, and the menu's focus return
+ // keeps the browser from drawing one after pointer input (see
+ // handleLayerHide), so its focus needs no bookkeeping here.
onFocus: () => {},
'aria-haspopup': 'menu',
'aria-expanded': isOpen,
diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuFocusReturn.a11y.browser.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuFocusReturn.a11y.browser.spec.ts
new file mode 100644
index 0000000000..34bcc956a0
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuFocusReturn.a11y.browser.spec.ts
@@ -0,0 +1,73 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DropdownMenuFocusReturn.a11y.browser.spec.ts
+ * @input The `Core/DropdownMenu` CustomTrigger story (an icon button the
+ * caller renders) in a built Storybook, real Chromium/WebKit pointer and
+ * keyboard input.
+ * @output Browser evidence that the focus the menu returns to a trigger the
+ * caller renders follows the last input
+ * (docs/architecture/interaction-modality.md INV1,
+ * `component:DropdownMenu/DEC-1`): no ring after a pointer pick, the ring
+ * after a keyboard pick.
+ * @position Cross-browser proof; jsdom only proves which focus call the menu
+ * makes. Unless the menu asks for no ring, both engines ring the focus it
+ * returns after a pointer pick.
+ */
+
+import {expect, test, type Locator, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+async function mount(page: Page): Promise<Locator> {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-dropdownmenu--custom-trigger&viewMode=story`,
+ );
+ const trigger = page.getByRole('button', {name: 'More actions'});
+ await expect(trigger).toBeVisible();
+ return trigger;
+}
+
+async function matchesFocusVisible(locator: Locator): Promise<boolean> {
+ return locator.evaluate(element => element.matches(':focus-visible'));
+}
+
+test('a pointer pick returns focus to the trigger without a ring', async ({
+ page,
+}) => {
+ const trigger = await mount(page);
+ await trigger.click();
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+ await page.getByRole('menuitem', {name: 'Rename'}).click();
+ await expect(menu).toBeHidden();
+ await expect(trigger).toBeFocused();
+ expect(await matchesFocusVisible(trigger)).toBe(false);
+});
+
+test('a keyboard pick returns focus to the trigger with its ring', async ({
+ page,
+}) => {
+ const trigger = await mount(page);
+ await trigger.focus();
+ await page.keyboard.press('Enter');
+ const menu = page.getByRole('menu');
+ await expect(page.getByRole('menuitem', {name: 'Rename'})).toBeFocused();
+ await page.keyboard.press('Enter');
+ await expect(menu).toBeHidden();
+ await expect(trigger).toBeFocused();
+ expect(await matchesFocusVisible(trigger)).toBe(true);
+});