Skip to content

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

TypeScript

feat(DropdownMenu): a trigger render prop — hang a menu off any control (#6836)

Christopher Chedeaud8370a1ee401
diff --git a/.changeset/menu-custom-trigger.md b/.changeset/menu-custom-trigger.md
new file mode 100644
index 0000000000..9ef702701e
--- /dev/null
+++ b/.changeset/menu-custom-trigger.md
@@ -0,0 +1,13 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] DropdownMenu takes a `trigger` render prop: hang a menu off any control.
+
+`trigger` renders the control the menu opens from — an IconButton, a chip, an
+avatar, a list row — and hands it `DropdownMenuTriggerProps` to spread: the
+press model, the keyboard opens, the toggle click and the ARIA wiring. The menu
+is named by that control through `aria-labelledby`. `button` and `trigger` are
+mutually exclusive (a dev warning).
+
+@vjeux
diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsx
index 99d8d3182c..4865608ae3 100644
--- a/apps/storybook/stories/DropdownMenu.stories.tsx
+++ b/apps/storybook/stories/DropdownMenu.stories.tsx
@@ -3,6 +3,7 @@
import type {Meta, StoryObj} from '@storybook/react';
import * as stylex from '@stylexjs/stylex';
import {Badge} from '@astryxdesign/core/Badge';
+import {IconButton} from '@astryxdesign/core/IconButton';
import {useState} from 'react';
import {
DropdownMenu,
@@ -1271,23 +1272,37 @@ export const SubmenuViewportFit: Story = {
},
};
-export const TallMenu: Story = {
- name: 'menuMaxHeight',
+export const CustomTrigger: Story = {
+ name: 'Custom trigger (any control)',
render: () => (
<DropdownMenu
- button={{label: 'Eleven rows, no scroll'}}
- menuMaxHeight={560}
- items={Array.from({length: 11}, (_, i) => ({
- label: `Row ${i + 1}`,
- onClick: () => {},
- }))}
- />
+ renderTrigger={props => (
+ <IconButton
+ icon={<EllipsisHorizontalIcon />}
+ label="More actions"
+ variant="ghost"
+ {...props}
+ />
+ )}>
+ <DropdownMenuItem icon={PencilIcon} label="Rename" onClick={() => {}} />
+ <DropdownMenuItem
+ icon={DocumentDuplicateIcon}
+ label="Duplicate"
+ onClick={() => {}}
+ />
+ <DropdownMenuItem
+ icon={TrashIcon}
+ label="Delete"
+ variant="destructive"
+ onClick={() => {}}
+ />
+ </DropdownMenu>
),
parameters: {
docs: {
description: {
story:
- 'A menu is capped at 300px and scrolls past it. `menuMaxHeight` lifts the cap for a menu that must show all of its rows; the viewport still bounds it.',
+ 'Any control can open a menu: `trigger` renders it and receives the props to spread — the press model (a mouse opens on press-down, a held finger opens with the finger down), the keyboard opens, the toggle click, and the ARIA wiring. The menu is named by that control through `aria-labelledby`.',
},
},
},
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
index 24eb54bff6..6cdfaf1180 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
@@ -180,9 +180,16 @@ export const docs = {
name: 'button',
type: 'DropdownMenuButtonProps',
description:
- 'Props for the trigger button (Button props except onClick).',
+ 'Props for the trigger button (Button props except onClick). Mutually exclusive with `trigger`.',
default: "{ label: 'Menu' }",
},
+ {
+ name: 'renderTrigger',
+ type: '(props: DropdownMenuTriggerProps) => ReactNode',
+ description:
+ 'Render the control the menu hangs off — an IconButton, a chip, an avatar, a list row — instead of the built-in Button. Spread the given props onto it: they carry the press model (a mouse opens on press-down, a held finger opens with the finger down), the keyboard opens, the toggle click, and `aria-haspopup`/`aria-expanded`/`aria-controls`/`id`; the menu is then named by that control through `aria-labelledby`. Mutually exclusive with `button`.',
+ },
+
{
name: 'items',
type: 'DropdownMenuOption[]',
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
index 351b381a40..35150a8af3 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md
+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
@@ -9,7 +9,7 @@ superseded_by: null
approved_by: null
approved_at: null
owners: [cixzhang]
-review_triggers: [theming, public-api, layout]
+review_triggers: [accessibility, behavior, layout, public-api, theming]
verified_by:
[
packages/core/src/DropdownMenu/DropdownMenu.test.tsx,
@@ -83,25 +83,28 @@ Consumer migration instructions belong in consumer docs and release notes.
## Public concepts
Consumer props, item shapes, subcomponents, and presentation policy remain
-documented in `DropdownMenu.doc.mjs` and the subcomponent docs. One
-component-local concept is added by DEC-3; it keeps its released default.
+documented in `DropdownMenu.doc.mjs` and the subcomponent docs. Two component-local concepts are added, by DEC-2 and DEC-3; each keeps its
+released default.
-| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
-| --------------- | ----------------------------------- | ------------------------------------------------------------------------------------ | ----------------------------------------- | ------- | ------------------------ | --------- | --------------------------- |
-| Menu height cap | `menuMaxHeight`: a number of pixels | Lifts the 300px cap for a menu that must fit its rows; the viewport still bounds it. | Pointer presentation | `300px` | `component:DropdownMenu` | stable | Ignored by the touch sheet. |
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| --------------- | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -------- | ------------------------ | --------- | --------------------------------------------------- |
+| Menu height cap | `menuMaxHeight`: a number of pixels | Lifts the 300px cap for a menu that must fit its rows; the viewport still bounds it. | Pointer presentation | `300px` | `component:DropdownMenu` | stable | Ignored by the touch sheet. |
+| Trigger source | `button` (Button props) or `renderTrigger` (render prop) | Which control the menu hangs off. `trigger` receives `DropdownMenuTriggerProps` — the press model, keyboard opens, toggle click and ARIA wiring — and names the menu. | Both presentations | `button` | `component:DropdownMenu` | stable | Both given: `trigger` wins and a dev warning fires. |
## 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 |
-| 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 |
-| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
-| FR8 | The Trigger button opens the pointer menu on a mouse press-down and on a finger held for the long-press delay, with the module's settle rule on the opening release; pressing the trigger of an open menu closes it without reopening in the same gesture; a tap and the keyboard open as before (`module:DropdownMenu/useMenuPress` proposed FR8, FR9). | Proposed `module:DropdownMenu/useMenuPress/DEC-4`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom, pending owner review |
+| 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 |
+| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
+| FR8 | The Trigger button opens the pointer menu on a mouse press-down and on a finger held for the long-press delay, with the module's settle rule on the opening release; pressing the trigger of an open menu closes it without reopening in the same gesture; a tap and the keyboard open as before (`module:DropdownMenu/useMenuPress` proposed FR8, FR9). | Proposed `module:DropdownMenu/useMenuPress/DEC-4`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom, pending owner review |
+| Trigger source | `button` (Button props) or `renderTrigger` (render prop) | Which control the menu hangs off. `trigger` receives `DropdownMenuTriggerProps` — the press model, keyboard opens, toggle click and ARIA wiring — and names the menu. | Both presentations | `button` | `component:DropdownMenu` | stable | Both given: `trigger` wins and a dev warning fires. |
+| FR9 | With `renderTrigger`, the rendered control MUST carry `aria-haspopup`, `aria-expanded`, `aria-controls` and the `id` the menu's `aria-labelledby` points at, and MUST receive the same press-model, keyboard-open and toggle-click handlers as the Button path; the menu is named by that control. `button` and `trigger` are mutually exclusive: both given, `trigger` wins and a dev warning fires, in both presentations. | `component:DropdownMenu/DEC-2` | Proposed; verified in jsdom; owner to confirm DEC-2 |
### Allowed variation
@@ -116,13 +119,14 @@ component-local concept is added by DEC-3; it keeps its released default.
### Representative states
-| State | Required invariant | Allowed variation |
-| --------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
-| Anchored root menu | Trigger button and Pointer menu surface render with pointer-owned rows. | Width, placement, alignment, and optional item content vary. |
-| Anchored nested flyout | Pointer action row opens another Pointer menu surface and may show the submenu indicator icon. | Loading may replace the indicator with the current Spinner. |
-| Bottom-sheet root actions | Trigger button opens Touch sheet frame, Touch menu surface, heading, action list, and action rows. | Icons, sections, dividers, and action descriptions may vary. |
-| Bottom-sheet nested actions | The same frame and list owners remain while heading and rows change to the selected action level. | Back control and drill-in indicator follow current navigation. |
-| Selectable pointer action | Pointer action row may contain shared checkbox or radio chrome. | Checked and disabled state follow the current item contracts. |
+| State | Required invariant | Allowed variation |
+| --------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
+| Anchored root menu | Trigger button and Pointer menu surface render with pointer-owned rows. | Width, placement, alignment, and optional item content vary. |
+| Anchored nested flyout | Pointer action row opens another Pointer menu surface and may show the submenu indicator icon. | Loading may replace the indicator with the current Spinner. |
+| Bottom-sheet root actions | Trigger button opens Touch sheet frame, Touch menu surface, heading, action list, and action rows. | Icons, sections, dividers, and action descriptions may vary. |
+| Bottom-sheet nested actions | The same frame and list owners remain while heading and rows change to the selected action level. | Back control and drill-in indicator follow current navigation. |
+| Selectable pointer action | Pointer action row may contain shared checkbox or radio chrome. | Checked and disabled state follow the current item contracts. |
+| Custom-trigger menu | The caller's control carries the trigger ARIA and names the menu; the Pointer menu surface is unchanged. | Any focusable control: icon button, chip, avatar, list row. |
### Transformation and precedence order
@@ -142,6 +146,11 @@ pointer is held, the highlight is DOM focus per
`architecture:interaction-modality` INV1 through the shared focus-return
visibility helper.
+- **AR1 — A custom trigger still names the menu.** With `trigger`, the menu
+ carries `aria-labelledby` pointing at the control's `id` (the Button path
+ keeps `aria-label`), and the control carries `aria-haspopup="menu"`,
+ `aria-expanded` and `aria-controls`.
+
## Design relationships
| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
@@ -250,6 +259,7 @@ than adding a DropdownMenu-owned heading target.
| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
| 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` |
| FR8 | `DropdownMenu.test.tsx` press model suite (trigger cases) | Press-open + drag-release, unsettled opening release, trigger toggle, held touch, tap | A menu that does not open on a mouse press, an unsettled release that acts, or a trigger that reopens in the same gesture fails. | `audit:DropdownMenu/behavior` |
+| FR9 | `DropdownMenu.test.tsx` custom trigger suite | Icon button, chip, list row; open, toggle, keyboard open, name | A rendered control missing `aria-haspopup`, `aria-expanded` or `aria-controls`, an unnamed menu, or a lost keyboard open, fails. | `audit:DropdownMenu/anatomy` |
## Decision log
@@ -285,6 +295,37 @@ The value is a number of pixels. Rejected: an arbitrary CSS length (`50vh`,
`spec:AST-002` does not admit, and which lets a caller write a cap the
viewport term cannot reason about.
+### DEC-3 — Any control can open a menu
+
+**Reference:** `component:DropdownMenu/DEC-3`
+
+**Decider:** `cixzhang`, 2026-10-02
+
+`renderTrigger` is a render prop handing the caller `DropdownMenuTriggerProps`
+to spread, so the press model, the keyboard opens and the ARIA wiring ride the
+same code path as the built-in Button, and the menu is named by the control
+through `aria-labelledby`. `button` and `renderTrigger` are mutually exclusive
+(a dev warning); the Button path is unchanged.
+
+The prop is named for `spec:AST-055` DEC-5 and DEC-6: `render<X>` is the
+prefix for every render prop in the system, and a bare `trigger` is already
+public with a different shape on `Collapsible`, where it is a `ReactNode`
+slot, so one word would otherwise mean two things.
+
+Rejected: a content slot taking a rendered element. A slot cannot hand the
+caller the props the control must carry, so the component would have to
+reach into the element to attach them.
+
+The open state reaches the caller's control as `aria-expanded` on the spread
+props, and the prop's documentation shows styling from that attribute. A
+pressed look keyed to `:active` is not a substitute: `:active` does not
+behave the same under a coarse pointer, which is why menu rows drop
+coarse-pointer `:active` paint entirely.
+
+Rejected: an `as` prop on the Button — an icon button, a chip, an avatar and a
+list row are not Button variants; a slot component — hides which props must
+reach the control.
+
## Open questions
None.
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 8332519925..cb1d5dc87a 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -2451,6 +2451,134 @@ describe('DropdownMenu trigger handler composition', () => {
});
});
+describe('DropdownMenu custom trigger', () => {
+ it('a custom trigger opens, toggles and names the menu', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ renderTrigger={props => (
+ <span {...props} role="button" tabIndex={0}>
+ Ada Lovelace
+ </span>
+ )}>
+ <DropdownMenuItem label="Profile" onClick={() => {}} />
+ </DropdownMenu>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Ada Lovelace'});
+ expect(trigger.tagName).toBe('SPAN');
+ expect(trigger).toHaveAttribute('aria-haspopup', 'menu');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ const menu = screen.getByRole('menu', {hidden: true});
+ expect(trigger).toHaveAttribute('aria-controls', menu.id);
+ // The menu is named by the control it hangs off.
+ expect(menu).toHaveAttribute('aria-labelledby', trigger.id);
+ expect(menu).not.toHaveAttribute('aria-label');
+ expect(screen.getByRole('menu', {name: 'Ada Lovelace', hidden: true})).toBe(
+ menu,
+ );
+
+ await user.click(trigger);
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'true'),
+ );
+ await user.click(trigger);
+ await waitFor(() =>
+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),
+ );
+ });
+
+ it('a custom trigger opens from the keyboard and lands on the first row', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ More
+ </button>
+ )}>
+ <DropdownMenuItem label="Profile" onClick={() => {}} />
+ </DropdownMenu>,
+ );
+ const trigger = screen.getByRole('button', {name: 'More'});
+ trigger.focus();
+ await user.keyboard('{ArrowDown}');
+ await waitFor(() =>
+ expect(
+ screen.getByRole('menuitem', {name: 'Profile', hidden: true}),
+ ).toHaveFocus(),
+ );
+ });
+
+ it('a mouse press on a custom trigger opens the menu', () => {
+ render(
+ <DropdownMenu
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ More
+ </button>
+ )}>
+ <DropdownMenuItem label="Profile" onClick={() => {}} />
+ </DropdownMenu>,
+ );
+ const trigger = screen.getByRole('button', {name: 'More'});
+ fireEvent.pointerDown(trigger, {
+ pointerType: 'mouse',
+ pointerId: 1,
+ button: 0,
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('warns when both button and trigger are given in the bottom-sheet presentation too', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ presentation="bottom-sheet"
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ More
+ </button>
+ )}
+ items={[{label: 'Profile'}]}
+ />,
+ );
+ expect(screen.getByRole('button', {name: 'More'})).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: /Actions/}),
+ ).not.toBeInTheDocument();
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('mutually exclusive'),
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it('warns when both button and trigger are given', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ renderTrigger={props => (
+ <button type="button" {...props}>
+ More
+ </button>
+ )}>
+ <DropdownMenuItem label="Profile" onClick={() => {}} />
+ </DropdownMenu>,
+ );
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('mutually exclusive'),
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
+
describe('DropdownMenu menuMaxHeight', () => {
it('a menu taller than the cap keeps the height it is given', () => {
render(
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 53b1615f76..063fbc231a 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -16,6 +16,9 @@
*
* Both modes use useListFocus for DOM-based keyboard navigation.
*
+ * The trigger is the design system's Button (`button`) or any control the
+ * caller renders (`trigger`).
+ *
* Initial focus on open follows the input modality: a keyboard open
* (Enter / Space / ArrowDown on the trigger) focuses the first enabled item
* (APG menu-button); a pointer open focuses the menu container itself so no
@@ -62,6 +65,7 @@ import type {MenuPressPointerType} from '../hooks/menuPressGesture';
import {useTypeahead} from '../hooks/useTypeahead';
import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';
import {useMenuOverflow} from './useMenuOverflow';
+import {useDevWarning} from '../hooks/useDevWarning';
import {resolveMenuWidth} from './menuWidth';
import {
useAdaptivePresentation,
@@ -315,8 +319,58 @@ export type DropdownMenuButtonProps = Omit<ButtonProps, 'onClick'>;
export type DropdownMenuPresentation = AdaptivePresentation;
+/**
+ * The props a custom `trigger` spreads onto the control that opens the menu.
+ * They carry the press model — a mouse opens on press-down, a held finger
+ * opens with the finger down — the keyboard opens (Enter, Space, ArrowDown,
+ * ArrowUp), the toggle click, and the ARIA wiring that names the menu after
+ * the control. Spread them all; add your own handlers beside them.
+ */
+export interface DropdownMenuTriggerProps {
+ /** Attaches the control as the menu's anchor and focus-return target. */
+ ref: (element: HTMLElement | null) => void;
+ /** The menu points at this id with `aria-labelledby`. */
+ id: string;
+ onClick: (event: React.MouseEvent<HTMLElement>) => void;
+ onClickCapture: (event: React.MouseEvent<HTMLElement>) => void;
+ onPointerDown: (event: React.PointerEvent<HTMLElement>) => void;
+ onContextMenu: (event: React.MouseEvent<HTMLElement>) => void;
+ onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => void;
+ onFocus: (event: React.FocusEvent<HTMLElement>) => void;
+ 'aria-haspopup': 'menu' | 'dialog';
+ 'aria-expanded': boolean;
+ 'aria-controls': string;
+}
+
interface DropdownMenuBaseProps extends BaseProps {
+ /**
+ * The design system's own button as the trigger. Mutually exclusive with
+ * `renderTrigger`.
+ */
button?: DropdownMenuButtonProps;
+ /**
+ * Render the control the menu hangs off — an icon button, a chip, an
+ * avatar, a list row. Spread the given props onto it; the menu is then
+ * named by that control. Mutually exclusive with `button`.
+ *
+ * Hover and pressed paint stay yours. The open state reaches your control
+ * as `aria-expanded` on the given props, so style it from the rendered
+ * attribute. A pressed look keyed to `:active` is not a substitute:
+ * `:active` does not behave the same under a coarse pointer, which is why
+ * menu rows drop coarse-pointer `:active` paint entirely.
+ *
+ * @example
+ * ```
+ * <DropdownMenu renderTrigger={props => <IconButton icon="more" label="More" {...props} />}>
+ * ```
+ *
+ * @example
+ * ```
+ * // Styling the open state from the rendered attribute:
+ * // .my-trigger[aria-expanded='true'] { background: var(--color-overlay-pressed); }
+ * ```
+ */
+ renderTrigger?: (props: DropdownMenuTriggerProps) => ReactNode;
isMenuOpen?: boolean;
onOpenChange?: (isOpen: boolean) => void;
/**
@@ -432,6 +486,7 @@ function holdInvokerThroughPress(
function DropdownMenuBottomSheet({
button: buttonFromProps,
+ renderTrigger,
isMenuOpen: controlledIsOpen,
onOpenChange,
onClick,
@@ -451,7 +506,9 @@ function DropdownMenuBottomSheet({
const t = useTranslator();
const button = buttonFromProps ?? {label: t(DEFAULT_BUTTON_I18N_KEY)};
const backLabel = t('@astryx.dropdownMenu.back');
- const buttonRef = useRef<HTMLButtonElement>(null);
+ const buttonRef = useRef<HTMLElement>(null);
+ const triggerId = useId();
+ const sheetId = useId();
const actionListRef = useRef<HTMLDivElement>(null);
const openModalityRef = useRef<'keyboard' | 'pointer'>('pointer');
const {
@@ -542,44 +599,70 @@ function DropdownMenuBottomSheet({
return () => cancelAnimationFrame(frame);
}, [isOpen, submenuPath.length]);
+ const handleSheetTriggerPointerDown = () => {
+ openModalityRef.current = 'pointer';
+ };
+ const handleSheetTriggerKeyDown = (event: React.KeyboardEvent) => {
+ if (
+ event.key === 'ArrowDown' ||
+ event.key === 'Enter' ||
+ event.key === ' '
+ ) {
+ openModalityRef.current = 'keyboard';
+ }
+ };
+ const handleSheetTriggerClick = () => {
+ onClick?.();
+ setOpen(!isOpen);
+ };
+
return (
<>
- <Button
- {...button}
- ref={buttonRef}
- xstyle={[
- isOpen && styles.triggerOpen,
- button.xstyle,
- isFocusRingSuppressed && focusOutlineStyles.suppressed,
- ]}
- tooltip={isOpen ? undefined : button.tooltip}
- endContent={resolvedEndContent}
- onPointerDown={event => {
- button.onPointerDown?.(event);
- openModalityRef.current = 'pointer';
- }}
- onKeyDown={event => {
- button.onKeyDown?.(event);
- if (
- event.key === 'ArrowDown' ||
- event.key === 'Enter' ||
- event.key === ' '
- ) {
- openModalityRef.current = 'keyboard';
- }
- }}
- onFocus={event => {
- button.onFocus?.(event);
- onFocusReturnTargetFocus();
- }}
- onClick={() => {
- onClick?.();
- setOpen(!isOpen);
- }}
- aria-haspopup="dialog"
- aria-expanded={isOpen}
- data-testid={testId}
- />
+ {renderTrigger != null ? (
+ renderTrigger({
+ ref: el => {
+ buttonRef.current = el;
+ },
+ id: triggerId,
+ onClick: handleSheetTriggerClick,
+ onClickCapture: () => {},
+ onPointerDown: handleSheetTriggerPointerDown,
+ onContextMenu: () => {},
+ onKeyDown: handleSheetTriggerKeyDown,
+ onFocus: onFocusReturnTargetFocus,
+ 'aria-haspopup': 'dialog',
+ 'aria-expanded': isOpen,
+ 'aria-controls': sheetId,
+ })
+ ) : (
+ <Button
+ {...button}
+ ref={buttonRef as React.Ref<HTMLButtonElement>}
+ xstyle={[
+ isOpen && styles.triggerOpen,
+ button.xstyle,
+ isFocusRingSuppressed && focusOutlineStyles.suppressed,
+ ]}
+ tooltip={isOpen ? undefined : button.tooltip}
+ endContent={resolvedEndContent}
+ onPointerDown={event => {
+ button.onPointerDown?.(event);
+ handleSheetTriggerPointerDown();
+ }}
+ onKeyDown={event => {
+ button.onKeyDown?.(event);
+ handleSheetTriggerKeyDown(event);
+ }}
+ onFocus={event => {
+ button.onFocus?.(event);
+ onFocusReturnTargetFocus();
+ }}
+ onClick={handleSheetTriggerClick}
+ aria-haspopup="dialog"
+ aria-expanded={isOpen}
+ data-testid={testId}
+ />
+ )}
<MenuBottomSheet
isOpen={isOpen}
@@ -588,6 +671,7 @@ function DropdownMenuBottomSheet({
label={sheetLabel}>
<div
ref={actionListRef}
+ id={sheetId}
{...rest}
{...mergeProps(
themeProps('dropdown-menu', {presentation: 'bottom-sheet'}),
@@ -636,6 +720,7 @@ function DropdownMenuBottomSheet({
function DropdownMenuPopover({
button: buttonFromProps,
+ renderTrigger,
isMenuOpen: controlledIsOpen,
onOpenChange,
menuWidth,
@@ -666,8 +751,9 @@ function DropdownMenuPopover({
} = props as Record<string, unknown>;
const menuId = useId();
+ const triggerId = useId();
const menuSize = button.size ?? 'md';
- const buttonRef = useRef<HTMLButtonElement>(null);
+ const buttonRef = useRef<HTMLElement>(null);
// Open state
const [internalIsOpen, setInternalIsOpen] = useState(false);
@@ -959,7 +1045,7 @@ function DropdownMenuPopover({
cancelMenuPressRef.current = menuPress.cancel;
const handleButtonClick = useCallback(
- (e: React.MouseEvent<HTMLButtonElement>) => {
+ (e: React.MouseEvent<HTMLElement>) => {
// The press already opened or closed the menu; its click is spent.
if (menuPress.isTriggerClickFromPress()) {
return;
@@ -994,7 +1080,7 @@ function DropdownMenuPopover({
);
const handleTriggerClickCapture = useCallback(
- (e: React.MouseEvent<HTMLButtonElement>) => {
+ (e: React.MouseEvent<HTMLElement>) => {
const control = e.currentTarget;
if (control.hasAttribute('popovertarget')) {
// Still the invoker from a press-open: the browser would toggle the
@@ -1065,54 +1151,76 @@ function DropdownMenuPopover({
props.items !== undefined ? renderDropdownItems(items) : children;
const hasOverflow = useMenuOverflow(listRef, menuContent, popover.isOpen);
+ const triggerProps: DropdownMenuTriggerProps = {
+ ref: el => {
+ buttonRef.current = el;
+ popover.triggerRef(el);
+ },
+ id: triggerId,
+ onClick: handleButtonClick,
+ onClickCapture: handleTriggerClickCapture,
+ 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.
+ onFocus: () => {},
+ 'aria-haspopup': 'menu',
+ 'aria-expanded': isOpen,
+ 'aria-controls': menuId,
+ };
+
return (
<>
- <Button
- {...button}
- ref={el => {
- buttonRef.current = el;
- popover.triggerRef(el);
- const consumerRef = button.ref;
- if (typeof consumerRef === 'function') {
- consumerRef(el);
- } else if (consumerRef) {
- /* eslint-disable react-compiler/react-compiler -- ref callback: forwarding consumer ref object */
- consumerRef.current = el;
- /* eslint-enable react-compiler/react-compiler */
- }
- }}
- xstyle={[
- styles.triggerPressable,
- isOpen && styles.triggerOpen,
- button.xstyle,
- isFocusRingSuppressed && focusOutlineStyles.suppressed,
- ]}
- tooltip={isOpen ? undefined : button.tooltip}
- endContent={resolvedEndContent}
- onClick={handleButtonClick}
- onClickCapture={event => {
- button.onClickCapture?.(event);
- handleTriggerClickCapture(event);
- }}
- onKeyDown={handleButtonKeyDown}
- onPointerDown={event => {
- button.onPointerDown?.(event);
- menuPress.triggerProps.onPointerDown(event);
- }}
- onContextMenu={event => {
- button.onContextMenu?.(event);
- menuPress.triggerProps.onContextMenu(event);
- }}
- onFocus={event => {
- button.onFocus?.(event);
- onFocusReturnTargetFocus();
- }}
- aria-haspopup="menu"
- aria-expanded={isOpen}
- aria-controls={menuId}
- data-testid={testId}
- />
-
+ {renderTrigger != null ? (
+ renderTrigger(triggerProps)
+ ) : (
+ <Button
+ {...button}
+ ref={el => {
+ buttonRef.current = el;
+ popover.triggerRef(el);
+ const consumerRef = button.ref;
+ if (typeof consumerRef === 'function') {
+ consumerRef(el);
+ } else if (consumerRef) {
+ /* eslint-disable react-compiler/react-compiler -- ref callback: forwarding consumer ref object */
+ consumerRef.current = el;
+ /* eslint-enable react-compiler/react-compiler */
+ }
+ }}
+ xstyle={[
+ styles.triggerPressable,
+ isOpen && styles.triggerOpen,
+ button.xstyle,
+ isFocusRingSuppressed && focusOutlineStyles.suppressed,
+ ]}
+ tooltip={isOpen ? undefined : button.tooltip}
+ endContent={resolvedEndContent}
+ onClick={handleButtonClick}
+ onClickCapture={event => {
+ button.onClickCapture?.(event);
+ handleTriggerClickCapture(event);
+ }}
+ onKeyDown={handleButtonKeyDown}
+ onPointerDown={event => {
+ button.onPointerDown?.(event);
+ menuPress.triggerProps.onPointerDown(event);
+ }}
+ onContextMenu={event => {
+ button.onContextMenu?.(event);
+ menuPress.triggerProps.onContextMenu(event);
+ }}
+ onFocus={event => {
+ button.onFocus?.(event);
+ onFocusReturnTargetFocus();
+ }}
+ aria-haspopup="menu"
+ aria-expanded={isOpen}
+ aria-controls={menuId}
+ data-testid={testId}
+ />
+ )}
{popover.render(
<div
{...rest}
@@ -1130,8 +1238,17 @@ function DropdownMenuPopover({
tabIndex={hasOverflow ? 0 : -1}
// Give the menu an accessible name from its trigger's label, so
// screen readers announce e.g. "Actions menu" rather than an unnamed
- // menu (menus-13).
- aria-label={button.label}
+ // menu (menus-13). A custom trigger names it by reference.
+ aria-label={
+ renderTrigger != null
+ ? (rest['aria-label'] as string | undefined)
+ : button.label
+ }
+ aria-labelledby={
+ renderTrigger != null && rest['aria-label'] == null
+ ? triggerId
+ : (rest['aria-labelledby'] as string | undefined)
+ }
onKeyDown={listKeyDown}
{...menuPress.menuProps}
{...mergeProps(
@@ -1184,6 +1301,13 @@ function DropdownMenuPopover({
export function DropdownMenu(props: DropdownMenuProps) {
const {onOpenChange} = props;
+ // Both presentations hang the menu off ONE control.
+ useDevWarning(
+ 'DropdownMenu',
+ '`button` and `trigger` are mutually exclusive: the menu hangs off one ' +
+ 'control. `trigger` wins; drop `button`.',
+ props.button != null && props.renderTrigger != null,
+ );
const requestedPresentation =
'items' in props ? (props.presentation ?? 'popover') : 'popover';
const resolvedPresentation = useAdaptivePresentation(requestedPresentation);
diff --git a/packages/core/src/DropdownMenu/index.ts b/packages/core/src/DropdownMenu/index.ts
index 7cdcdb0c19..21254d9cf6 100644
--- a/packages/core/src/DropdownMenu/index.ts
+++ b/packages/core/src/DropdownMenu/index.ts
@@ -22,6 +22,7 @@ export {
type DropdownMenuProps,
type DropdownMenuPresentation,
type DropdownMenuButtonProps,
+ type DropdownMenuTriggerProps,
type DropdownMenuItemData,
type DropdownMenuDividerData,
type DropdownMenuSection,