Skip to content

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

TypeScript

fix(DropdownMenu): a row the pointer lights takes focus without :focus-visible (#8221)

Christopher Chedeau785e42ad929f
diff --git a/.changeset/menu-hover-focus-not-visible.md b/.changeset/menu-hover-focus-not-visible.md
new file mode 100644
index 0000000000..78c81c5363
--- /dev/null
+++ b/.changeset/menu-hover-focus-not-visible.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] DropdownMenu, ContextMenu: after a pointer press, a row the mouse rests on, or a held press is dragged over, takes focus without matching `:focus-visible`. A plain focus inherited the state from the focus before it (the menu after a pointer open), so any keyboard-only focus style, a theme's or an app's, painted on the row under the mouse. That focus now follows the last input, as other programmatic focus in Astryx does: after a keyboard open, or a key press, the indicator stays. Checkbox, radio and sub-menu rows, and the ContextMenu and Breadcrumbs menus built on them, follow. Browsers without the focus option (Chrome and Edge before 145, Safari before 18.4) keep the earlier behavior.
+
+@vjeux
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index dfd0139b31..8634edd39f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1576,6 +1576,17 @@ jobs:
--project chromium \
--output table-min-width-output
+ # A row the pointer lights in a menu (a resting mouse, a held press
+ # dragged over it) takes focus without matching :focus-visible, and a key
+ # pressed afterwards moves focus with it; jsdom has no focus-visible
+ # heuristic, so only a real engine shows it.
+ - name: Run menu hover focus contract
+ run: |
+ pnpm exec playwright test \
+ packages/core/src/DropdownMenu/__tests__/MenuHoverFocus.a11y.chromium.spec.ts \
+ --project chromium \
+ --output menu-hover-focus-output
+
# A CodeBlock diff row's tint has to follow a long line to the end of its
# scroll width; jsdom has no layout, so only a real engine shows whether
# the paint stops at the viewport edge when the reader scrolls.
diff --git a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
index 479465e78d..6df4d9e270 100644
--- a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
+++ b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
@@ -68,6 +68,7 @@ import {
import type {DropdownMenuOption} from '../DropdownMenu/DropdownMenu';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {useInteractionModalityTracking} from '../utils/interactionModality';
// =============================================================================
// Props
// =============================================================================
@@ -519,6 +520,10 @@ function BreadcrumbMenuTrigger({
const triggerId = useId();
const buttonRef = useRef<HTMLButtonElement>(null);
const isSupporting = variant === 'supporting';
+ // The menu's rows move focus with the last input
+ // (`architecture:interaction-modality` INV1); this menu has no press model
+ // to activate the tracking they read, so it activates it itself.
+ useInteractionModalityTracking();
const popover = usePopover({
hasLightDismiss: true,
diff --git a/packages/core/src/Breadcrumbs/Breadcrumbs.test.tsx b/packages/core/src/Breadcrumbs/Breadcrumbs.test.tsx
index 8535b1cb28..aaba1212fe 100644
--- a/packages/core/src/Breadcrumbs/Breadcrumbs.test.tsx
+++ b/packages/core/src/Breadcrumbs/Breadcrumbs.test.tsx
@@ -457,6 +457,28 @@ describe('BreadcrumbItem menu', () => {
).toBeInTheDocument();
});
+ it('after a pointer open, a row the mouse rests on takes focus without :focus-visible', async () => {
+ // Nothing else in this file activates the shared modality tracking, so
+ // the menu crumb must activate it for its rows to follow the last input
+ // (architecture:interaction-modality INV1).
+ const user = userEvent.setup();
+ render(
+ <Breadcrumbs>
+ <BreadcrumbItem menu={items}>Teams</BreadcrumbItem>
+ <BreadcrumbItem isCurrent>Overview</BreadcrumbItem>
+ </Breadcrumbs>,
+ );
+ await user.click(screen.getByRole('button', {name: 'Teams'}));
+ const design = screen.getByRole('menuitem', {name: 'Design', hidden: true});
+ const focusSpy = vi.spyOn(design, 'focus');
+ fireEvent.pointerMove(design, {pointerType: 'mouse'});
+ expect(design).toHaveFocus();
+ expect(focusSpy).toHaveBeenCalledWith({
+ preventScroll: true,
+ focusVisible: false,
+ });
+ });
+
it('fires the item onClick and closes the menu on select', async () => {
const user = userEvent.setup();
const onDesign = vi.fn();
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 490f79b480..324eda6207 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -2262,11 +2262,37 @@ describe('DropdownMenu keyboard access for menuitemradio/menuitemcheckbox (#3829
// focus-driven highlight follows the pointer instead of leaving two.
// Focus must be scroll-free: scrolling the focused item into view moves
// the next item under the stationary pointer, which re-highlights and
- // scrolls again — a runaway auto-scroll loop.
+ // scrolls again — a runaway auto-scroll loop. And it is the mouse's focus,
+ // so it asks the browser not to match :focus-visible.
const focusSpy = vi.spyOn(del, 'focus');
fireEvent.pointerMove(del, {pointerType: 'mouse'});
expect(del).toHaveFocus();
expect(edit).not.toHaveFocus();
+ expect(focusSpy).toHaveBeenCalledWith({
+ preventScroll: true,
+ focusVisible: false,
+ });
+ });
+
+ it('after a keyboard open, focus that follows the mouse keeps the keyboard indicator (the last input)', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem label="Edit" onClick={() => {}} />
+ <DropdownMenuItem label="Delete" onClick={() => {}} />
+ </DropdownMenu>,
+ );
+ screen.getByRole('button', {name: /Actions/}).focus();
+ await user.keyboard('{ArrowDown}');
+ const edit = screen.getByRole('menuitem', {name: 'Edit', hidden: true});
+ await waitFor(() => expect(edit).toHaveFocus());
+
+ // No pointer press since the key: the browser keeps deciding the
+ // indicator, as for any focus the keyboard moved.
+ const del = screen.getByRole('menuitem', {name: 'Delete', hidden: true});
+ const focusSpy = vi.spyOn(del, 'focus');
+ fireEvent.pointerMove(del, {pointerType: 'mouse'});
+ expect(del).toHaveFocus();
expect(focusSpy).toHaveBeenCalledWith({preventScroll: true});
});
diff --git a/packages/core/src/DropdownMenu/__tests__/MenuHoverFocus.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/MenuHoverFocus.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..b926af31cf
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/MenuHoverFocus.a11y.chromium.spec.ts
@@ -0,0 +1,237 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MenuHoverFocus.a11y.chromium.spec.ts
+ * @input The `Core/DropdownMenu` Default, LabCheckboxItems, LabRadioGroup and
+ * Submenu stories, the `Core/ContextMenu` Default story and the
+ * `Core/Breadcrumbs` Menu Crumb story in a built
+ * Storybook, with real mouse and keyboard input.
+ * @output Real-engine evidence that focus the pointer moves onto a row (a
+ * resting mouse, or a held press dragged over it) follows the last input
+ * (`architecture:interaction-modality` INV1): after a pointer press the row
+ * does not match `:focus-visible`, an arrow key afterwards moves focus to a
+ * row that does, and after a keyboard open the indicator stays. A first case
+ * checks that the browser running them honors `FocusOptions.focusVisible`
+ * and records its version.
+ * @position Run with `pnpm test:a11y-contract`; jsdom has no `:focus-visible`
+ * heuristic, so only a real engine shows whether hover focus would paint a
+ * keyboard-only focus style.
+ */
+
+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 gotoStory(page: Page, id: string) {
+ await page.goto(`${storybook.origin}/iframe.html?id=${id}&viewMode=story`);
+}
+
+async function center(target: Locator): Promise<{x: number; y: number}> {
+ const box = await target.boundingBox();
+ if (box == null) {
+ throw new Error('the element has no layout box');
+ }
+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};
+}
+
+async function matchesFocusVisible(target: Locator): Promise<boolean> {
+ return target.evaluate(el => el.matches(':focus-visible'));
+}
+
+/** Rests the mouse on a row; the menu moves focus to it. */
+async function hover(page: Page, row: Locator) {
+ const {x, y} = await center(row);
+ await page.mouse.move(x, y, {steps: 4});
+ await expect(row).toBeFocused();
+}
+
+test('the browser running these cases honors FocusOptions.focusVisible', async ({
+ page,
+ browser,
+ browserName,
+}) => {
+ test.info().annotations.push({
+ type: 'browser',
+ description: `${browserName} ${browser.version()}`,
+ });
+ const markup =
+ '<button id="key">Key</button><div id="row" tabindex="-1">Row</div>';
+ // After a key press, a plain focus() inherits :focus-visible...
+ await page.setContent(markup);
+ await page.keyboard.press('Tab');
+ await expect(page.locator('#key')).toBeFocused();
+ const plain = await page.locator('#row').evaluate((row: HTMLElement) => {
+ row.focus();
+ return row.matches(':focus-visible');
+ });
+ expect(plain).toBe(true);
+ // ...and the option keeps it from matching. Chrome and Edge from 145,
+ // Firefox from 104 and Safari from 18.4 honor it; an older engine ignores
+ // it, and the cases below would then fail for that reason alone.
+ await page.setContent(markup);
+ await page.keyboard.press('Tab');
+ await expect(page.locator('#key')).toBeFocused();
+ const withOption = await page.locator('#row').evaluate((row: HTMLElement) => {
+ row.focus({focusVisible: false});
+ return row.matches(':focus-visible');
+ });
+ expect(
+ withOption,
+ `${browserName} ${browser.version()} ignores FocusOptions.focusVisible`,
+ ).toBe(false);
+});
+
+test('after a pointer open, rows the mouse rests on take focus without :focus-visible, and ArrowDown afterwards gets it', async ({
+ page,
+}) => {
+ await gotoStory(page, 'core-dropdownmenu--default');
+ await page.getByRole('button', {name: 'Actions'}).click();
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+
+ const edit = menu.getByRole('menuitem', {name: 'Edit'});
+ const duplicate = menu.getByRole('menuitem', {name: 'Duplicate'});
+ const del = menu.getByRole('menuitem', {name: 'Delete'});
+ await hover(page, edit);
+ expect(await matchesFocusVisible(edit)).toBe(false);
+ await hover(page, duplicate);
+ expect(await matchesFocusVisible(duplicate)).toBe(false);
+
+ // The keyboard takes over from where the mouse left the highlight.
+ await page.keyboard.press('ArrowDown');
+ await expect(del).toBeFocused();
+ expect(await matchesFocusVisible(del)).toBe(true);
+});
+
+test('in a Breadcrumbs menu alone on the page, rows the mouse rests on take focus without :focus-visible after a pointer open', async ({
+ page,
+}) => {
+ // Nothing else on this page activates the modality tracking, so the menu
+ // crumb must activate it itself.
+ await gotoStory(page, 'core-breadcrumbs--menu-crumb');
+ await page.getByRole('button', {name: 'Teams'}).click();
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+ const design = menu.getByRole('menuitem', {name: 'Design'});
+ const engineering = menu.getByRole('menuitem', {name: 'Engineering'});
+ await hover(page, design);
+ expect(await matchesFocusVisible(design)).toBe(false);
+ await hover(page, engineering);
+ expect(await matchesFocusVisible(engineering)).toBe(false);
+});
+
+test('after a keyboard open, a row the mouse moves to keeps the indicator: no pointer press changed the last input', async ({
+ page,
+}) => {
+ await gotoStory(page, 'core-dropdownmenu--default');
+ await page.getByRole('button', {name: 'Actions'}).focus();
+ await page.keyboard.press('ArrowDown');
+ const menu = page.getByRole('menu');
+ const edit = menu.getByRole('menuitem', {name: 'Edit'});
+ await expect(edit).toBeFocused();
+ expect(await matchesFocusVisible(edit)).toBe(true);
+
+ const del = menu.getByRole('menuitem', {name: 'Delete'});
+ await hover(page, del);
+ expect(await matchesFocusVisible(del)).toBe(true);
+});
+
+test('checkbox, radio and sub-menu rows the mouse rests on take focus without :focus-visible after a pointer open', async ({
+ page,
+}) => {
+ const cases = [
+ {
+ story: 'core-dropdownmenu--lab-checkbox-items',
+ button: 'View',
+ role: 'menuitemcheckbox',
+ name: 'Show drafts',
+ },
+ {
+ story: 'core-dropdownmenu--lab-radio-group',
+ button: 'Sort',
+ role: 'menuitemradio',
+ name: 'Oldest',
+ },
+ {
+ story: 'core-dropdownmenu--submenu',
+ button: 'Actions',
+ role: 'menuitem',
+ name: 'Move to',
+ },
+ ] as const;
+ for (const {story, button, role, name} of cases) {
+ await gotoStory(page, story);
+ const trigger = page.getByRole('button', {name: button});
+ await expect(trigger).toBeVisible();
+ // A story may open its own menu on load; close it, so the open below is
+ // a pointer press.
+ const menu = page.getByRole('menu').first();
+ if (await menu.isVisible()) {
+ await page.keyboard.press('Escape');
+ await expect(menu).toBeHidden();
+ }
+ await trigger.click();
+ const row = menu.getByRole(role, {name});
+ await expect(row).toBeVisible();
+ await hover(page, row);
+ expect(await matchesFocusVisible(row), `${role} "${name}"`).toBe(false);
+ }
+});
+
+test('a ContextMenu row the mouse rests on takes focus without :focus-visible, and ArrowDown afterwards gets it', async ({
+ page,
+}) => {
+ await gotoStory(page, 'core-contextmenu--default');
+ const area = page.getByText('Right-click this area');
+ const {x, y} = await center(area);
+ await page.mouse.click(x, y, {button: 'right'});
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+
+ // Not the first row: the menu's own open focuses that one.
+ const copy = menu.getByRole('menuitem', {name: 'Copy'});
+ await hover(page, copy);
+ expect(await matchesFocusVisible(copy)).toBe(false);
+
+ await page.keyboard.press('ArrowDown');
+ const paste = menu.getByRole('menuitem', {name: 'Paste'});
+ await expect(paste).toBeFocused();
+ expect(await matchesFocusVisible(paste)).toBe(true);
+});
+
+test('a row a held press is dragged over takes focus without :focus-visible', async ({
+ page,
+}) => {
+ await gotoStory(page, 'core-dropdownmenu--default');
+ const trigger = page.getByRole('button', {name: 'Actions'});
+ const start = await center(trigger);
+ await page.mouse.move(start.x, start.y);
+ await page.mouse.down();
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+
+ const duplicate = menu.getByRole('menuitem', {name: 'Duplicate'});
+ const over = await center(duplicate);
+ await page.mouse.move(over.x, over.y, {steps: 8});
+ await expect(duplicate).toBeFocused();
+ expect(await matchesFocusVisible(duplicate)).toBe(false);
+
+ // Releasing over the row picks it, as the press model does.
+ await page.mouse.up();
+ await expect(menu).toBeHidden();
+});
diff --git a/packages/core/src/DropdownMenu/menuItemHover.ts b/packages/core/src/DropdownMenu/menuItemHover.ts
index bfe6c84dd7..a1220dee6b 100644
--- a/packages/core/src/DropdownMenu/menuItemHover.ts
+++ b/packages/core/src/DropdownMenu/menuItemHover.ts
@@ -11,6 +11,9 @@
* highlight source. Mouse hover moves focus onto the pointed-at item so the
* one focus highlight follows the pointer — instead of a separate `:hover`
* background leaving the keyboard-focused item highlighted at the same time.
+ * That focus follows the last input (`architecture:interaction-modality` INV1):
+ * after a pointer press it does not match `:focus-visible`, so a keyboard-only
+ * focus style does not paint on the row under the mouse.
*
* SYNC: When modified, update the item components that use it:
* - /packages/core/src/DropdownMenu/DropdownMenuItem.tsx
@@ -20,6 +23,7 @@
*/
import type {PointerEvent} from 'react';
+import {focusForLastInput} from '../utils/focusReturn';
/**
* Move focus to a menu item as the pointer moves over it, so hover and
@@ -39,6 +43,14 @@ export function focusMenuItemOnHover(
// stationary pointer, whose next pointerenter focuses it again — a
// runaway auto-scroll loop. Keyboard navigation scrolls via its own
// highlight handling; hover must never scroll.
- el.focus({preventScroll: true});
+ // A plain focus() inherits :focus-visible from the element focused before
+ // it (the menu after a pointer open), so after a pointer press it is moved
+ // with the browser's focusVisible option instead. After a key press the
+ // keyboard is the last input and the indicator stays. A browser without
+ // the option (Chrome and Edge before 145, Safari before 18.4) ignores it,
+ // and the row may then match :focus-visible as it did before.
+ // The menu activates the modality tracking this reads (its press model,
+ // or the Breadcrumbs menu trigger).
+ focusForLastInput(el, {preventScroll: true});
}
}
diff --git a/packages/core/src/hooks/useMenuPress.doc.mjs b/packages/core/src/hooks/useMenuPress.doc.mjs
index b860c2de93..d9a1835d49 100644
--- a/packages/core/src/hooks/useMenuPress.doc.mjs
+++ b/packages/core/src/hooks/useMenuPress.doc.mjs
@@ -55,7 +55,7 @@ export const docs = {
name: 'options.onHighlight',
type: '(row: HTMLElement | null) => void',
description:
- 'Move the highlight; null clears it. Defaults to moving DOM focus with preventScroll onto the row, and onto the menu root when there is no row. A picker that highlights through aria-activedescendant supplies its own.',
+ 'Move the highlight; null clears it. Defaults to moving DOM focus with preventScroll onto the row, and onto the menu root when there is no row; after a pointer press that focus does not match :focus-visible. A picker that highlights through aria-activedescendant supplies its own.',
},
{
name: 'options.onActivate',
@@ -164,7 +164,7 @@ export const docsDense = {
'options.onTriggerPress':
'mouse press / held finger on trigger: open, return whether it opened (false = the press closed it).',
'options.onHighlight':
- 'move highlight (null clears); default = focus w/ preventScroll, menu root when no row.',
+ 'move highlight (null clears); default = focus w/ preventScroll (not :focus-visible after a pointer press), menu root when no row.',
'options.onActivate':
'act on row under release; default = dispatch click w/ release button + modifiers.',
'options.onDismiss': 'MOUSE released outside: close. Finger: never called.',
diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx
index f8e6571ff8..d686fa0a5b 100644
--- a/packages/core/src/hooks/useMenuPress.test.tsx
+++ b/packages/core/src/hooks/useMenuPress.test.tsx
@@ -171,7 +171,7 @@ describe('useMenuPress — tracking inside the menu', () => {
}
});
- it('moves the highlight as focus with preventScroll', () => {
+ it('moves the highlight as focus with preventScroll and without :focus-visible', () => {
render(<Harness />);
const b = row('B');
const focusSpy = vi.spyOn(b, 'focus');
@@ -179,7 +179,10 @@ describe('useMenuPress — tracking inside the menu', () => {
expect(row('A')).toHaveFocus();
fireEvent.pointerMove(b, touch());
expect(b).toHaveFocus();
- expect(focusSpy).toHaveBeenCalledWith({preventScroll: true});
+ expect(focusSpy).toHaveBeenCalledWith({
+ preventScroll: true,
+ focusVisible: false,
+ });
});
it('clears the highlight over a disabled row or a divider and acts on nothing there', () => {
diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts
index 695810656b..dd06ef3ad1 100644
--- a/packages/core/src/hooks/useMenuPress.ts
+++ b/packages/core/src/hooks/useMenuPress.ts
@@ -18,7 +18,8 @@
* pointer events stay with the element it landed on (implicit capture), so a
* menu container never sees a finger that slid onto it — the document does.
* - The highlight follows the pointer (DOM focus with `preventScroll` in a
- * menu; a callback for a picker that highlights by index).
+ * menu, its indicator following the last input; a callback for a picker
+ * that highlights by index).
* - The row under the RELEASE acts, the way its own click would, carrying the
* release's button and modifier keys.
* - The browser's stray `click` for a tracked gesture is swallowed at the
@@ -58,6 +59,8 @@ import {
type MenuPressPointerType,
} from './menuPressGesture';
import {useLongPress, type UseLongPressHandlers} from './useLongPress';
+import {focusForLastInput} from '../utils/focusReturn';
+import {useInteractionModalityTracking} from '../utils/interactionModality';
/** Marks a menu root that carries this press model. */
export const MENU_PRESS_MARKER = 'data-astryx-menu-press';
@@ -327,6 +330,9 @@ interface ResolvedPoint {
export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
const optionsRef = useRef(options);
optionsRef.current = options;
+ // The highlight, and the hover focus of the rows in this menu, follow the
+ // last input, which this tracks for the document.
+ useInteractionModalityTracking();
const gestureRef = useRef<MenuPressGesture<HTMLElement>>(IDLE_MENU_PRESS);
const pointerIdRef = useRef<number | null>(null);
@@ -423,7 +429,10 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
}
// In a menu the highlight IS focus. A row whose root takes no
// focus is highlighted through the control inside it; over nothing,
- // the menu root holds focus so no row is lit.
+ // the menu root holds focus so no row is lit. The focus follows the
+ // last input (`architecture:interaction-modality` INV1): a held press
+ // is pointer input, so the row does not match :focus-visible, which a
+ // plain focus() would inherit from the focus before it.
const target =
row == null
? menuRef.current
@@ -431,7 +440,7 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
? row
: row.querySelector<HTMLElement>(INNER_CONTROL_SELECTOR);
if (target != null && target !== getDocument().activeElement) {
- target.focus({preventScroll: true});
+ focusForLastInput(target, {preventScroll: true});
}
},
[getDocument],