An open source design system that's fully customizable and agent ready
TypeScript
feat(core): DropdownMenu & ContextMenu radio & checkbox menu items (#3829) (#4122)
Cindy Zhangeb8e07bb3bf9
diff --git a/.changeset/dropdown-menu-selectable-items.md b/.changeset/dropdown-menu-selectable-items.mdnew file mode 100644index 0000000000..ec135237f0--- /dev/null+++ b/.changeset/dropdown-menu-selectable-items.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] DropdownMenu selectable items: add `DropdownMenuCheckboxItem` (independent toggle, `role="menuitemcheckbox"`) and `DropdownMenuRadioGroup` + `DropdownMenuRadioItem` (single-select, `role="menuitemradio"`). The control size derives from the menu's item size and swaps to the row's inline-end on touch. They also work inside `ContextMenu` (re-exported as `ContextMenuCheckboxItem` / `ContextMenuRadioGroup` / `ContextMenuRadioItem`). Both menus' keyboard/typeahead/activation now recognize the selectable roles, and the menu context (`DropdownMenuContext`, `useDropdownMenuContext`, `DropdownMenuSize`) is exported for building custom menu items. See #3829.++@cixzhangdiff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsxindex 566b036c5d..ae68c0605f 100644--- a/apps/storybook/stories/ContextMenu.stories.tsx+++ b/apps/storybook/stories/ContextMenu.stories.tsx@@ -1,6 +1,13 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import type {Meta, StoryObj} from '@storybook/react';-import {ContextMenu, ContextMenuItem} from '@astryxdesign/core/ContextMenu';+import {useState} from 'react';+import {+ ContextMenu,+ ContextMenuItem,+ ContextMenuCheckboxItem,+ ContextMenuRadioGroup,+ ContextMenuRadioItem,+} from '@astryxdesign/core/ContextMenu';import {Divider} from '@astryxdesign/core/Divider';import {PencilIcon,@@ -303,3 +310,56 @@ export const CompoundWithDescriptions: Story = {</ContextMenu>),};++export const WithSelectableItems: Story = {+ render: function WithSelectableItemsStory() {+ const [sort, setSort] = useState('name');+ const [showHidden, setShowHidden] = useState(false);+ const [showPreview, setShowPreview] = useState(true);+ return (+ <ContextMenu+ menuWidth={220}+ menuContent={+ <>+ <ContextMenuItem+ icon={PencilIcon}+ label="Rename"+ onClick={() => console.log('Rename')}+ />+ <Divider />+ <ContextMenuRadioGroup+ value={sort}+ onChange={setSort}+ aria-label="Sort by">+ <ContextMenuRadioItem value="name" label="Sort by name" />+ <ContextMenuRadioItem value="date" label="Sort by date" />+ <ContextMenuRadioItem value="size" label="Sort by size" />+ </ContextMenuRadioGroup>+ <Divider />+ <ContextMenuCheckboxItem+ label="Show hidden files"+ value={showHidden}+ onChange={setShowHidden}+ />+ <ContextMenuCheckboxItem+ label="Show preview pane"+ value={showPreview}+ onChange={setShowPreview}+ />+ </>+ }>+ <div {...stylex.props(triggerStyles.area)}>+ Right-click for selectable items+ </div>+ </ContextMenu>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'Checkbox and radio menu items compose inside a ContextMenu just like in a DropdownMenu. The radio group is a single-select set (menuitemradio) that closes the menu on selection; the checkbox items are independent toggles (menuitemcheckbox) that keep the menu open so several can be flipped. Arrow keys, typeahead, and Enter/Space traverse and activate all three row types alongside plain items.',+ },+ },+ },+};diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsxindex c5dcd873e0..bdc3c910a7 100644--- a/apps/storybook/stories/DropdownMenu.stories.tsx+++ b/apps/storybook/stories/DropdownMenu.stories.tsx@@ -2,7 +2,13 @@import type {Meta, StoryObj} from '@storybook/react';import {useState} from 'react';-import {DropdownMenu, DropdownMenuItem} from '@astryxdesign/core/DropdownMenu';+import {+ DropdownMenu,+ DropdownMenuItem,+ DropdownMenuCheckboxItem,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+} from '@astryxdesign/core/DropdownMenu';import {Divider} from '@astryxdesign/core/Divider';import {PencilIcon,@@ -550,3 +556,104 @@ export const RTL: Story = {},},};++// =============================================================================+// Lab — selectable items (#3829)+// =============================================================================++export const LabCheckboxItems: Story = {+ render: function LabCheckboxItemsStory() {+ const [showArchived, setShowArchived] = useState(false);+ const [showDrafts, setShowDrafts] = useState(true);+ return (+ <DropdownMenu button={{label: 'View'}}>+ <DropdownMenuCheckboxItem+ label="Show archived"+ value={showArchived}+ onChange={setShowArchived}+ />+ <DropdownMenuCheckboxItem+ label="Show drafts"+ description="Include unpublished items"+ value={showDrafts}+ onChange={setShowDrafts}+ />+ </DropdownMenu>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'DropdownMenuCheckboxItem — independent toggles (role="menuitemcheckbox"). The menu stays open on toggle by default so several can be flipped at once.',+ },+ },+ },+};++export const LabRadioGroup: Story = {+ render: function LabRadioGroupStory() {+ const [sort, setSort] = useState('newest');+ return (+ <DropdownMenu button={{label: 'Sort'}}>+ <DropdownMenuRadioGroup+ value={sort}+ onChange={setSort}+ aria-label="Sort by">+ <DropdownMenuRadioItem value="newest" label="Newest" />+ <DropdownMenuRadioItem value="oldest" label="Oldest" />+ <DropdownMenuRadioItem+ value="az"+ label="Alphabetical"+ description="A → Z"+ />+ </DropdownMenuRadioGroup>+ </DropdownMenu>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'DropdownMenuRadioGroup + DropdownMenuRadioItem — single-select group (role="menuitemradio"). Selecting closes the menu by default.',+ },+ },+ },+};++export const LabSelectableSizes: Story = {+ render: function LabSelectableSizesStory() {+ const [sm, setSm] = useState('a');+ const [lg, setLg] = useState('a');+ return (+ <div style={{display: 'flex', gap: 24}}>+ <DropdownMenu button={{label: 'Small menu', size: 'sm'}}>+ <DropdownMenuRadioGroup+ value={sm}+ onChange={setSm}+ aria-label="Small">+ <DropdownMenuRadioItem value="a" label="Option A" />+ <DropdownMenuRadioItem value="b" label="Option B" />+ </DropdownMenuRadioGroup>+ </DropdownMenu>+ <DropdownMenu button={{label: 'Large menu', size: 'lg'}}>+ <DropdownMenuRadioGroup+ value={lg}+ onChange={setLg}+ aria-label="Large">+ <DropdownMenuRadioItem value="a" label="Option A" />+ <DropdownMenuRadioItem value="b" label="Option B" />+ </DropdownMenuRadioGroup>+ </DropdownMenu>+ </div>+ );+ },+ parameters: {+ docs: {+ description: {+ story:+ 'The checkbox/radio control size is derived from the menu item size — a `sm` menu renders the small (18px) control, `md`/`lg` render the standard (22px) control. On coarse-pointer (touch) devices the control swaps to the inline-end of the row.',+ },+ },+ },+};diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsxindex aa3d78788d..b2922aab8c 100644--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx@@ -12,7 +12,12 @@ import {describe, it, expect, vi, beforeEach} from 'vitest';import {render, screen, fireEvent, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {ContextMenu} from './ContextMenu';-import {ContextMenuItem} from './index';+import {+ ContextMenuItem,+ ContextMenuCheckboxItem,+ ContextMenuRadioGroup,+ ContextMenuRadioItem,+} from './index';import {DropdownMenuItem} from '../DropdownMenu/DropdownMenuItem';import {Divider} from '../Divider';@@ -537,3 +542,72 @@ describe('ContextMenu compound mode', () => {});});});++describe('ContextMenu selectable items', () => {+ it('renders checkbox and radio items with correct roles and state', () => {+ render(+ <ContextMenu+ menuContent={+ <>+ <ContextMenuRadioGroup+ value="name"+ onChange={() => {}}+ aria-label="Sort by">+ <ContextMenuRadioItem value="name" label="Sort by name" />+ <ContextMenuRadioItem value="date" label="Sort by date" />+ </ContextMenuRadioGroup>+ <ContextMenuCheckboxItem label="Show hidden" value={true} />+ </>+ }>+ <div>Right-click me</div>+ </ContextMenu>,+ );+ expect(+ screen.getByRole('menuitemradio', {name: 'Sort by name', hidden: true}),+ ).toHaveAttribute('aria-checked', 'true');+ expect(+ screen.getByRole('menuitemradio', {name: 'Sort by date', hidden: true}),+ ).toHaveAttribute('aria-checked', 'false');+ expect(+ screen.getByRole('menuitemcheckbox', {name: 'Show hidden', hidden: true}),+ ).toHaveAttribute('aria-checked', 'true');+ expect(+ screen.getByRole('group', {name: 'Sort by', hidden: true}),+ ).toBeInTheDocument();+ });++ it('fires onChange for radio and checkbox items', async () => {+ const user = userEvent.setup();+ const onSort = vi.fn();+ const onToggle = vi.fn();+ render(+ <ContextMenu+ menuContent={+ <>+ <ContextMenuRadioGroup+ value="name"+ onChange={onSort}+ aria-label="Sort by">+ <ContextMenuRadioItem value="name" label="Sort by name" />+ <ContextMenuRadioItem value="date" label="Sort by date" />+ </ContextMenuRadioGroup>+ <ContextMenuCheckboxItem+ label="Show hidden"+ value={false}+ onChange={onToggle}+ />+ </>+ }>+ <div>Right-click me</div>+ </ContextMenu>,+ );+ await user.click(+ screen.getByRole('menuitemradio', {name: 'Sort by date', hidden: true}),+ );+ expect(onSort).toHaveBeenCalledWith('date');+ await user.click(+ screen.getByRole('menuitemcheckbox', {name: 'Show hidden', hidden: true}),+ );+ expect(onToggle).toHaveBeenCalledWith(true);+ });+});diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex 54e72232c5..b8709534eb 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -46,6 +46,10 @@ import {DropdownMenuContext,type DropdownMenuContextValue,} from '../DropdownMenu/DropdownMenuContext';+import {+ MENU_ITEM_ROLES,+ MENU_ITEM_SELECTOR,+} from '../DropdownMenu/menuItemRoles';import {useListFocus} from '../hooks/useListFocus';import {useTypeahead} from '../hooks/useTypeahead';import {useLongPress} from '../hooks/useLongPress';@@ -265,7 +269,7 @@ export function ContextMenu({focusFirst,focusItem,} = useListFocus<HTMLDivElement>({- itemSelector: '[role="menuitem"]:not([aria-disabled="true"])',+ itemSelector: MENU_ITEM_SELECTOR,wrap: false,onEscape: closeMenu,});@@ -275,9 +279,7 @@ export function ContextMenu({(): HTMLElement[] =>listRef.current? Array.from(- listRef.current.querySelectorAll<HTMLElement>(- '[role="menuitem"]:not([aria-disabled="true"])',- ),+ listRef.current.querySelectorAll<HTMLElement>(MENU_ITEM_SELECTOR),): [],[listRef],@@ -341,7 +343,10 @@ export function ContextMenu({if (e.key === 'Enter' || e.key === ' ') {e.preventDefault();const focused = document.activeElement as HTMLElement | null;- if (focused?.getAttribute('role') === 'menuitem') {+ if (+ focused &&+ MENU_ITEM_ROLES.has(focused.getAttribute('role') ?? '')+ ) {focused.click();}return;diff --git a/packages/core/src/ContextMenu/index.ts b/packages/core/src/ContextMenu/index.tsindex 83e72c048a..da92d7aef2 100644--- a/packages/core/src/ContextMenu/index.ts+++ b/packages/core/src/ContextMenu/index.ts@@ -20,3 +20,18 @@ export {DropdownMenuItem as ContextMenuItem,type DropdownMenuItemProps as ContextMenuItemProps,} from '../DropdownMenu/DropdownMenuItem';++// Selectable items work inside a ContextMenu too — re-exported under the+// ContextMenu name for a coherent API.+export {+ DropdownMenuCheckboxItem as ContextMenuCheckboxItem,+ type DropdownMenuCheckboxItemProps as ContextMenuCheckboxItemProps,+} from '../DropdownMenu/DropdownMenuCheckboxItem';+export {+ DropdownMenuRadioGroup as ContextMenuRadioGroup,+ type DropdownMenuRadioGroupProps as ContextMenuRadioGroupProps,+} from '../DropdownMenu/DropdownMenuRadioGroup';+export {+ DropdownMenuRadioItem as ContextMenuRadioItem,+ type DropdownMenuRadioItemProps as ContextMenuRadioItemProps,+} from '../DropdownMenu/DropdownMenuRadioItem';diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjsindex b28acfe632..c982652c56 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs@@ -12,6 +12,16 @@ export const docs = {targets: [{className: 'astryx-dropdown-menu'},{className: 'astryx-dropdown-menu-item', visualProps: ['size']},+ {+ className: 'astryx-dropdown-menu-checkbox',+ visualProps: ['size'],+ states: ['checked', 'disabled'],+ },+ {+ className: 'astryx-dropdown-menu-radio',+ visualProps: ['size'],+ states: ['checked', 'disabled'],+ },],vars: [{name: '--_dropdown-menu-radius', description: 'Border radius of the menu popup', default: 'var(--radius-element)', private: true},diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex 62cb18b841..38e2161860 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -38,6 +38,7 @@ import {Icon} from '../Icon';import type {IconType} from '../Icon';import {renderDropdownItems} from './renderDropdownItems';+import {MENU_ITEM_ROLES, MENU_ITEM_SELECTOR} from './menuItemRoles';import {DropdownMenuContext,type DropdownMenuContextValue,@@ -255,14 +256,17 @@ export function DropdownMenu({popover.hide();}, [popover]);- // Single keyboard navigation path for both modes+ // Single keyboard navigation path for both modes.+ // The selector matches plain items plus selectable items+ // (menuitemradio/menuitemcheckbox) so lab checkbox/radio rows are reachable+ // and roved to alongside plain items — not just role="menuitem".const {listRef,handleKeyDown: listNavKeyDown,focusFirst,focusItem,} = useListFocus<HTMLDivElement>({- itemSelector: '[role="menuitem"]:not([aria-disabled="true"])',+ itemSelector: MENU_ITEM_SELECTOR,wrap: false,onEscape: closeMenu,});@@ -273,9 +277,7 @@ export function DropdownMenu({(): HTMLElement[] =>listRef.current? Array.from(- listRef.current.querySelectorAll<HTMLElement>(- '[role="menuitem"]:not([aria-disabled="true"])',- ),+ listRef.current.querySelectorAll<HTMLElement>(MENU_ITEM_SELECTOR),): [],[listRef],@@ -308,7 +310,10 @@ export function DropdownMenu({if (e.key === 'Enter' || e.key === ' ') {e.preventDefault();const focused = document.activeElement as HTMLElement | null;- if (focused?.getAttribute('role') === 'menuitem') {+ if (+ focused &&+ MENU_ITEM_ROLES.has(focused.getAttribute('role') ?? '')+ ) {focused.click();}return;diff --git a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjsnew file mode 100644index 0000000000..6896e2cfcb--- /dev/null+++ b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs@@ -0,0 +1,95 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../docs-types').ComponentDoc} */++export const docs = {+ name: 'DropdownMenuCheckboxItem',+ subComponentOf: 'DropdownMenu',+ displayName: 'Dropdown Menu Checkbox Item',+ isHiddenFromOverview: true,+ description:+ 'A checkable menu item (role="menuitemcheckbox") that toggles an independent boolean. Use for on/off options inside a DropdownMenu; for a one-of-N choice use DropdownMenuRadioGroup.',+ props: [+ {+ name: 'label',+ type: 'ReactNode',+ description: 'Primary label text identifying the item.',+ },+ {+ name: 'description',+ type: 'ReactNode',+ description: 'Secondary description text displayed below the label.',+ },+ {+ name: 'icon',+ type: 'IconType',+ description:+ 'Icon to display before the label. See `npx astryx docs icons` for valid semantic names.',+ },+ {+ name: 'value',+ type: 'boolean',+ description: 'Whether the item is checked. Controlled — pair with onChange.',+ },+ {+ name: 'onChange',+ type: '(checked: boolean) => void',+ description: 'Callback fired with the next checked state when the item is toggled.',+ },+ {+ name: 'isDisabled',+ type: 'boolean',+ default: 'false',+ description:+ 'Whether the item is disabled. Disabled items stay focusable (via aria-disabled) so they remain discoverable by keyboard and assistive technology, but activation is blocked.',+ },+ {+ name: 'hasCloseOnSelect',+ type: 'boolean',+ default: 'false',+ description:+ 'Whether toggling the item closes the menu. Checkbox items default to staying open so several can be toggled in a single session.',+ },+ {+ name: 'endContent',+ type: 'ReactNode',+ description:+ 'Content to render after the label and description, such as a keyboard shortcut hint or badge.',+ },+ ],+};++export const docsZh = {+ name: 'DropdownMenuCheckboxItem',+ isHiddenFromOverview: true,+ displayName: 'Dropdown Menu Checkbox Item',+ description:+ '可勾选的菜单项(role="menuitemcheckbox"),用于切换独立的布尔值。用于 DropdownMenu 中的开关选项;单选请使用 DropdownMenuRadioGroup。',+ propDescriptions: {+ label: '标识该项的主标签文本。',+ description: '显示在标签下方的次要描述文本。',+ icon: '显示在标签前的图标。',+ value: '该项是否被勾选。受控 — 与 onChange 搭配使用。',+ onChange: '切换该项时以下一个勾选状态触发的回调。',+ isDisabled: '该项是否禁用。',+ hasCloseOnSelect: '切换该项是否关闭菜单。默认保持打开。',+ endContent: '在标签和描述之后渲染的内容。',+ },+};++export const docsDense = {+ name: 'DropdownMenuCheckboxItem',+ isHiddenFromOverview: true,+ displayName: 'Dropdown Menu Checkbox Item',+ description: 'checkable menu item (menuitemcheckbox); independent boolean toggle',+ propDescriptions: {+ label: 'primary label text',+ description: 'secondary text below label',+ icon: 'icon before label',+ value: 'checked state (controlled, w/ onChange)',+ onChange: 'fired w/ next checked state on toggle',+ isDisabled: 'disabled; stays focusable via aria-disabled',+ hasCloseOnSelect: 'close menu on toggle (default false — stays open)',+ endContent: 'content after label+description',+ },+};diff --git a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsxnew file mode 100644index 0000000000..efa4e78875--- /dev/null+++ b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx@@ -0,0 +1,237 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file DropdownMenuCheckboxItem.tsx+ * @input React, stylex, Item + Icon + DropdownMenu context + tokens from core+ * @output DropdownMenuCheckboxItem — a standalone checkable menu item.+ * @position Sub-component; used inside DropdownMenu.+ *+ * A menu item that toggles an independent boolean (role="menuitemcheckbox").+ * Unlike CheckboxInput, there is no nested native <input>: the row itself owns+ * the role and aria-checked, per the WAI-ARIA menuitemcheckbox pattern.+ * Keyboard navigation (arrows/typeahead) and Enter/Space activation come from+ * the parent DropdownMenu's useListFocus + activation path, which matches+ * menuitemcheckbox alongside plain menuitem rows.+ *+ * The square checkbox visual is decorative (aria-hidden) — the row owns the+ * checked state. Its size is derived from the menu's item size (a `sm` menu+ * gets the compact control; `md`/`lg` get the standard one) and it swaps to the+ * inline-end of the row on coarse-pointer (touch) devices via CSS `order`, so+ * it lands where selection toggles are conventionally placed on mobile. The+ * checkmark uses the `check` icon from the active theme's icon registry.+ */++import {useCallback, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {Icon, renderIconSlot, type IconType} from '../Icon';+import {Item} from '../Item';+import {useDropdownMenuContext} from './DropdownMenuContext';+import {+ colorVars,+ spacingVars,+ radiusVars,+ durationVars,+ easeVars,+ borderVars,+} from '../theme/tokens.stylex';+import {mergeProps, themeProps} from '../utils';+import type {BaseProps} from '../BaseProps';++const styles = stylex.create({+ root: {+ width: '100%',+ borderRadius: `max(0px, calc(var(--_dropdown-menu-radius, ${spacingVars['--spacing-2']}) - var(--_dropdown-menu-padding, ${spacingVars['--spacing-1']})))`,+ color: colorVars['--color-text-primary'],+ backgroundColor: {+ default: 'transparent',+ ':focus': colorVars['--color-overlay-hover'],+ ':hover': colorVars['--color-overlay-hover'],+ },+ cursor: 'pointer',+ outline: 'none',+ },+ disabled: {+ opacity: 0.5,+ cursor: 'not-allowed',+ },+ // Rendered in Item's `marker` slot as a raw flex child, so `order` moves it+ // relative to the label within the row. On touch it moves to the inline-end.+ box: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ boxSizing: 'border-box',+ borderWidth: borderVars['--border-width'],+ borderStyle: 'solid',+ borderRadius: radiusVars['--radius-inner'],+ color: colorVars['--color-on-accent'],+ transitionProperty: 'background-color, border-color',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ order: {+ default: 0,+ '@media (pointer: coarse)': 1,+ },+ marginInlineStart: {+ default: 0,+ '@media (pointer: coarse)': 'auto',+ },+ },+ unchecked: {+ borderColor: colorVars['--color-border-emphasized'],+ backgroundColor: colorVars['--color-background-surface'],+ },+ checked: {+ borderColor: colorVars['--color-accent'],+ backgroundColor: colorVars['--color-accent'],+ },+});++const boxSizeStyles = stylex.create({+ sm: {width: 18, height: 18},+ md: {width: 22, height: 22},+});++export interface DropdownMenuCheckboxItemProps extends Omit<+ BaseProps,+ 'onChange' | 'role' | 'aria-checked' | 'tabIndex'+> {+ /**+ * Primary label text identifying the item.+ */+ label: ReactNode;+ /**+ * Secondary description text displayed below the label.+ */+ description?: ReactNode;+ /**+ * Icon to display before the label. Accepts a semantic icon name (see+ * `npx astryx docs icons`) or a rendered node.+ */+ icon?: ReactNode | IconType;+ /**+ * Whether the item is checked. Controlled — pair with `onChange`.+ */+ value: boolean;+ /**+ * Callback fired with the next checked state when the item is toggled.+ */+ onChange?: (checked: boolean) => void;+ /**+ * Whether the item is disabled. Disabled items stay focusable (via+ * `aria-disabled`) so they remain discoverable by keyboard and assistive+ * technology, but activation is blocked.+ * @default false+ */+ isDisabled?: boolean;+ /**+ * Whether toggling the item closes the menu. Checkbox items default to+ * staying open so several can be toggled in a single session, unlike radio+ * items which default to closing on selection.+ * @default false+ */+ hasCloseOnSelect?: boolean;+ /**+ * Content to render after the label and description, such as a keyboard+ * shortcut hint or badge.+ */+ endContent?: ReactNode;+}++/**+ * A checkable dropdown menu item (role="menuitemcheckbox").+ *+ * Must be used inside a DropdownMenu. Toggles an independent boolean; for a+ * one-of-N choice use DropdownMenuRadioGroup + DropdownMenuRadioItem instead.+ *+ * @example+ * ```+ * * import {DropdownMenuCheckboxItem} from '@astryxdesign/core/DropdownMenu';+ *+ * <DropdownMenu button={{label: 'View'}}>+ * <DropdownMenuCheckboxItem+ * label="Show archived"+ * value={showArchived}+ * onChange={setShowArchived}+ * />+ * </DropdownMenu>+ * ```+ */+export function DropdownMenuCheckboxItem({+ label,+ description,+ icon,+ value,+ onChange,+ isDisabled = false,+ hasCloseOnSelect = false,+ endContent,+ xstyle,+ className,+ style,+ ...rest+}: DropdownMenuCheckboxItemProps) {+ const ctx = useDropdownMenuContext();+ const menuSize = ctx?.menuSize ?? 'md';+ const controlSize = menuSize === 'sm' ? 'sm' : 'md';++ const handleClick = useCallback(() => {+ if (isDisabled) {+ return;+ }+ onChange?.(!value);+ if (hasCloseOnSelect) {+ ctx?.closeMenu();+ }+ }, [isDisabled, onChange, value, hasCloseOnSelect, ctx]);++ return (+ <Item+ {...rest}+ role="menuitemcheckbox"+ aria-checked={value}+ tabIndex={isDisabled ? undefined : -1}+ marker={+ <span+ aria-hidden="true"+ {...mergeProps(+ themeProps('dropdown-menu-checkbox', {+ size: controlSize,+ checked: value ? 'checked' : null,+ disabled: isDisabled ? 'disabled' : null,+ }),+ stylex.props(+ styles.box,+ boxSizeStyles[controlSize],+ value ? styles.checked : styles.unchecked,+ ),+ )}>+ {value && <Icon icon="check" size="sm" color="inherit" />}+ </span>+ }+ startContent={+ icon+ ? renderIconSlot(icon, {size: 'sm', color: 'secondary'})+ : undefined+ }+ label={label}+ description={description}+ endContent={endContent}+ onClick={handleClick}+ isDisabled={isDisabled}+ xstyle={[styles.root, isDisabled && styles.disabled, xstyle]}+ {...mergeProps(themeProps('dropdown-menu-item', {size: menuSize}), {+ className,+ style,+ })}+ />+ );+}++DropdownMenuCheckboxItem.displayName = 'DropdownMenuCheckboxItem';diff --git a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx b/packages/core/src/DropdownMenu/DropdownMenuContext.tsxindex 567c04f623..b5bfe316b3 100644--- a/packages/core/src/DropdownMenu/DropdownMenuContext.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuContext.tsx@@ -14,11 +14,14 @@import {createContext, use} from 'react';+/** Menu size, derived from the trigger button size. */+export type DropdownMenuSize = 'sm' | 'md' | 'lg';+export interface DropdownMenuContextValue {/** Close the menu and return focus to trigger */closeMenu: () => void;/** Menu size derived from button size */- menuSize: 'sm' | 'md' | 'lg';+ menuSize: DropdownMenuSize;}export const DropdownMenuContext =@@ -32,3 +35,28 @@ DropdownMenuContext.displayName = 'DropdownMenuContext';export function useDropdownMenuContext(): DropdownMenuContextValue | null {return use(DropdownMenuContext);}++// =============================================================================+// Radio group coordination+// =============================================================================++export interface DropdownMenuRadioGroupContextValue {+ /** The currently selected value in the group. */+ value: string | undefined;+ /** Select a value. Called by a DropdownMenuRadioItem on activation. */+ onChange: (value: string) => void;+ /** Whether selecting an item should close the menu. @default true */+ hasCloseOnSelect: boolean;+}++export const DropdownMenuRadioGroupContext =+ createContext<DropdownMenuRadioGroupContextValue | null>(null);+DropdownMenuRadioGroupContext.displayName = 'DropdownMenuRadioGroupContext';++/**+ * Read the enclosing radio group's selection state.+ * Returns null when used outside a DropdownMenuRadioGroup.+ */+export function useDropdownMenuRadioGroupContext(): DropdownMenuRadioGroupContextValue | null {+ return use(DropdownMenuRadioGroupContext);+}diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioGroup.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuRadioGroup.doc.mjsnew file mode 100644index 0000000000..2189d05e96--- /dev/null+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioGroup.doc.mjs@@ -0,0 +1,80 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../docs-types').ComponentDoc} */++export const docs = {+ name: 'DropdownMenuRadioGroup',+ subComponentOf: 'DropdownMenu',+ displayName: 'Dropdown Menu Radio Group',+ isHiddenFromOverview: true,+ description:+ 'A single-select group of radio menu items (role="group" of menuitemradio). Owns the selected value and lays its items out with the menu\'s inter-item gap.',+ props: [+ {+ name: 'value',+ type: 'string | undefined',+ description:+ 'The currently selected value in the group. Pass undefined when nothing is selected yet.',+ },+ {+ name: 'onChange',+ type: '(value: string) => void',+ description: 'Callback fired when the selected value changes.',+ },+ {+ name: 'aria-label',+ type: 'string',+ description:+ 'Accessible label for the group. Required (or aria-labelledby) so screen readers announce the radios as a named set, e.g. "Sort by".',+ },+ {+ name: 'aria-labelledby',+ type: 'string',+ description:+ 'The id of an element that labels the group, as an alternative to aria-label.',+ },+ {+ name: 'hasCloseOnSelect',+ type: 'boolean',+ default: 'true',+ description:+ 'Whether selecting a value closes the menu. Radio items default to closing on selection (a single-choice commit).',+ },+ {+ name: 'children',+ type: 'ReactNode',+ description: 'The DropdownMenuRadioItems that make up the group.',+ },+ ],+};++export const docsZh = {+ name: 'DropdownMenuRadioGroup',+ isHiddenFromOverview: true,+ displayName: 'Dropdown Menu Radio Group',+ description:+ '单选的单选菜单项组(menuitemradio 的 role="group")。持有所选值,并以菜单的项间距布局其子项。',+ propDescriptions: {+ value: '组中当前选中的值。尚无选中项时传 undefined。',+ onChange: '所选值变化时触发的回调。',+ 'aria-label': '组的无障碍标签。必需(或 aria-labelledby),以便屏幕阅读器将单选项作为命名集合朗读。',+ 'aria-labelledby': '标记该组的元素 id,作为 aria-label 的替代。',+ hasCloseOnSelect: '选择某值是否关闭菜单。默认关闭。',+ children: '组成该组的 DropdownMenuRadioItem。',+ },+};++export const docsDense = {+ name: 'DropdownMenuRadioGroup',+ isHiddenFromOverview: true,+ displayName: 'Dropdown Menu Radio Group',+ description: 'single-select group of menuitemradio; owns selected value',+ propDescriptions: {+ value: 'selected value (undefined = none)',+ onChange: 'fired when selected value changes',+ 'aria-label': 'accessible group name (or aria-labelledby); required',+ 'aria-labelledby': 'id of labelling element (alt to aria-label)',+ hasCloseOnSelect: 'close menu on select (default true)',+ children: 'the DropdownMenuRadioItems',+ },+};diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioGroup.tsx b/packages/core/src/DropdownMenu/DropdownMenuRadioGroup.tsxnew file mode 100644index 0000000000..96cb75f328--- /dev/null+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioGroup.tsx@@ -0,0 +1,119 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file DropdownMenuRadioGroup.tsx+ * @output DropdownMenuRadioGroup — a single-select group of menu items.+ * @position Sub-component; wraps DropdownMenuRadioItem inside a DropdownMenu.+ *+ * Owns single-selection state (value/onChange) for its child+ * DropdownMenuRadioItems and exposes it via context. Renders role="group" with+ * an accessible name so the radios are announced as a set. Keyboard navigation+ * comes from the parent DropdownMenu's useListFocus, which matches+ * menuitemradio rows.+ */++import {useMemo, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {spacingVars} from '../theme/tokens.stylex';+import {mergeProps} from '../utils';+import type {BaseProps} from '../BaseProps';+import {+ DropdownMenuRadioGroupContext,+ type DropdownMenuRadioGroupContextValue,+} from './DropdownMenuContext';++const styles = stylex.create({+ // Match the menu's own inter-item rhythm (2px) so grouped radio items keep+ // the same gap as ungrouped items instead of sitting flush against each+ // other inside the role="group" wrapper.+ group: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-0-5'],+ },+});++export interface DropdownMenuRadioGroupProps extends Omit<+ BaseProps,+ 'onChange'+> {+ /**+ * The currently selected value in the group. Pass `undefined` when nothing+ * is selected yet.+ */+ value: string | undefined;+ /**+ * Callback fired when the selected value changes.+ */+ onChange: (value: string) => void;+ /**+ * Accessible label for the group. Required (together with `aria-labelledby`,+ * one of the two) so screen readers announce the radios as a named set,+ * e.g. "Sort by".+ */+ 'aria-label'?: string;+ /**+ * The id of an element that labels the group, as an alternative to+ * `aria-label`.+ */+ 'aria-labelledby'?: string;+ /**+ * Whether selecting a value closes the menu. Radio items default to closing+ * on selection (a single-choice commit), unlike checkbox items which stay+ * open.+ * @default true+ */+ hasCloseOnSelect?: boolean;+ /**+ * The `DropdownMenuRadioItem`s that make up the group.+ */+ children: ReactNode;+}++/**+ * A single-select group of radio menu items (role="group" of menuitemradio).+ *+ * @example+ * ```+ * * import {+ * DropdownMenuRadioGroup,+ * DropdownMenuRadioItem,+ * } from '@astryxdesign/core/DropdownMenu';+ *+ * <DropdownMenu button={{label: 'Sort'}}>+ * <DropdownMenuRadioGroup value={sort} onChange={setSort} aria-label="Sort by">+ * <DropdownMenuRadioItem value="newest" label="Newest" />+ * <DropdownMenuRadioItem value="oldest" label="Oldest" />+ * </DropdownMenuRadioGroup>+ * </DropdownMenu>+ * ```+ */+export function DropdownMenuRadioGroup({+ value,+ onChange,+ hasCloseOnSelect = true,+ children,+ className,+ style,+ ...rest+}: DropdownMenuRadioGroupProps) {+ const contextValue = useMemo<DropdownMenuRadioGroupContextValue>(+ () => ({value, onChange, hasCloseOnSelect}),+ [value, onChange, hasCloseOnSelect],+ );++ return (+ <div+ {...rest}+ role="group"+ {...mergeProps(stylex.props(styles.group), {className, style})}>+ <DropdownMenuRadioGroupContext value={contextValue}>+ {children}+ </DropdownMenuRadioGroupContext>+ </div>+ );+}++DropdownMenuRadioGroup.displayName = 'DropdownMenuRadioGroup';diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjsnew file mode 100644index 0000000000..6b3e488fb7--- /dev/null+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs@@ -0,0 +1,80 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../docs-types').ComponentDoc} */++export const docs = {+ name: 'DropdownMenuRadioItem',+ subComponentOf: 'DropdownMenu',+ displayName: 'Dropdown Menu Radio Item',+ isHiddenFromOverview: true,+ description:+ 'A single option in a DropdownMenuRadioGroup (role="menuitemradio"). Must be used inside a DropdownMenuRadioGroup.',+ props: [+ {+ name: 'value',+ type: 'string',+ description:+ "The value this item represents within its group. The group's value matches against this to determine the checked state.",+ },+ {+ name: 'label',+ type: 'ReactNode',+ description: 'Primary label text identifying the option.',+ },+ {+ name: 'description',+ type: 'ReactNode',+ description: 'Secondary description text displayed below the label.',+ },+ {+ name: 'icon',+ type: 'IconType',+ description:+ 'Icon to display before the label. See `npx astryx docs icons` for valid semantic names.',+ },+ {+ name: 'isDisabled',+ type: 'boolean',+ default: 'false',+ description:+ 'Whether this individual radio item is disabled. Disabled items stay focusable (via aria-disabled) so they remain discoverable by keyboard and assistive technology, but selection is blocked.',+ },+ {+ name: 'endContent',+ type: 'ReactNode',+ description:+ 'Content to render after the label and description, such as a badge or metadata.',+ },+ ],+};++export const docsZh = {+ name: 'DropdownMenuRadioItem',+ isHiddenFromOverview: true,+ displayName: 'Dropdown Menu Radio Item',+ description:+ 'DropdownMenuRadioGroup 中的单个选项(role="menuitemradio")。必须在 DropdownMenuRadioGroup 内使用。',+ propDescriptions: {+ value: '该项在组内代表的值。组的 value 与之匹配以确定勾选状态。',+ label: '标识该选项的主标签文本。',+ description: '显示在标签下方的次要描述文本。',+ icon: '显示在标签前的图标。',+ isDisabled: '该单选项是否禁用。',+ endContent: '在标签和描述之后渲染的内容。',+ },+};++export const docsDense = {+ name: 'DropdownMenuRadioItem',+ isHiddenFromOverview: true,+ displayName: 'Dropdown Menu Radio Item',+ description: 'one option in a DropdownMenuRadioGroup (menuitemradio)',+ propDescriptions: {+ value: "item's value within the group (matched vs group value)",+ label: 'primary label text',+ description: 'secondary text below label',+ icon: 'icon before label',+ isDisabled: 'disabled; stays focusable via aria-disabled',+ endContent: 'content after label+description',+ },+};diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsxnew file mode 100644index 0000000000..35ac7a15ca--- /dev/null+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx@@ -0,0 +1,232 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file DropdownMenuRadioItem.tsx+ * @input React, stylex, Item + Icon + DropdownMenu context + tokens from core+ * @output DropdownMenuRadioItem — a single option in a radio group.+ * @position Sub-component; must be used inside a DropdownMenuRadioGroup.+ *+ * A menu item representing one option in a single-select group+ * (role="menuitemradio"). The row owns the role and aria-checked; there is no+ * nested native <input> (per the WAI-ARIA menuitemradio pattern). Selection+ * state + onChange come from DropdownMenuRadioGroupContext. Keyboard nav ++ * Enter/Space activation come from the parent DropdownMenu.+ *+ * The round radio visual (circle + center dot) is decorative (aria-hidden) —+ * the row owns the checked state. Its size is derived from the menu's item size+ * and it swaps to the inline-end of the row on coarse-pointer (touch) devices+ * via CSS `order`. The dot is a shaped element, not an icon (a filled circle+ * has no registry glyph).+ */++import {useCallback, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {renderIconSlot, type IconType} from '../Icon';+import {Item} from '../Item';+import {useDropdownMenuContext} from './DropdownMenuContext';+import {+ colorVars,+ spacingVars,+ durationVars,+ easeVars,+ borderVars,+} from '../theme/tokens.stylex';+import {mergeProps, themeProps} from '../utils';+import type {BaseProps} from '../BaseProps';+import {useDropdownMenuRadioGroupContext} from './DropdownMenuContext';++const styles = stylex.create({+ root: {+ width: '100%',+ borderRadius: `max(0px, calc(var(--_dropdown-menu-radius, ${spacingVars['--spacing-2']}) - var(--_dropdown-menu-padding, ${spacingVars['--spacing-1']})))`,+ color: colorVars['--color-text-primary'],+ backgroundColor: {+ default: 'transparent',+ ':focus': colorVars['--color-overlay-hover'],+ ':hover': colorVars['--color-overlay-hover'],+ },+ cursor: 'pointer',+ outline: 'none',+ },+ disabled: {+ opacity: 0.5,+ cursor: 'not-allowed',+ },+ // Rendered in Item's `marker` slot as a raw flex child. On touch it moves to+ // the inline-end of the row via `order`.+ circle: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ boxSizing: 'border-box',+ borderWidth: borderVars['--border-width'],+ borderStyle: 'solid',+ borderRadius: '50%',+ transitionProperty: 'background-color, border-color',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ order: {+ default: 0,+ '@media (pointer: coarse)': 1,+ },+ marginInlineStart: {+ default: 0,+ '@media (pointer: coarse)': 'auto',+ },+ },+ unchecked: {+ borderColor: colorVars['--color-border-emphasized'],+ backgroundColor: colorVars['--color-background-surface'],+ },+ checked: {+ borderColor: colorVars['--color-accent'],+ backgroundColor: colorVars['--color-accent'],+ },+ dot: {+ borderRadius: '50%',+ backgroundColor: colorVars['--color-on-accent'],+ },+});++const circleSizeStyles = stylex.create({+ sm: {width: 18, height: 18},+ md: {width: 22, height: 22},+});++const dotSizeStyles = stylex.create({+ sm: {width: 6, height: 6},+ md: {width: 8, height: 8},+});++export interface DropdownMenuRadioItemProps extends Omit<+ BaseProps,+ 'role' | 'aria-checked' | 'tabIndex'+> {+ /**+ * The value this item represents within its group. The group's `value`+ * matches against this to determine the checked state.+ */+ value: string;+ /**+ * Primary label text identifying the option.+ */+ label: ReactNode;+ /**+ * Secondary description text displayed below the label.+ */+ description?: ReactNode;+ /**+ * Icon to display before the label. Accepts a semantic icon name (see+ * `npx astryx docs icons`) or a rendered node.+ */+ icon?: ReactNode | IconType;+ /**+ * Whether this individual radio item is disabled. Disabled items stay+ * focusable (via `aria-disabled`) so they remain discoverable by keyboard+ * and assistive technology, but selection is blocked.+ * @default false+ */+ isDisabled?: boolean;+ /**+ * Content to render after the label and description, such as a badge or+ * metadata.+ */+ endContent?: ReactNode;+}++/**+ * A single option in a DropdownMenuRadioGroup (role="menuitemradio").+ *+ * @example+ * ```+ * <DropdownMenuRadioGroup value={sort} onChange={setSort} aria-label="Sort by">+ * <DropdownMenuRadioItem value="newest" label="Newest" />+ * <DropdownMenuRadioItem value="oldest" label="Oldest" icon="clock" />+ * </DropdownMenuRadioGroup>+ * ```+ */+export function DropdownMenuRadioItem({+ value,+ label,+ description,+ icon,+ isDisabled = false,+ endContent,+ xstyle,+ className,+ style,+ ...rest+}: DropdownMenuRadioItemProps) {+ const menuCtx = useDropdownMenuContext();+ const groupCtx = useDropdownMenuRadioGroupContext();+ if (!groupCtx) {+ throw new Error(+ 'DropdownMenuRadioItem must be used within a DropdownMenuRadioGroup',+ );+ }+ const menuSize = menuCtx?.menuSize ?? 'md';+ const controlSize = menuSize === 'sm' ? 'sm' : 'md';+ const isChecked = groupCtx.value === value;++ const handleClick = useCallback(() => {+ if (isDisabled) {+ return;+ }+ groupCtx.onChange(value);+ if (groupCtx.hasCloseOnSelect) {+ menuCtx?.closeMenu();+ }+ }, [isDisabled, groupCtx, value, menuCtx]);++ return (+ <Item+ {...rest}+ role="menuitemradio"+ aria-checked={isChecked}+ tabIndex={isDisabled ? undefined : -1}+ marker={+ <span+ aria-hidden="true"+ {...mergeProps(+ themeProps('dropdown-menu-radio', {+ size: controlSize,+ checked: isChecked ? 'checked' : null,+ disabled: isDisabled ? 'disabled' : null,+ }),+ stylex.props(+ styles.circle,+ circleSizeStyles[controlSize],+ isChecked ? styles.checked : styles.unchecked,+ ),+ )}>+ {isChecked && (+ <span {...stylex.props(styles.dot, dotSizeStyles[controlSize])} />+ )}+ </span>+ }+ startContent={+ icon+ ? renderIconSlot(icon, {size: 'sm', color: 'secondary'})+ : undefined+ }+ label={label}+ description={description}+ endContent={endContent}+ onClick={handleClick}+ isDisabled={isDisabled}+ xstyle={[styles.root, isDisabled && styles.disabled, xstyle]}+ {...mergeProps(themeProps('dropdown-menu-item', {size: menuSize}), {+ className,+ style,+ })}+ />+ );+}++DropdownMenuRadioItem.displayName = 'DropdownMenuRadioItem';diff --git a/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsxnew file mode 100644index 0000000000..f29d8e4434--- /dev/null+++ b/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx@@ -0,0 +1,163 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DropdownMenuSelectable.test.tsx+ * @input vitest, @testing-library/react, DropdownMenu + selectable items+ * @output Unit tests for DropdownMenuCheckboxItem / RadioGroup / RadioItem (#3829)+ */++import {describe, it, expect, vi, beforeEach} from 'vitest';+import {render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {DropdownMenu} from './DropdownMenu';+import {DropdownMenuCheckboxItem} from './DropdownMenuCheckboxItem';+import {DropdownMenuRadioGroup} from './DropdownMenuRadioGroup';+import {DropdownMenuRadioItem} from './DropdownMenuRadioItem';++beforeEach(() => {+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {+ this.setAttribute('popover-open', '');+ const event = new Event('toggle', {bubbles: false});+ Object.defineProperty(event, 'newState', {value: 'open'});+ this.dispatchEvent(event);+ });+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {+ this.removeAttribute('popover-open');+ const event = new Event('toggle', {bubbles: false});+ Object.defineProperty(event, 'newState', {value: 'closed'});+ this.dispatchEvent(event);+ });+ const originalMatches = HTMLElement.prototype.matches;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (HTMLElement.prototype as any).matches = function (+ selector: string,+ ): boolean {+ if (selector === ':popover-open') {+ return this.hasAttribute('popover-open');+ }+ return originalMatches.call(this, selector);+ };+});++describe('DropdownMenuCheckboxItem', () => {+ it('renders role menuitemcheckbox and reflects checked state', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu button={{label: 'View'}}>+ <DropdownMenuCheckboxItem label="Show archived" value={true} />+ </DropdownMenu>,+ );+ await user.click(screen.getByRole('button', {name: /View/}));+ expect(+ screen.getByRole('menuitemcheckbox', {+ name: /Show archived/,+ hidden: true,+ }),+ ).toHaveAttribute('aria-checked', 'true');+ });++ it('calls onChange with the toggled value on click', async () => {+ const user = userEvent.setup();+ const onChangeSpy = vi.fn();+ render(+ <DropdownMenu button={{label: 'View'}}>+ <DropdownMenuCheckboxItem+ label="Show archived"+ value={false}+ onChange={onChangeSpy}+ />+ </DropdownMenu>,+ );+ await user.click(screen.getByRole('button', {name: /View/}));+ await user.click(+ screen.getByRole('menuitemcheckbox', {+ name: /Show archived/,+ hidden: true,+ }),+ );+ expect(onChangeSpy).toHaveBeenCalledWith(true);+ });++ it('does not toggle when disabled', async () => {+ const user = userEvent.setup();+ const onChangeSpy = vi.fn();+ render(+ <DropdownMenu button={{label: 'View'}}>+ <DropdownMenuCheckboxItem+ label="Show archived"+ value={false}+ onChange={onChangeSpy}+ isDisabled+ />+ </DropdownMenu>,+ );+ await user.click(screen.getByRole('button', {name: /View/}));+ const item = screen.getByRole('menuitemcheckbox', {+ name: /Show archived/,+ hidden: true,+ });+ expect(item).toHaveAttribute('aria-disabled', 'true');+ await user.click(item);+ expect(onChangeSpy).not.toHaveBeenCalled();+ });+});++describe('DropdownMenuRadioGroup / RadioItem', () => {+ it('renders a named group with radios reflecting the selected value', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu button={{label: 'Sort'}}>+ <DropdownMenuRadioGroup+ value="newest"+ onChange={() => {}}+ aria-label="Sort by">+ <DropdownMenuRadioItem value="newest" label="Newest" />+ <DropdownMenuRadioItem value="oldest" label="Oldest" />+ </DropdownMenuRadioGroup>+ </DropdownMenu>,+ );+ await user.click(screen.getByRole('button', {name: /Sort/}));+ expect(+ screen.getByRole('menuitemradio', {name: 'Newest', hidden: true}),+ ).toHaveAttribute('aria-checked', 'true');+ expect(+ screen.getByRole('menuitemradio', {name: 'Oldest', hidden: true}),+ ).toHaveAttribute('aria-checked', 'false');+ expect(+ screen.getByRole('group', {name: 'Sort by', hidden: true}),+ ).toBeInTheDocument();+ });++ it('calls onChange with the selected value', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <DropdownMenu button={{label: 'Sort'}}>+ <DropdownMenuRadioGroup+ value="newest"+ onChange={onChange}+ aria-label="Sort by">+ <DropdownMenuRadioItem value="newest" label="Newest" />+ <DropdownMenuRadioItem value="oldest" label="Oldest" />+ </DropdownMenuRadioGroup>+ </DropdownMenu>,+ );+ await user.click(screen.getByRole('button', {name: /Sort/}));+ await user.click(+ screen.getByRole('menuitemradio', {name: 'Oldest', hidden: true}),+ );+ expect(onChange).toHaveBeenCalledWith('oldest');+ });++ it('throws when a radio item is used outside a group', () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});+ expect(() =>+ render(+ <DropdownMenu button={{label: 'Sort'}}>+ <DropdownMenuRadioItem value="x" label="X" />+ </DropdownMenu>,+ ),+ ).toThrow(/DropdownMenuRadioGroup/);+ spy.mockRestore();+ });+});diff --git a/packages/core/src/DropdownMenu/index.ts b/packages/core/src/DropdownMenu/index.tsindex 91facc50e2..ca399caf90 100644--- a/packages/core/src/DropdownMenu/index.ts+++ b/packages/core/src/DropdownMenu/index.ts@@ -18,7 +18,27 @@ export {type DropdownMenuOption,} from './DropdownMenu';+export {DropdownMenuItem, type DropdownMenuItemProps} from './DropdownMenuItem';++// Selectable items — checkbox (independent) and radio (single-select group).+export {+ DropdownMenuCheckboxItem,+ type DropdownMenuCheckboxItemProps,+} from './DropdownMenuCheckboxItem';+export {+ DropdownMenuRadioGroup,+ type DropdownMenuRadioGroupProps,+} from './DropdownMenuRadioGroup';+export {+ DropdownMenuRadioItem,+ type DropdownMenuRadioItemProps,+} from './DropdownMenuRadioItem';++// Menu-coordination context — public so consumers can build custom menu items+// that read the menu size / close the menu.export {- DropdownMenuItem,- type DropdownMenuItemProps,-} from './DropdownMenuItem';+ DropdownMenuContext,+ useDropdownMenuContext,+ type DropdownMenuContextValue,+ type DropdownMenuSize,+} from './DropdownMenuContext';diff --git a/packages/core/src/DropdownMenu/menuItemRoles.ts b/packages/core/src/DropdownMenu/menuItemRoles.tsnew file mode 100644index 0000000000..7c86772b06--- /dev/null+++ b/packages/core/src/DropdownMenu/menuItemRoles.ts@@ -0,0 +1,22 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file menuItemRoles.ts+ * @output Shared menu-item role set + focus selector.+ * @position Internal; used by DropdownMenu and ContextMenu so their+ * roving-focus, typeahead, and Enter/Space activation stay in sync.+ *+ * Includes the selectable items (menuitemradio/menuitemcheckbox) alongside+ * plain menuitem so checkbox/radio rows are reachable by arrow keys, typeahead,+ * and Enter/Space — not just role="menuitem".+ */++export const MENU_ITEM_ROLES: ReadonlySet<string> = new Set([+ 'menuitem',+ 'menuitemradio',+ 'menuitemcheckbox',+]);++export const MENU_ITEM_SELECTOR: string = [...MENU_ITEM_ROLES]+ .map(role => `[role="${role}"]:not([aria-disabled="true"])`)+ .join(',');