Skip to content

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

TypeScript

feat(menu): a menu item can report its own result (hasCloseOnSelect) (#4953)

Cindy Zhangf4607ea27cb8
diff --git a/.changeset/menu-item-activation-fixes.md b/.changeset/menu-item-activation-fixes.md
new file mode 100644
index 0000000000..361a27ccaa
--- /dev/null
+++ b/.changeset/menu-item-activation-fixes.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A DropdownMenu item closes the menu on activation even when it carries no `onClick`, and a data-mode row that changes its own label keeps its identity instead of remounting and dropping focus
+@cixzhang
diff --git a/.changeset/menu-item-close-on-select.md b/.changeset/menu-item-close-on-select.md
new file mode 100644
index 0000000000..952522aaac
--- /dev/null
+++ b/.changeset/menu-item-close-on-select.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] DropdownMenuItem takes `hasCloseOnSelect`, so a plain action can report its result on the item instead of closing the menu
+@cixzhang
diff --git a/.changeset/menu-item-id.md b/.changeset/menu-item-id.md
new file mode 100644
index 0000000000..015b4ab0e0
--- /dev/null
+++ b/.changeset/menu-item-id.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `DropdownMenuItemData` and `DropdownMenuSection` take an optional `id`, the row's stable React key for a menu whose items reorder or filter (also reaching MoreMenu, ContextMenu and Breadcrumbs, which share the type)
+@cixzhang
diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsx
index 7fb423abe8..5d54eea49c 100644
--- a/apps/storybook/stories/DropdownMenu.stories.tsx
+++ b/apps/storybook/stories/DropdownMenu.stories.tsx
@@ -322,6 +322,32 @@ export const WithOnClick: Story = {
},
};
+export const StaysOpenOnSelect: Story = {
+ render: () => {
+ const [copied, setCopied] = useState(false);
+ return (
+ <DropdownMenu
+ button={{label: 'Session'}}
+ items={[
+ {
+ label: copied ? 'Copied' : 'Copy session ID',
+ icon: <DocumentDuplicateIcon style={{width: 16, height: 16}} />,
+ hasCloseOnSelect: false,
+ onClick: () => setCopied(true),
+ },
+ {label: 'Rename'},
+ {label: 'Delete', variant: 'destructive'},
+ ]}
+ onOpenChange={isOpen => {
+ if (!isOpen) {
+ setCopied(false);
+ }
+ }}
+ />
+ );
+ },
+};
+
// Custom item rendering with compound mode
export const CustomItemRender: Story = {
render: () => (
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
index e4f5b3c2be..3c0450e58f 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
@@ -54,7 +54,7 @@ export const docs = {
{
name: 'items',
type: 'DropdownMenuOption[]',
- description: 'Array of menu entries. Each entry is one of: an action item `{label, onClick?, icon?, isDisabled?, variant?}` (variant `"destructive"` renders it in the error color), a divider `{type: "divider"}`, or a section `{type: "section", title?, items: [...action items]}`.',
+ description: 'Array of menu entries. Each entry is one of: an action item `{label, onClick?, icon?, isDisabled?, variant?, hasCloseOnSelect?, id?}` (variant `"destructive"` renders it in the error color; `id` is the row\'s stable React key, needed only when the array reorders or filters), a divider `{type: "divider"}`, or a section `{type: "section", title?, id?, items: [...action items]}`.',
required: true,
},
{
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 531edc8d2e..618f9bd273 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -411,6 +411,169 @@ describe('DropdownMenu items', () => {
expect(handleClick).toHaveBeenCalledTimes(1);
});
+ it('closes the menu after an item is activated', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ items={[{label: 'Edit', onClick: () => {}}]}
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ await user.click(
+ screen.getByRole('menuitem', {name: 'Edit', hidden: true}),
+ );
+ expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled();
+ });
+
+ it('keeps the menu open when the item opts out of closing', async () => {
+ const user = userEvent.setup();
+ const handleClick = vi.fn();
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ items={[
+ {label: 'Copy ID', onClick: handleClick, hasCloseOnSelect: false},
+ ]}
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const item = screen.getByRole('menuitem', {name: 'Copy ID', hidden: true});
+ await user.click(item);
+ expect(handleClick).toHaveBeenCalledTimes(1);
+ expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled();
+
+ // Second activation still works, and focus never left the item.
+ await user.click(item);
+ expect(handleClick).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps the menu open on keyboard activation too', async () => {
+ const user = userEvent.setup();
+ const handleClick = vi.fn();
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ items={[
+ {label: 'Copy ID', onClick: handleClick, hasCloseOnSelect: false},
+ ]}
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const menu = screen.getByRole('menu', {hidden: true});
+ await waitFor(() => expect(menu).toHaveFocus());
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ fireEvent.keyDown(menu, {key: 'Enter'});
+
+ expect(handleClick).toHaveBeenCalledTimes(1);
+ expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled();
+ expect(
+ screen.getByRole('menuitem', {name: 'Copy ID', hidden: true}),
+ ).toHaveFocus();
+ });
+
+ it('closes the menu on activation even when the item carries no handler', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu button={{label: 'Actions'}} items={[{label: 'Edit'}]} />,
+ );
+
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ await user.click(
+ screen.getByRole('menuitem', {name: 'Edit', hidden: true}),
+ );
+ expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled();
+ });
+
+ it('keeps a row mounted when its label changes, so focus survives (data mode keys by position)', async () => {
+ const user = userEvent.setup();
+
+ function CopyMenu() {
+ const [copied, setCopied] = useState(false);
+ return (
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ items={[
+ {
+ label: copied ? 'Copied' : 'Copy ID',
+ hasCloseOnSelect: false,
+ onClick: () => setCopied(true),
+ },
+ {label: 'Rename'},
+ ]}
+ />
+ );
+ }
+
+ render(<CopyMenu />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ const item = screen.getByRole('menuitem', {name: 'Copy ID', hidden: true});
+ item.focus();
+ await user.click(item);
+
+ const renamed = screen.getByRole('menuitem', {
+ name: 'Copied',
+ hidden: true,
+ });
+ expect(renamed).toBe(item);
+ expect(renamed).toHaveFocus();
+ });
+
+ it('follows the item, not the slot, when ids are supplied and the list changes', async () => {
+ const user = userEvent.setup();
+
+ // A menu whose rows are filtered by a control outside it: the focused row
+ // survives at a new index. Position keys cannot express this — the DOM node
+ // at index 0 would be reused for whatever item lands there.
+ function FilterableMenu({hideFirst}: {hideFirst: boolean}) {
+ const items = [
+ {id: 'edit', label: 'Edit'},
+ {id: 'duplicate', label: 'Duplicate'},
+ {id: 'archive', label: 'Archive'},
+ ].filter(item => !hideFirst || item.id !== 'edit');
+ return <DropdownMenu button={{label: 'Actions'}} items={items} />;
+ }
+
+ const {rerender} = render(<FilterableMenu hideFirst={false} />);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+
+ const duplicate = screen.getByRole('menuitem', {
+ name: 'Duplicate',
+ hidden: true,
+ });
+ duplicate.focus();
+
+ rerender(<FilterableMenu hideFirst={true} />);
+
+ // Same node, still focused, even though it moved from index 1 to index 0.
+ expect(
+ screen.getByRole('menuitem', {name: 'Duplicate', hidden: true}),
+ ).toBe(duplicate);
+ expect(duplicate).toHaveFocus();
+ expect(
+ screen.queryByRole('menuitem', {name: 'Edit', hidden: true}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not put id on the rendered row', async () => {
+ const user = userEvent.setup();
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ items={[{id: 'edit', label: 'Edit'}]}
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+
+ // `id` is identity for React, not a DOM attribute the caller is setting.
+ expect(
+ screen.getByRole('menuitem', {name: 'Edit', hidden: true}),
+ ).not.toHaveAttribute('id', 'edit');
+ });
+
it('does not call onClick when disabled', async () => {
const user = userEvent.setup();
const handleClick = vi.fn();
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 49ab5470d4..1b5624bfec 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -106,12 +106,17 @@ const styles = stylex.create({
*/
export interface DropdownMenuItemData extends Pick<
DropdownMenuItemProps,
- 'icon' | 'onClick' | 'isDisabled' | 'variant'
+ 'icon' | 'onClick' | 'isDisabled' | 'variant' | 'hasCloseOnSelect'
> {
/**
- * Primary label text. Narrowed to `string` from the item's `ReactNode`:
- * data mode derives each row's React key from the label.
+ * Stable identity for the row, used as its React key (as on
+ * `TreeListItemData`). Omit it and the row is keyed by position, which is
+ * correct for a fixed menu; set it when `items` can reorder, filter, or grow,
+ * so a row keeps its DOM node — and therefore keyboard focus — as the array
+ * changes around it.
*/
+ id?: string;
+ /** Primary label text. */
label: string;
/**
* Nested submenu entries. When present, this row becomes a submenu (a
@@ -127,6 +132,8 @@ export interface DropdownMenuDivider {
export interface DropdownMenuSection {
type: 'section';
+ /** Stable identity for the group; see {@link DropdownMenuItemData.id}. */
+ id?: string;
title?: string;
items: DropdownMenuItemData[];
}
diff --git a/packages/core/src/DropdownMenu/DropdownMenuItem.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuItem.doc.mjs
index acaa5a9379..b039864a8d 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuItem.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenuItem.doc.mjs
@@ -38,6 +38,13 @@ export const docs = {
description:
'Additional content rendered after the label and description.',
},
+ {
+ name: 'hasCloseOnSelect',
+ type: 'boolean',
+ description:
+ 'Whether activating the item closes the menu. Set false for an action that reports its result on the item itself.',
+ default: 'true',
+ },
{
name: 'variant',
type: "'default' | 'destructive'",
@@ -80,6 +87,12 @@ export const docsZh = {
type: 'ReactNode',
description: '在标签和描述之后渲染的附加内容。',
},
+ {
+ name: 'hasCloseOnSelect',
+ type: 'boolean',
+ description: '激活该项时是否关闭菜单。若操作要在该项上就地反馈结果,请设为 false。',
+ default: 'true',
+ },
{
name: 'variant',
type: "'default' | 'destructive'",
@@ -105,6 +118,8 @@ export const docsDense = {
label: 'primary label text',
description: 'secondary text below label',
endContent: 'additional content after label+description',
+ hasCloseOnSelect:
+ 'false keeps the menu open on activation (in-place result on the item)',
variant:
"'destructive' renders the item in the error color for dangerous actions",
xstyle: 'StyleX styles for root container',
diff --git a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
index 27eb4fc961..8dbf5f6956 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
@@ -100,6 +100,14 @@ export interface DropdownMenuItemProps extends Pick<
isDisabled?: boolean;
/** Additional content to render after the label/description. */
endContent?: ReactNode;
+ /**
+ * Whether activating the item closes the menu. Set `false` for an action
+ * that reports its result on the item itself (a copy row swapping to
+ * "Copied"), matching the checkbox and radio items, which already decide
+ * this for themselves.
+ * @default true
+ */
+ hasCloseOnSelect?: boolean;
/**
* Visual variant. `'destructive'` renders the label, description, and icon in
* the error color for dangerous actions (e.g. Delete). @default 'default'
@@ -128,6 +136,7 @@ export function DropdownMenuItem({
onClick,
isDisabled = false,
endContent,
+ hasCloseOnSelect = true,
variant = 'default',
xstyle,
className,
@@ -137,12 +146,14 @@ export function DropdownMenuItem({
const menuSize = ctx?.menuSize ?? 'md';
const handleClick = useCallback(() => {
- if (isDisabled || !onClick) {
+ if (isDisabled) {
return;
}
- onClick();
- ctx?.closeMenu();
- }, [isDisabled, onClick, ctx]);
+ onClick?.();
+ if (hasCloseOnSelect) {
+ ctx?.closeMenu();
+ }
+ }, [isDisabled, onClick, hasCloseOnSelect, ctx]);
const handlePointerMove = useCallback(
(e: PointerEvent<HTMLElement>) => focusMenuItemOnHover(e, isDisabled),
diff --git a/packages/core/src/DropdownMenu/renderDropdownItems.tsx b/packages/core/src/DropdownMenu/renderDropdownItems.tsx
index 68dec4464b..14426e1efa 100644
--- a/packages/core/src/DropdownMenu/renderDropdownItems.tsx
+++ b/packages/core/src/DropdownMenu/renderDropdownItems.tsx
@@ -39,26 +39,36 @@ const styles = stylex.create({
},
});
-function getItemKey(item: DropdownMenuItemData): string {
- return `item-${item.label}`;
+function getItemKey(item: DropdownMenuItemData, index: number): string {
+ return `item-${item.id ?? index}`;
}
function getSectionKey(section: DropdownMenuSection, index: number): string {
- return `section-${section.title ?? index}`;
+ return `section-${section.id ?? index}`;
}
/**
* Renders one leaf row as a `DropdownMenuItem`.
*
- * `items` is stripped because it selects the submenu shape rather than being an
- * item prop; every other field of `DropdownMenuItemData` is a
+ * Keyed by `item.id` when the caller supplies one, else by position. NOT by
+ * label: an item that reports its own result (a copy row swapping to "Copied")
+ * would change key mid-interaction, remounting the row and dropping keyboard
+ * focus. Position is the safe default because a menu's rows are usually fixed;
+ * a menu whose items reorder or filter needs `id` for the same reason.
+ *
+ * `items` selects the submenu shape rather than being an item prop, and `id` is
+ * identity for React rather than something `DropdownMenuItem` renders, so both
+ * are stripped. Every remaining field of `DropdownMenuItemData` is a
* `DropdownMenuItem` prop by construction (the type is `Pick`ed from
* `DropdownMenuItemProps`), so the data path forwards them wholesale and can't
* silently drop a field the data API advertises.
*/
-function renderLeafItem(item: DropdownMenuItemData): ReactElement {
- const {items: _submenuItems, ...itemProps} = item;
- return <DropdownMenuItem key={getItemKey(item)} {...itemProps} />;
+function renderLeafItem(
+ item: DropdownMenuItemData,
+ index: number,
+): ReactElement {
+ const {items: _submenuItems, id: _id, ...itemProps} = item;
+ return <DropdownMenuItem key={getItemKey(item, index)} {...itemProps} />;
}
/**
@@ -107,7 +117,7 @@ export function renderDropdownItems(items: DropdownMenuOption[]): ReactNode {
if (option.items && option.items.length > 0) {
elements.push(
<DropdownMenuSubMenu
- key={getItemKey(option)}
+ key={getItemKey(option, i)}
icon={option.icon}
label={option.label}
isDisabled={option.isDisabled}>
@@ -115,7 +125,7 @@ export function renderDropdownItems(items: DropdownMenuOption[]): ReactNode {
</DropdownMenuSubMenu>,
);
} else {
- elements.push(renderLeafItem(option));
+ elements.push(renderLeafItem(option, i));
}
}
}