An open source design system that's fully customizable and agent ready
TypeScript
fix(DropdownMenu): a field or button a menu hosts beside its rows keeps its own keys (#7309)
Christopher Chedeau0f2d2edc3c21
diff --git a/.changeset/menu-hosted-field-keys.md b/.changeset/menu-hosted-field-keys.mdnew file mode 100644index 0000000000..55110d35ae--- /dev/null+++ b/.changeset/menu-hosted-field-keys.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A field or a button that a DropdownMenu, ContextMenu or sub-menu hosts beside its rows keeps its own keys: typed text, Space and Enter reach the field, its caret keys move the caret until the caret reaches an edge, and Enter or Space press a hosted button. The menu's typeahead and Enter/Space activation used to take those keys, so a field inside a menu could not be typed in. Rows, Tab and Escape behave as before.++@vjeuxdiff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsxindex 20049f0b94..b0eea08436 100644--- a/apps/storybook/stories/DropdownMenu.stories.tsx+++ b/apps/storybook/stories/DropdownMenu.stories.tsx@@ -15,6 +15,8 @@ import {DropdownMenuRadioItem,DropdownMenuSubMenu,} from '@astryxdesign/core/DropdownMenu';+import {Button} from '@astryxdesign/core/Button';+import {TextInput} from '@astryxdesign/core/TextInput';import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';import {PencilIcon,@@ -1427,3 +1429,35 @@ export const SubmenuAdaptiveFixture: Story = {</div>),};++// A menu that hosts a field and a button beside its rows: the field keeps+// what is typed and the button its own keys, while the rows keep the menu's.+export const HostedField: Story = {+ render: () => {+ const [query, setQuery] = useState('');+ const [created, setCreated] = useState(0);+ return (+ <>+ <DropdownMenu button={{label: 'Labels'}}>+ <TextInput+ label="Filter labels"+ isLabelHidden+ value={query}+ onChange={setQuery}+ />+ <Button+ label="Create label"+ variant="ghost"+ onClick={() => setCreated(count => count + 1)}+ />+ <DropdownMenuItem label="Bug" onClick={() => console.log('Bug')} />+ <DropdownMenuItem+ label="Feature"+ onClick={() => console.log('Feature')}+ />+ </DropdownMenu>+ <output data-testid="created">{created}</output>+ </>+ );+ },+};diff --git a/packages/core/src/ContextMenu/ContextMenu.spec.md b/packages/core/src/ContextMenu/ContextMenu.spec.mdindex 51c89df3e9..dcb1e92668 100644--- a/packages/core/src/ContextMenu/ContextMenu.spec.md+++ b/packages/core/src/ContextMenu/ContextMenu.spec.md@@ -90,7 +90,7 @@ Consumer props, content modes, and presentation policy remain documented in| FR5 | The Pointer menu surface carries `data-astryx-menu-press` and follows `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 stray click never acts, and `touch-action` follows overflow. Right-click, Shift+F10, long-press invocation and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `ContextMenu.test.tsx` press model suite | Proposed; verified in jsdom || FR6 | With `triggerAs="span"` the Trigger area MUST be an inline element that owns a box, so the cursor anchor measures from the trigger's own rect on every invocation path. Every invocation path (right-click, Shift+F10, long-press) and the `context-menu` target's placement are unchanged. | `component:ContextMenu/DEC-1` | Accepted; verified in jsdom || FR7 | Sub-menu rows follow `component:DropdownMenu` FR12 inside the pointer menu: ContextMenu mounts the same drill-in view stack, named after its `label`, so a sub-menu drills in on a phone here too. | `component:DropdownMenu/DEC-2` | Proposed; verified in jsdom |-| FR8 | 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 page as in DropdownMenu FR6; a held key's auto-repeat does not activate; typeahead matches the row's label element alone. | Proposed in this change; `ContextMenu.test.tsx` keyboard case; shared `useListFocus` and `useTypeahead` suites | Proposed; verified in jsdom, pending owner review |+| FR8 | 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 page as in DropdownMenu FR6; a held key's auto-repeat does not activate; typeahead matches the row's label element alone. A key pressed in a control the menu hosts beside its rows stays with it, as in `component:DropdownMenu` FR12. | Proposed in this change; `ContextMenu.test.tsx` keyboard case; shared `useListFocus` and `useTypeahead` suites | Proposed; verified in jsdom, pending owner review |### Allowed variation@@ -206,6 +206,7 @@ anchor is positioning infrastructure rather than consumer anatomy.| FR6 | `ContextMenu.test.tsx` keyboard case; shared `useListFocus` and `useTypeahead` suites | wrap at both ends | Clamping arrows fail. | `audit:ContextMenu/behavior` || Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` || FR6, AR1 | `ContextMenu.test.tsx` "inline trigger (triggerAs)" suite | `span` in a paragraph, default `div` | A block trigger inside prose, or a lost invocation path, fails. | `audit:ContextMenu/behavior` |+| FR8 (hosted) | `ContextMenu.test.tsx` compound-mode hosted field case | typing into a hosted field | A hosted field that loses typed text to typeahead fails. | `audit:ContextMenu/behavior` |## Decision logdiff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsxindex c880a9cc3b..1e2e97e72b 100644--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx@@ -564,6 +564,36 @@ describe('ContextMenu dividers', () => {});describe('ContextMenu compound mode', () => {+ it('keeps what is typed in a field the menu hosts beside its rows', async () => {+ const user = userEvent.setup();+ render(+ <ContextMenu+ menuContent={+ <>+ <input aria-label="Filter" />+ <DropdownMenuItem label="Cut" onClick={() => {}} />+ <DropdownMenuItem label="Copy" onClick={() => {}} />+ </>+ }>+ <div>Right-click me</div>+ </ContextMenu>,+ );+ fireEvent.contextMenu(screen.getByText('Right-click me'), {+ clientX: 50,+ clientY: 15,+ detail: 1,+ });+ // Let the open's focus frame land before moving focus.+ await waitFor(() =>+ expect(document.activeElement?.closest('[role="menu"]')).not.toBeNull(),+ );+ const field = screen.getByRole('textbox', {name: 'Filter', hidden: true});+ act(() => field.focus());+ await user.keyboard('co py');+ expect(field).toHaveValue('co py');+ expect(field).toHaveFocus();+ });+it('renders menuContent as menu items', () => {render(<ContextMenudiff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex 77fdc76ad4..5b46378a6f 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -61,6 +61,8 @@ import {MENU_ITEM_SELECTOR,MENU_BOUNDARY_SELECTOR,activateMenuItem,+ hostedControlOf,+ isTextEntry,} from '../DropdownMenu/menuItemRoles';import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow';import {useMenuDrillIn} from '../DropdownMenu/useMenuDrillIn';@@ -416,6 +418,9 @@ export function ContextMenu({// Menus wrap from the last row to the first and back.wrap: true,hasPaging: true,+ // Arrows, Home and End leave a text field the menu hosts only at its+ // caret's edge.+ hasCaretGuard: true,onEscape: closeMenu,});@@ -485,7 +490,13 @@ export function ContextMenu({if (!ownsEvent(e)) {return;}+ // A key pressed in a control the menu hosts beside its rows is that+ // control's; see DropdownMenu.+ const hosted = hostedControlOf(e.target, listRef.current);if (e.key === 'Enter' || e.key === ' ') {+ if (hosted != null) {+ return;+ }e.preventDefault();// A held key's auto-repeat never activates.if (e.repeat) {@@ -511,13 +522,13 @@ export function ContextMenu({closeMenu();return;}- if (typeahead.onKeyDown(e)) {+ if (!(hosted != null && isTextEntry(hosted)) && typeahead.onKeyDown(e)) {e.preventDefault();return;}listNavKeyDown(e);},- [listNavKeyDown, closeMenu, typeahead, ownsEvent],+ [listNavKeyDown, closeMenu, typeahead, ownsEvent, listRef],);// Place the zero-size cursor anchor at a point in the trigger's localdiff --git a/packages/core/src/DropdownMenu/DropdownMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.mdindex ec60514578..739023cb86 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md@@ -111,7 +111,7 @@ released default.| FR10 | An action row with `href` MUST render as one anchor carrying `role="menuitem"` (the pointer menu) or the touch sheet's link row, routed through `LinkProvider`; a plain click MUST run `onClick`, then close the menu (`hasCloseOnSelect`), then let the browser navigate; a modified click or middle click MUST be left to the browser and MUST NOT run `onClick`; Enter and Space MUST activate through a synthesized click that carries the key's modifiers. A disabled link row has no `href`. | `component:DropdownMenu/DEC-2`; `family:navigation-destinations` | Proposed; verified in jsdom; owner to confirm DEC-1 || 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 |+| 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. A key pressed in a control the menu hosts beside its rows stays with it: Enter and Space press it, and a text field keeps typed text and its caret keys until the caret reaches an edge. | 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 || FR14 | A compound `DropdownMenuGroup` is one `role="group"` named by its heading through `aria-labelledby`; the heading carries `dropdown-menu-section-heading`, is plain text rather than a menu item, and is skipped by roving focus and typeahead. An untitled group is an unnamed `role="group"`. | DEC-1, docs, and tests | Proposed; awaiting owner approval |@@ -275,6 +275,7 @@ than adding a DropdownMenu-owned heading target.| FR9 | `DropdownMenu.test.tsx` custom trigger suite; `DropdownMenuSubMenu.test.tsx` custom-trigger Back row cases | Icon button, chip, list row; open, toggle, keyboard open, name; drill-in Back row | A rendered control missing `aria-haspopup`, `aria-expanded` or `aria-controls`, an unnamed menu, a lost keyboard open, or a "Back to Menu" row, 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` |+| FR12 (hosted) | `DropdownMenu.test.tsx` hosted-control keys suite; `DropdownMenuSubMenu.test.tsx` flyout field case; `__tests__/MenuHostedField.a11y.chromium.spec.ts` | typing, Space, Home/End, ArrowDown at the end, Enter/Space on a button, Escape | A hosted field that loses typed text or its caret keys, or a hosted button that a key cannot press, 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 logdiff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex 2300fbf96b..8e86041180 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -20,6 +20,7 @@ import {DropdownMenuItem} from './DropdownMenuItem';import {DropdownMenuDivider} from './DropdownMenuDivider';import {DropdownMenuGroup} from './DropdownMenuGroup';import {Divider} from '../Divider';+import {Button} from '../Button';import {rtlStyles} from '../utils';import {__resetInteractionModalityForTest} from '../utils/interactionModality';import {focusOutlineStyles} from '../utils/focusOutline.stylex';@@ -3353,3 +3354,89 @@ describe('DropdownMenu keyboard', () => {expect(onClick).toHaveBeenCalledTimes(1);});});++describe('DropdownMenu keys in a control the menu hosts', () => {+ function renderMenu() {+ const onCreate = vi.fn<() => void>();+ const onPick = vi.fn<(label: string) => void>();+ render(+ <DropdownMenu button={{label: 'Labels'}}>+ <input aria-label="Filter labels" />+ <Button label="Create label" onClick={onCreate} />+ <DropdownMenuItem label="Bug" onClick={() => onPick('Bug')} />+ <DropdownMenuItem label="Feature" onClick={() => onPick('Feature')} />+ </DropdownMenu>,+ );+ return {onCreate, onPick};+ }+ const field = () =>+ screen.getByRole<HTMLInputElement>('textbox', {+ name: 'Filter labels',+ hidden: true,+ });+ const row = (name: string) =>+ screen.getByRole('menuitem', {name, hidden: true});+ const trigger = () => screen.getByRole('button', {name: /Labels/});++ async function open(user: ReturnType<typeof userEvent.setup>) {+ await user.click(trigger());+ // A pointer open focuses the menu in a frame; let it land first.+ await waitFor(() =>+ expect(+ screen.getByRole('menu', {name: 'Labels', hidden: true}),+ ).toHaveFocus(),+ );+ }++ it('typing, Space and Home stay in a hosted field', async () => {+ const user = userEvent.setup();+ renderMenu();+ await open(user);+ act(() => field().focus());+ await user.keyboard('bu g');+ expect(field()).toHaveValue('bu g');+ expect(field()).toHaveFocus();+ await user.keyboard('{Home}');+ expect(field()).toHaveFocus();+ expect(field().selectionStart).toBe(0);+ });++ it('ArrowDown leaves a hosted field for the first row only from the end of its text', async () => {+ const user = userEvent.setup();+ renderMenu();+ await open(user);+ act(() => field().focus());+ await user.keyboard('x{ArrowLeft}{ArrowDown}');+ expect(field()).toHaveFocus();+ await user.keyboard('{End}{ArrowDown}');+ expect(row('Bug')).toHaveFocus();+ });++ it('Enter and Space press a hosted button, and no row acts', async () => {+ const user = userEvent.setup();+ const {onCreate, onPick} = renderMenu();+ await open(user);+ act(() =>+ screen.getByRole('button', {name: 'Create label', hidden: true}).focus(),+ );+ await user.keyboard('{Enter}');+ expect(onCreate).toHaveBeenCalledTimes(1);+ await user.keyboard(' ');+ expect(onCreate).toHaveBeenCalledTimes(2);+ expect(onPick).not.toHaveBeenCalled();+ });++ it('Escape in a hosted field still closes the menu, and typeahead still roves the rows', async () => {+ const user = userEvent.setup();+ renderMenu();+ await open(user);+ act(() => row('Bug').focus());+ await user.keyboard('f');+ expect(row('Feature')).toHaveFocus();+ act(() => field().focus());+ await user.keyboard('{Escape}');+ await waitFor(() =>+ expect(trigger()).toHaveAttribute('aria-expanded', 'false'),+ );+ });+});diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex 11bbaee7c9..edfdbcaac0 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -57,6 +57,8 @@ import {MENU_ITEM_SELECTOR,MENU_BOUNDARY_SELECTOR,activateMenuItem,+ hostedControlOf,+ isTextEntry,} from './menuItemRoles';import {DropdownMenuContext,@@ -885,6 +887,9 @@ function DropdownMenuPopover({// a picker's list clamps instead.wrap: true,hasPaging: true,+ // Arrows, Home and End leave a text field the menu hosts only at its+ // caret's edge.+ hasCaretGuard: true,onEscape: closeMenu,});@@ -966,7 +971,14 @@ function DropdownMenuPopover({if (!ownsEvent(e)) {return;}+ // A key pressed in a control the menu hosts beside its rows (a filter+ // field, a create button) is that control's: it types, or presses the+ // control. Tab and Escape still close the menu.+ const hosted = hostedControlOf(e.target, listRef.current);if (e.key === 'Enter' || e.key === ' ') {+ if (hosted != null) {+ return;+ }e.preventDefault();// The key that opened the menu, held down, auto-repeats into the menu// once focus has moved there; a repeat is never an activation.@@ -993,14 +1005,15 @@ function DropdownMenuPopover({closeMenu();return;}- // Type-to-focus next; if it consumed a printable key, stop here.- if (typeahead.onKeyDown(e)) {+ // Type-to-focus next; if it consumed a printable key, stop here. Text+ // typed into a hosted field is the field's.+ if (!(hosted != null && isTextEntry(hosted)) && typeahead.onKeyDown(e)) {e.preventDefault();return;}listNavKeyDown(e);},- [listNavKeyDown, closeMenu, typeahead, ownsEvent],+ [listNavKeyDown, closeMenu, typeahead, ownsEvent, listRef],);const openAndFocus = useCallback(diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsxindex f4e4481ce8..3647b8c0d7 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx@@ -195,6 +195,44 @@ describe('DropdownMenuSubMenu', () => {expect(trigger).toHaveFocus();});+ it('a field the flyout hosts keeps what is typed and its Left key', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuSubMenu label="Move to">+ <input aria-label="Folder name" />+ <DropdownMenuItem label="Folder A" onClick={() => {}} />+ </DropdownMenuSubMenu>+ </DropdownMenu>,+ );+ await user.click(screen.getByRole('button', {name: /Actions/}));+ const trigger = screen.getByRole('menuitem', {+ name: /Move to/,+ hidden: true,+ });+ await waitFor(() => {+ expect(+ screen.getByRole('menu', {name: 'Actions', hidden: true}),+ ).toHaveFocus();+ });+ trigger.focus();+ await user.keyboard('{ArrowRight}');+ await waitFor(() => {+ expect(+ screen.getByRole('menuitem', {name: 'Folder A', hidden: true}),+ ).toHaveFocus();+ });+ const field = screen.getByRole('textbox', {+ name: 'Folder name',+ hidden: true,+ });+ act(() => field.focus());+ await user.keyboard('fa{ArrowLeft}');+ expect(field).toHaveValue('fa');+ expect(field).toHaveFocus();+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ });+it('mirrors its indicator and keyboard directions under RTL', async () => {const user = userEvent.setup();const {className: mirrorClassName} = stylex.props(rtlStyles.mirror);diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsxindex b024341c84..96eb51610c 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx@@ -90,6 +90,8 @@ import {MENU_ITEM_SELECTOR,MENU_BOUNDARY_SELECTOR,activateMenuItem,+ hostedControlOf,+ isTextEntry,} from './menuItemRoles';import {DropdownMenuContext,@@ -410,6 +412,9 @@ export function DropdownMenuSubMenu(// Menus wrap.wrap: true,hasPaging: true,+ // Arrows, Home and End leave a text field this level hosts only at its+ // caret's edge.+ hasCaretGuard: true,onEscape: () => close({focusTrigger: true}),});// A drilled-in list scrolls with the root menu, not on its own.@@ -630,7 +635,14 @@ export function DropdownMenuSubMenu(close({focusTrigger: true});return;}+ // A key pressed in a control this level hosts beside its rows is that+ // control's (see DropdownMenu); a text field also keeps Left and Right.+ const hosted = hostedControlOf(e.target, menuRef.current);+ const isHostedText = hosted != null && isTextEntry(hosted);if (e.key === 'Enter' || e.key === ' ') {+ if (hosted != null) {+ return;+ }e.preventDefault();// A held key's auto-repeat never activates.if (e.repeat) {@@ -652,12 +664,12 @@ export function DropdownMenuSubMenu(? window.getComputedStyle(menuRef.current).direction === 'rtl': false;const closeKey = isRtl ? 'ArrowRight' : 'ArrowLeft';- if (e.key === closeKey) {+ if (e.key === closeKey && !isHostedText) {e.preventDefault();close({focusTrigger: true});return;}- if (typeahead.onKeyDown(e)) {+ if (!isHostedText && typeahead.onKeyDown(e)) {e.preventDefault();return;}diff --git a/packages/core/src/DropdownMenu/__tests__/MenuHostedField.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/MenuHostedField.a11y.chromium.spec.tsnew file mode 100644index 0000000000..398880fbb1--- /dev/null+++ b/packages/core/src/DropdownMenu/__tests__/MenuHostedField.a11y.chromium.spec.ts@@ -0,0 +1,73 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file MenuHostedField.a11y.chromium.spec.ts+ * @input The `Core/DropdownMenu` HostedField story in a built Storybook and+ * real keyboard and mouse input.+ * @output Real-engine proof that a field and a button a menu hosts beside its+ * rows keep their own keys while the rows keep the menu's.+ * @position Run with `pnpm test:a11y-contract`.+ */++import {expect, test, 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();+});++const STORY = 'core-dropdownmenu--hosted-field';+const TRIGGER = '#storybook-root [aria-haspopup="menu"]';++async function openMenu(page: Page) {+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);+ await page.locator(TRIGGER).click();+ const menu = page.getByRole('menu');+ await expect(menu).toBeVisible();+ // A pointer open focuses the menu itself; let that land first.+ await expect(menu).toBeFocused();+}++test('typing into a hosted field stays in the field', async ({page}) => {+ await openMenu(page);+ const field = page.getByRole('textbox', {name: 'Filter labels'});+ await field.click();+ await expect(field).toBeFocused();+ await page.keyboard.type('bu g');+ await expect(field).toHaveValue('bu g');+ await expect(field).toBeFocused();+ // Mid-text, the caret keys are the field's.+ await page.keyboard.press('Home');+ await expect(field).toBeFocused();+ await expect+ .poll(async () =>+ field.evaluate(el => (el as HTMLInputElement).selectionStart),+ )+ .toBe(0);+ // From the end of the text, ArrowDown moves on to the first row.+ await page.keyboard.press('End');+ await page.keyboard.press('ArrowDown');+ await expect(page.getByRole('menuitem', {name: 'Bug'})).toBeFocused();+});++test('Enter and Space press a hosted button', async ({page}) => {+ await openMenu(page);+ await page.getByRole('button', {name: 'Create label'}).focus();+ await page.keyboard.press('Enter');+ await expect(page.getByTestId('created')).toHaveText('1');+ await page.keyboard.press(' ');+ await expect(page.getByTestId('created')).toHaveText('2');+ await expect(page.getByRole('menu')).toBeVisible();+});diff --git a/packages/core/src/DropdownMenu/menuItemRoles.ts b/packages/core/src/DropdownMenu/menuItemRoles.tsindex 570da61f1f..bbe5177740 100644--- a/packages/core/src/DropdownMenu/menuItemRoles.ts+++ b/packages/core/src/DropdownMenu/menuItemRoles.ts@@ -2,7 +2,8 @@/*** @file menuItemRoles.ts- * @output Shared menu-item role set + focus selector + keyboard activation.+ * @output Shared menu-item role set + focus selector + keyboard activation,+ * and the hosted-control test that leaves a control's own keys to it.* @position Internal; used by DropdownMenu and ContextMenu so their* roving-focus, typeahead, and Enter/Space activation stay in sync.*@@ -30,6 +31,60 @@ export const MENU_ITEM_SELECTOR: string = [...MENU_ITEM_ROLES]*/export const MENU_BOUNDARY_SELECTOR = '[role="menu"]';+// Controls a menu may host beside its rows: a filter field, a create button.+const HOSTED_CONTROL_SELECTOR =+ 'input, textarea, select, button, a[href], [contenteditable]:not([contenteditable="false"]), [role="textbox"]';+// A row of any state: a control inside a disabled row still belongs to it.+const ANY_ROW_SELECTOR = [...MENU_ITEM_ROLES]+ .map(role => `[role="${role}"]`)+ .join(',');+// The input types that take typed text, as in useListFocus's caret guard.+const TEXT_ENTRY_INPUT_TYPES: ReadonlySet<string> = new Set([+ 'text',+ 'search',+ 'url',+ 'tel',+ 'email',+ 'password',+ 'number',+]);++/**+ * The control a menu hosts beside its rows that `target` sits in (a filter+ * field, a create button), or null. A key pressed there is the control's: the+ * menu's Enter/Space activation and its typeahead are for rows. A control+ * inside a row belongs to the row.+ */+export function hostedControlOf(+ target: EventTarget | null,+ menu: Element | null,+): HTMLElement | null {+ if (!(target instanceof HTMLElement) || menu == null || target === menu) {+ return null;+ }+ const control = target.closest<HTMLElement>(HOSTED_CONTROL_SELECTOR);+ if (control == null || !menu.contains(control)) {+ return null;+ }+ const row = control.closest(ANY_ROW_SELECTOR);+ return row != null && menu.contains(row) ? null : control;+}++/** Whether a hosted control takes typed text, so printable keys are its own. */+export function isTextEntry(control: HTMLElement): boolean {+ if (+ control.tagName === 'TEXTAREA' ||+ control.getAttribute('role') === 'textbox' ||+ control.matches('[contenteditable]:not([contenteditable="false"])')+ ) {+ return true;+ }+ return (+ control.tagName === 'INPUT' &&+ TEXT_ENTRY_INPUT_TYPES.has((control as HTMLInputElement).type)+ );+}+/*** Whether a click carries a modifier or a non-primary button: on a row that* is a link the browser gives it a meaning of its own (a new tab, a