An open source design system that's fully customizable and agent ready
TypeScript
fix(core): full APG menu pattern for TopNavMenu popups (#3994)
Baraa Hamodi9fca3afb22cb
diff --git a/.changeset/topnavmenu-menu-pattern.md b/.changeset/topnavmenu-menu-pattern.mdnew file mode 100644index 0000000000..2095c45b05--- /dev/null+++ b/.changeset/topnavmenu-menu-pattern.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] TopNav: TopNavMenu popups now expose proper menu semantics (no modal dialog wrapper) with the full APG keyboard pattern (roving tabindex, arrow keys, typeahead).+@bhamodidiff --git a/packages/core/src/TopNav/TopNavMenu.test.tsx b/packages/core/src/TopNav/TopNavMenu.test.tsxindex bd3f0af678..895e15c7f5 100644--- a/packages/core/src/TopNav/TopNavMenu.test.tsx+++ b/packages/core/src/TopNav/TopNavMenu.test.tsx@@ -9,8 +9,9 @@* SYNC: When TopNavMenu changes, update tests to match new behavior*/-import {describe, it, expect} from 'vitest';-import {render, screen} from '@testing-library/react';+import {describe, it, expect, vi} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import userEvent from '@testing-library/user-event';import {TopNavMenu} from './TopNavMenu';const mockItems = [@@ -32,10 +33,13 @@ describe('TopNavMenu', () => {expect(screen.getByRole('button', {name: 'Products'})).toBeInTheDocument();});- it('trigger has aria-haspopup attribute', () => {+ it('trigger announces a menu popup, not a dialog', () => {render(<TopNavMenu label="Products" items={mockItems} />);const trigger = screen.getByRole('button', {name: 'Products'});- expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');+ // usePopover with role:'none' emits aria-haspopup="true" (the ARIA+ // synonym for "menu") because the exposed semantics of the popup are its+ // child role="menu", not a dialog.+ expect(trigger).toHaveAttribute('aria-haspopup', 'true');});it('renders with custom items', () => {@@ -57,3 +61,113 @@ describe('TopNavMenu', () => {expect(screen.getByRole('button', {name: 'Menu'})).toBeInTheDocument();});});++describe('menu semantics (APG)', () => {+ it('does not wrap the popup in a role="dialog" / aria-modal shell', () => {+ render(<TopNavMenu label="Products" items={mockItems} />);+ // The popup's exposed semantics are the role="menu" container itself —+ // no dialog wrapper, no aria-modal.+ expect(+ screen.queryByRole('dialog', {hidden: true}),+ ).not.toBeInTheDocument();+ expect(document.querySelector('[aria-modal]')).toBeNull();+ expect(+ screen.getByRole('menu', {name: 'Products', hidden: true}),+ ).toBeInTheDocument();+ });+});++describe('keyboard navigation (APG menu pattern)', () => {+ it('exposes exactly one tab stop among menu items (roving tabindex)', async () => {+ const user = userEvent.setup();+ render(<TopNavMenu label="Products" items={mockItems} />);+ await user.click(screen.getByRole('button', {name: 'Products'}));++ const items = screen.getAllByRole('menuitem', {hidden: true});+ expect(items).toHaveLength(2);+ const tabbable = items.filter(el => el.getAttribute('tabindex') === '0');+ expect(tabbable).toHaveLength(1);+ });++ it('moves focus with ArrowDown/ArrowUp and the tab stop follows', async () => {+ const user = userEvent.setup();+ render(<TopNavMenu label="Products" items={mockItems} />);+ await user.click(screen.getByRole('button', {name: 'Products'}));++ const menu = screen.getByRole('menu', {hidden: true});+ const items = screen.getAllByRole('menuitem', {hidden: true});+ items[0].focus();++ fireEvent.keyDown(menu, {key: 'ArrowDown'});+ expect(items[1]).toHaveFocus();+ expect(items[1]).toHaveAttribute('tabindex', '0');+ expect(items[0]).toHaveAttribute('tabindex', '-1');++ fireEvent.keyDown(menu, {key: 'ArrowUp'});+ expect(items[0]).toHaveFocus();+ expect(items[0]).toHaveAttribute('tabindex', '0');+ expect(items[1]).toHaveAttribute('tabindex', '-1');+ });++ it('wraps focus at both ends', async () => {+ const user = userEvent.setup();+ render(<TopNavMenu label="Products" items={mockItems} />);+ await user.click(screen.getByRole('button', {name: 'Products'}));++ const menu = screen.getByRole('menu', {hidden: true});+ const items = screen.getAllByRole('menuitem', {hidden: true});++ items[1].focus();+ fireEvent.keyDown(menu, {key: 'ArrowDown'});+ expect(items[0]).toHaveFocus();++ fireEvent.keyDown(menu, {key: 'ArrowUp'});+ expect(items[1]).toHaveFocus();+ });++ it('typeahead moves focus to the item matching the typed character', async () => {+ const user = userEvent.setup();+ render(<TopNavMenu label="Products" items={mockItems} />);+ await user.click(screen.getByRole('button', {name: 'Products'}));++ const menu = screen.getByRole('menu', {hidden: true});+ fireEvent.keyDown(menu, {key: 'm'});+ expect(+ screen.getByRole('menuitem', {name: /Messaging/, hidden: true}),+ ).toHaveFocus();+ });++ it('activates a focused onClick-only item with Enter', async () => {+ const user = userEvent.setup();+ const onClick = vi.fn();+ render(<TopNavMenu label="Menu" items={[{title: 'Action', onClick}]} />);+ await user.click(screen.getByRole('button', {name: 'Menu'}));++ const item = screen.getByRole('menuitem', {hidden: true});+ item.focus();+ fireEvent.keyDown(item, {key: 'Enter'});+ expect(onClick).toHaveBeenCalledOnce();+ });++ it('still activates an item on click', async () => {+ const user = userEvent.setup();+ const onClick = vi.fn();+ render(<TopNavMenu label="Menu" items={[{title: 'Action', onClick}]} />);+ await user.click(screen.getByRole('button', {name: 'Menu'}));++ await user.click(screen.getByRole('menuitem', {hidden: true}));+ expect(onClick).toHaveBeenCalledOnce();+ });++ it('closes the menu with Escape', async () => {+ const user = userEvent.setup();+ render(<TopNavMenu label="Products" items={mockItems} />);+ const trigger = screen.getByRole('button', {name: 'Products'});+ await user.click(trigger);+ expect(trigger).toHaveAttribute('aria-expanded', 'true');++ const menu = screen.getByRole('menu', {hidden: true});+ fireEvent.keyDown(menu, {key: 'Escape'});+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });+});diff --git a/packages/core/src/TopNav/TopNavMenu.tsx b/packages/core/src/TopNav/TopNavMenu.tsxindex 935f8a4c58..9325dcf0a3 100644--- a/packages/core/src/TopNav/TopNavMenu.tsx+++ b/packages/core/src/TopNav/TopNavMenu.tsx@@ -4,7 +4,8 @@/*** @file TopNavMenu.tsx- * @input Uses React, StyleX, useHoverCard, TopNavItem tokens+ * @input Uses React, StyleX, usePopover, useMenuHover, useListFocus,+ * useTypeahead, TopNavItem tokens* @output Exports TopNavMenu component and related types* @position Navigation item with hover-triggered overflow menu for TopNav*@@ -15,10 +16,18 @@* - /packages/cli/templates/blocks/components/TopNav/ (showcase blocks)*/-import React, {useId, useRef, useState, type ReactNode} from 'react';+import React, {+ useCallback,+ useId,+ useRef,+ useState,+ type ReactNode,+} from 'react';import * as stylex from '@stylexjs/stylex';import {usePopover} from '../Popover/usePopover';import {useMenuHover} from '../hooks/useMenuHover';+import {useListFocus} from '../hooks/useListFocus';+import {useTypeahead} from '../hooks/useTypeahead';import {getIcon} from '../Icon/globalIconRegistry';import {mergeProps, mergeRefs} from '../utils';import type {BaseProps} from '../BaseProps';@@ -332,7 +341,10 @@ export function TopNavMenu({const triggerButtonRef = useRef<HTMLButtonElement | null>(null);const popover = usePopover({- dialogLabel: label,+ // The popup's own role="menu" is the exposed semantics; a modal dialog+ // wrapper would announce an unnamed dialog around the menu and make the+ // trigger claim aria-haspopup="dialog" for menu content (see TabMenu).+ role: 'none',xstyle: styles.menuOffset,});@@ -353,6 +365,65 @@ export function TopNavMenu({ref,);+ // The desktop popup is a composite menu widget per the APG menu pattern:+ // a single roving tab stop with ArrowUp/ArrowDown traversal (wrapping),+ // Home/End, and first-character typeahead. The hook owns item tabindex —+ // items render tabIndex={-1} and exactly one is promoted to 0. The+ // composition mirrors NavHeadingMenu.+ const {listRef, handleKeyDown, handleFocus, focusItem} =+ useListFocus<HTMLDivElement>({+ itemSelector: '[role="menuitem"]',+ hasRovingTabIndex: true,+ onEscape: popover.hide,+ });++ // First-character typeahead over the menu items (menus-11).+ const getMenuItems = useCallback(+ (): HTMLElement[] =>+ listRef.current+ ? Array.from(+ listRef.current.querySelectorAll<HTMLElement>('[role="menuitem"]'),+ )+ : [],+ [listRef],+ );+ const typeahead = useTypeahead({+ getItemLabels: () => getMenuItems().map(el => el.textContent),+ onMatch: focusItem,+ getCurrentIndex: () =>+ getMenuItems().findIndex(+ el =>+ el === document.activeElement || el.contains(document.activeElement),+ ),+ });++ // Extend useListFocus with Enter/Space activation. Items rendered without an+ // `href` are `<div role="menuitem">` elements, which have no native keyboard+ // activation — without this, Enter/Space on a focused onClick-only item does+ // nothing. Anchor items (with `href`) already activate on Enter natively.+ const menuKeyDown = useCallback(+ (e: React.KeyboardEvent) => {+ if (e.key === 'Enter' || e.key === ' ') {+ const focused = document.activeElement as HTMLElement | null;+ if (focused?.getAttribute('role') === 'menuitem') {+ e.preventDefault();+ focused.click();+ return;+ }+ }+ if (typeahead.onKeyDown(e)) {+ e.preventDefault();+ return;+ }+ handleKeyDown(e);+ },+ [handleKeyDown, typeahead],+ );++ // Menu container carries both the hover hook's ref (for its open/close+ // focus management) and the list-focus ref (for roving tabindex/typeahead).+ const setMenuRef = mergeRefs<HTMLDivElement>(menuRef, listRef);+// Mobile bar: hide menus entirelyif (renderMode === 'mobile-bar') {return null;@@ -437,10 +508,15 @@ export function TopNavMenu({</button>{popover.render(<div- ref={menuRef}+ ref={setMenuRef}role="menu"aria-label={label}{...contentProps}+ // After the contentProps spread so the full APG composition (roving+ // tabindex + typeahead + Enter/Space activation) replaces the hover+ // hook's basic arrow-key handler.+ onKeyDown={menuKeyDown}+ onFocus={handleFocus}{...stylex.props(styles.menuContainer)}>{items.map(item => {const Element = item.href ? 'a' : 'div';@@ -448,7 +524,9 @@ export function TopNavMenu({<Elementkey={getMenuItemKey(item)}role="menuitem"- tabIndex={popover.isOpen ? 0 : -1}+ // Single tab stop: useListFocus owns the roving tabindex and+ // promotes exactly one item to 0.+ tabIndex={-1}href={item.href}onClick={item.onClick}{...stylex.props(styles.menuItem)}>