An open source design system that's fully customizable and agent ready
TypeScript
feat(DropdownMenuItem): a row that navigates is a real link (href, target, rel) (#6835)
Christopher Chedeauc3f64eff915e
diff --git a/.changeset/menu-link-rows.md b/.changeset/menu-link-rows.mdnew file mode 100644index 0000000000..42fe8d06d1--- /dev/null+++ b/.changeset/menu-link-rows.md@@ -0,0 +1,15 @@+---+'@astryxdesign/core': patch+---++[feat] DropdownMenuItem takes `href`: a menu row that navigates is a real link.++`DropdownMenuItem` (and a data-mode item) takes `href`, `target` and `rel`.+The row renders as the anchor itself, with `role="menuitem"`, routed through+`LinkProvider`, so a ⌘-click, Ctrl-click or middle click keeps the browser's+meaning and skips `onClick`; a plain click runs `onClick`, closes the menu and+navigates. The touch sheet renders the same item as a link row. `onClick` now+receives the click event. Enter and Space in every menu synthesize a click+that carries the key's modifiers.++@vjeuxdiff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsxindex 4865608ae3..c3b73547f8 100644--- a/apps/storybook/stories/DropdownMenu.stories.tsx+++ b/apps/storybook/stories/DropdownMenu.stories.tsx@@ -1307,3 +1307,40 @@ export const CustomTrigger: Story = {},},};++export const LinkRows: Story = {+ name: 'Rows that navigate (href)',+ render: () => (+ <DropdownMenu button={{label: 'Places'}}>+ <DropdownMenuItem icon={UserIcon} label="Profile" href="/profile" />+ <DropdownMenuItem+ icon={Cog6ToothIcon}+ label="Settings"+ href="/settings"+ onClick={() => console.log('leaving for settings')}+ />+ <DropdownMenuItem+ icon={ShareIcon}+ label="Help center"+ description="Opens in a new tab"+ href="https://example.com/help"+ target="_blank"+ />+ <DropdownMenuDivider />+ <DropdownMenuItem+ icon={TrashIcon}+ label="Delete"+ variant="destructive"+ onClick={() => {}}+ />+ </DropdownMenu>+ ),+ parameters: {+ docs: {+ description: {+ story:+ 'A row whose act is navigation takes an `href` and renders as a real anchor with role="menuitem", routed through LinkProvider. A ⌘-click, Ctrl-click or middle click keeps the browser\'s meaning (a new tab) and skips `onClick`; a plain click runs `onClick`, closes the menu and navigates. Enter and Space synthesize a click that keeps the key\'s modifiers.',+ },+ },+ },+};diff --git a/docs/families/navigation-destinations.md b/docs/families/navigation-destinations.mdindex a7aa97ce37..7663cf6ee0 100644--- a/docs/families/navigation-destinations.md+++ b/docs/families/navigation-destinations.md@@ -23,6 +23,7 @@ verified_by:apps/docsite/src/__tests__/link-navigation.test.ts,packages/core/src/hooks/useClickableContainer.test.tsx,packages/core/src/ClickableCard/ClickableCard.test.tsx,+ packages/core/src/DropdownMenu/DropdownMenu.test.tsx,]members:[@@ -31,6 +32,7 @@ members:component:Button,component:Citation,component:ClickableCard,+ component:DropdownMenuItem,component:Item,component:Link,component:ListItem,@@ -86,7 +88,9 @@ renderers, and callbacks are outside the boundary after Astryx hands overcontrol.- **Current members:** Avatar; BreadcrumbItem; Button link mode; Citation;- ClickableCard; Item; Link; ListItem; Markdown links; NavHeadingMenuItem;+ ClickableCard; DropdownMenuItem link rows (and the data-mode item they render,+ in the pointer menu and the touch sheet); Item; Link; ListItem; Markdown+ links; NavHeadingMenuItem;SideNavHeading and SideNavItem; navigation-mode Tab; Token link mode;TopNavHeading, TopNavItem, TopNavMenu, TopNavMegaMenuItem, andTopNavMegaMenuFeaturedCard; and TreeListItem.diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex bdfc9a33cc..eacaaf42d3 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -60,6 +60,7 @@ import {MENU_ITEM_ROLES,MENU_ITEM_SELECTOR,MENU_BOUNDARY_SELECTOR,+ activateMenuItem,} from '../DropdownMenu/menuItemRoles';import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow';import {useListFocus} from '../hooks/useListFocus';@@ -379,11 +380,11 @@ export function ContextMenu({}, [layer, updateOpenState, usesBottomSheet]);const handleBottomSheetSelect = useCallback(- (item: ContextMenuItemData) => {+ (item: ContextMenuItemData, event: React.MouseEvent) => {if (item.isDisabled) {return;}- item.onClick?.();+ item.onClick?.(event);if (item.hasCloseOnSelect !== false) {closeMenu();}@@ -488,7 +489,9 @@ export function ContextMenu({focused &&MENU_ITEM_ROLES.has(focused.getAttribute('role') ?? '')) {- focused.click();+ // The synthesized click keeps the key's modifiers, so a modified+ // Enter on a link row opens the way a modified click would.+ activateMenuItem(focused, e);}return;}diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjsindex 6cdfaf1180..824105da33 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs@@ -194,7 +194,7 @@ export const docs = {name: 'items',type: 'DropdownMenuOption[]',description:- 'Array of menu entries. Each entry is one of: an action item `{label, onClick?, icon?, description?, endContent?, isDisabled?, variant?, hasCloseOnSelect?, id?}` (variant `"destructive"` renders it in the error color; `endContent` holds trailing content such as a keyboard-shortcut hint; `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]}`.',+ 'Array of menu entries. Each entry is one of: an action item `{label, onClick?, href?, target?, rel?, icon?, description?, endContent?, isDisabled?, variant?, hasCloseOnSelect?, id?}` (`href` makes the row a real link, so a modified click keeps the browser\'s meaning; variant `"destructive"` renders it in the error color; `endContent` holds trailing content such as a keyboard-shortcut hint; `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.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.mdindex 35150a8af3..964b274d3b 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md@@ -22,7 +22,7 @@ verified_by:scripts/check-knowledge.mjs,]modules: [module:DropdownMenu/useMenuPress, module:DropdownMenu/useMenuHover]-families: [family:overlay-dismissal]+families: [family:overlay-dismissal, family:navigation-destinations]design_specs: []architecture:[@@ -93,18 +93,20 @@ released default.## 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 |-| 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 |+| 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 |+| Row destination | `href` (+ `target`, `rel`) on an action item | The row's act is navigation: the row itself is the link (`family:navigation-destinations`). | Pointer action row and Touch action row, compound and data mode | none (an action row) | `component:DropdownMenu` | stable | Blocked schemes follow the family rule; a disabled row has none. |+| FR10 | An action row with `href` MUST render as one anchor carrying `role="menuitem"` (the pointer menu) or the touch sheet's link row, routed through `LinkProvider`; a plain click MUST run `onClick`, then close the menu (`hasCloseOnSelect`), then let the browser navigate; a modified click or middle click MUST be left to the browser and MUST NOT run `onClick`; Enter and Space MUST activate through a synthesized click that carries the key's modifiers. A disabled link row has no `href`. | `component:DropdownMenu/DEC-2`; `family:navigation-destinations` | Proposed; verified in jsdom; owner to confirm DEC-1 |### Allowed variation@@ -119,19 +121,22 @@ 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. |-| 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. |+| 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. |+| Link row | The Pointer action row (or Touch action row) is the anchor; `onClick`, close and navigation run in that order on a plain click. | `target`, `rel`, icon, description and destructive variant vary. |### Transformation and precedence order-- No new presentation-resolution, open-state, item-rendering, positioning, or- styling precedence rule is introduced.+- **ORD2 — Link row activation.** modified click → the browser alone; else+ `onClick` → close (`hasCloseOnSelect`) → the browser navigates.+- No other presentation-resolution, open-state, positioning, or styling+ precedence rule is introduced.### Performance and resources@@ -260,6 +265,7 @@ than adding a DropdownMenu-owned heading target.| 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` |+| FR8, AR2 | `DropdownMenu.test.tsx` "DropdownMenuItem href" suite (pointer menu and bottom sheet) | Plain click, ⌘-click, Enter with modifiers, disabled link row | A row rendering an inner anchor, running `onClick` on a modified click, or a synthesized click dropping the modifiers fails. | `audit:DropdownMenu/behavior` |## Decision log@@ -326,6 +332,22 @@ Rejected: an `as` prop on the Button — an icon button, a chip, an avatar and alist row are not Button variants; a slot component — hides which props mustreach the control.+### DEC-4 — A row that goes somewhere is a link++**Reference:** `component:DropdownMenu/DEC-4`++**Decider:** vjeux, 2026-09-27 (owner confirmation pending)++A menu row whose act is navigation renders as the anchor itself, not a row with+an anchor inside, so a ⌘-click, Ctrl-click or middle click keeps the browser's+meaning and `LinkProvider` routes it; `onClick` runs before navigation on a+plain click and is skipped for a modified one, which the browser owns. The menu+still closes on a modified click — the row acted. Keyboard activation+synthesizes a click carrying the key's modifiers so ⌘-Enter opens a tab.++Rejected: an `onClick` that calls `navigate()` — loses new-tab, middle-click+and the router's prefetch; an inner anchor — two controls in one row.+## Open questionsNone.diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex cb1d5dc87a..1e406d6a6b 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -2667,3 +2667,237 @@ describe('DropdownMenu focus return after a pointer pick', () => {);});});++describe('DropdownMenuItem href', () => {+ it('renders an anchor when given href', async () => {+ const user = userEvent.setup();+ const onClick = vi.fn();+ render(+ <DropdownMenu button={{label: 'Places'}}>+ <DropdownMenuItem+ label="Inbox"+ href="/inbox"+ target="_blank"+ onClick={onClick}+ />+ </DropdownMenu>,+ );+ const row = screen.getByRole('menuitem', {name: 'Inbox', hidden: true});+ expect(row.tagName).toBe('A');+ expect(row).toHaveAttribute('href', '/inbox');+ expect(row).toHaveAttribute('target', '_blank');+ expect(row).toHaveAttribute('rel', 'noopener noreferrer');+ expect(row).toHaveAttribute('tabindex', '-1');+ // The anchor IS the row: no inner anchor or button doubles the control.+ expect(row.querySelector('a, button')).toBeNull();++ await user.click(screen.getByRole('button', {name: /Places/}));+ // onClick runs on the row's click, before the browser navigates, and the+ // row closes the menu after it.+ const order: string[] = [];+ onClick.mockImplementation(() => order.push('onClick'));+ (HTMLElement.prototype.hidePopover as ReturnType<typeof vi.fn>).mockClear();+ fireEvent.click(row);+ expect(order).toEqual(['onClick']);+ expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled();+ });++ it('a modified click is left to the browser', async () => {+ const user = userEvent.setup();+ const onClick = vi.fn();+ render(+ <DropdownMenu button={{label: 'Places'}}>+ <DropdownMenuItem label="Inbox" href="/inbox" onClick={onClick} />+ </DropdownMenu>,+ );+ await user.click(screen.getByRole('button', {name: /Places/}));+ const row = screen.getByRole('menuitem', {name: 'Inbox', hidden: true});++ const event = new MouseEvent('click', {+ bubbles: true,+ cancelable: true,+ metaKey: true,+ });+ row.dispatchEvent(event);+ // Nothing prevents the browser's meaning of a ⌘-click (a new tab), and+ // the row's own handler stays out of it — the browser is acting.+ expect(event.defaultPrevented).toBe(false);+ expect(onClick).not.toHaveBeenCalled();+ });++ it('Enter on an href row synthesizes a click that keeps the key modifiers', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu button={{label: 'Places'}}>+ <DropdownMenuItem label="Inbox" href="/inbox" />+ </DropdownMenu>,+ );+ const trigger = screen.getByRole('button', {name: /Places/});+ trigger.focus();+ await user.keyboard('{Enter}');+ const row = screen.getByRole('menuitem', {name: 'Inbox', hidden: true});+ await waitFor(() => expect(row).toHaveFocus());++ const clicks: MouseEvent[] = [];+ row.addEventListener('click', e => {+ clicks.push(e);+ e.preventDefault();+ });+ fireEvent.keyDown(row, {key: 'Enter', metaKey: true, shiftKey: true});+ expect(clicks).toHaveLength(1);+ expect(clicks[0].metaKey).toBe(true);+ expect(clicks[0].shiftKey).toBe(true);+ expect(clicks[0].ctrlKey).toBe(false);+ });++ it('a data item with href is a real link in the bottom sheet and still closes it', async () => {+ const user = userEvent.setup();+ const onClick = vi.fn();+ render(+ <DropdownMenu+ button={{label: 'Places'}}+ presentation="bottom-sheet"+ items={[+ {label: 'Inbox', href: '/inbox', target: '_blank', onClick},+ {label: 'Rename', onClick: () => {}},+ ]}+ />,+ );+ const trigger = screen.getByRole('button', {name: /Places/});+ await user.click(trigger);+ const row = await screen.findByRole('link', {name: 'Inbox'});+ expect(row).toHaveAttribute('href', '/inbox');+ expect(row).toHaveAttribute('target', '_blank');+ expect(row).toHaveAttribute('rel', 'noopener noreferrer');+ // The plain row stays a button.+ expect(screen.getByRole('button', {name: 'Rename'})).toBeInTheDocument();++ // A plain click runs onClick and closes the sheet (the browser navigates).+ const plain = new MouseEvent('click', {bubbles: true, cancelable: true});+ row.dispatchEvent(plain);+ expect(onClick).toHaveBeenCalledTimes(1);+ expect(plain.defaultPrevented).toBe(false);+ await waitFor(() =>+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),+ );+ });++ it('a modified click on a bottom-sheet link row is left to the browser', async () => {+ const user = userEvent.setup();+ const onClick = vi.fn();+ render(+ <DropdownMenu+ button={{label: 'Places'}}+ presentation="bottom-sheet"+ items={[{label: 'Inbox', href: '/inbox', onClick}]}+ />,+ );+ await user.click(screen.getByRole('button', {name: /Places/}));+ const row = await screen.findByRole('link', {name: 'Inbox'});+ const event = new MouseEvent('click', {+ bubbles: true,+ cancelable: true,+ metaKey: true,+ });+ row.dispatchEvent(event);+ expect(event.defaultPrevented).toBe(false);+ expect(onClick).not.toHaveBeenCalled();+ });++ it('a disabled href row renders no address', () => {+ render(+ <DropdownMenu button={{label: 'Places'}}>+ <DropdownMenuItem label="Inbox" href="/inbox" isDisabled />+ </DropdownMenu>,+ );+ const row = screen.getByRole('menuitem', {name: 'Inbox', hidden: true});+ expect(row.tagName).toBe('A');+ expect(row).not.toHaveAttribute('href');+ expect(row).toHaveAttribute('aria-disabled', 'true');+ });+});++describe("DropdownMenu link rows — the browser's own clicks", () => {+ async function openWithLinkRow(props: {+ onClick?: () => void;+ isDisabled?: boolean;+ }) {+ const user = userEvent.setup();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuItem label="Docs" href="/docs" {...props} />+ </DropdownMenu>,+ );+ const trigger = screen.getByRole('button', {name: 'Actions'});+ await user.click(trigger);+ return {+ trigger,+ row: screen.getByRole('menuitem', {name: 'Docs', hidden: true}),+ };+ }++ const auxClick = (el: Element, button: number) =>+ fireEvent(+ el,+ new MouseEvent('auxclick', {bubbles: true, cancelable: true, button}),+ );++ it('closes the menu on a middle click, which fires auxclick not click', async () => {+ // A middle click never fires `click`, so the row's click handler never+ // saw it: the browser opened the tab and the menu stayed open behind it.+ const onClick = vi.fn();+ const {trigger, row} = await openWithLinkRow({onClick});+ expect(row.tagName).toBe('A');+ expect(trigger).toHaveAttribute('aria-expanded', 'true');++ auxClick(row, 1);++ // The browser does the navigating, so the row's own handler stays out of+ // it exactly as it does for a modified click — but the row acted, so the+ // menu closes.+ expect(onClick).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),+ );+ });++ it('leaves a right click to the context menu', async () => {+ const {trigger, row} = await openWithLinkRow({});++ // Button 2 is the right button: it opens the browser's context menu over+ // the link, and closing the menu out from under it would be wrong.+ auxClick(row, 2);++ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ });++ it('does not navigate a disabled link row on a middle click', async () => {+ const {trigger, row} = await openWithLinkRow({isDisabled: true});++ // A disabled row keeps its place in the tree but carries no address, so+ // there is nothing for the browser to open and the menu stays put.+ expect(row).not.toHaveAttribute('href');+ auxClick(row, 1);+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ });++ it('renders a blocked destination inertly', async () => {+ // A menu row is a place an address can arrive from data. The row's root+ // is the application's link component, so the shared destination rule+ // applies by construction rather than by a check of this component's+ // own: a rejected scheme renders with no href at all and goes nowhere.+ const user = userEvent.setup();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ {/* eslint-disable-next-line @eslint-react/dom-no-script-url -- the test proves this URL never navigates */}+ <DropdownMenuItem label="Trap" href="javascript:window.__fired=true" />+ </DropdownMenu>,+ );+ await user.click(screen.getByRole('button', {name: 'Actions'}));+ const row = screen.getByRole('menuitem', {name: 'Trap', hidden: true});++ expect(row).not.toHaveAttribute('href');+ await user.click(row);+ expect((window as unknown as {__fired?: boolean}).__fired).toBeUndefined();+ });+});diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex 063fbc231a..c243eb1fa9 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -53,6 +53,7 @@ import {MENU_ITEM_ROLES,MENU_ITEM_SELECTOR,MENU_BOUNDARY_SELECTOR,+ activateMenuItem,} from './menuItemRoles';import {DropdownMenuContext,@@ -273,6 +274,9 @@ export interface DropdownMenuItemData extends Pick<| 'description'| 'endContent'| 'hasCloseOnSelect'+ | 'href'+ | 'target'+ | 'rel'> {/*** Stable identity for the row, used as its React key (as on@@ -553,11 +557,11 @@ function DropdownMenuBottomSheet({);const handleSelect = useCallback(- (item: DropdownMenuItemData) => {+ (item: DropdownMenuItemData, event: React.MouseEvent) => {if (item.isDisabled) {return;}- item.onClick?.();+ item.onClick?.(event);if (item.hasCloseOnSelect !== false) {setOpen(false);}@@ -949,7 +953,9 @@ function DropdownMenuPopover({focused &&MENU_ITEM_ROLES.has(focused.getAttribute('role') ?? '')) {- focused.click();+ // The synthesized click keeps the key's modifiers, so a modified+ // Enter on a link row opens the way a modified click would.+ activateMenuItem(focused, e);}return;}diff --git a/packages/core/src/DropdownMenu/DropdownMenuItem.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuItem.doc.mjsindex d956e01eee..1d3d7de5e5 100644--- a/packages/core/src/DropdownMenu/DropdownMenuItem.doc.mjs+++ b/packages/core/src/DropdownMenu/DropdownMenuItem.doc.mjs@@ -32,6 +32,29 @@ export const docs = {type: 'ReactNode',description: 'Secondary description text displayed below the label.',},+ {+ name: 'onClick',+ type: '(event: MouseEvent) => void',+ description:+ "Callback when the item is selected. A keyboard activation arrives as a synthesized click carrying the key's modifiers. On a row with `href` it runs before the browser navigates and is skipped for a modified click (⌘, Ctrl, Shift, Alt, middle button), which is left to the browser.",+ },+ {+ name: 'href',+ type: 'string',+ description:+ 'Address the row navigates to. The row then renders as a real anchor with role="menuitem" (through LinkProvider), so a modified click or a middle click keeps the browser\'s meaning — a new tab — instead of running onClick.',+ },+ {+ name: 'target',+ type: "'_blank' | '_self'",+ description: 'Link target. Only used with href.',+ },+ {+ name: 'rel',+ type: 'string',+ description:+ 'Link relationship. noopener noreferrer is added for target="_blank". Only used with href.',+ },{name: 'endContent',type: 'ReactNode',@@ -88,6 +111,28 @@ export const docsZh = {type: 'ReactNode',description: '显示在标签下方的次要描述文本。',},+ {+ name: 'onClick',+ type: '(event: MouseEvent) => void',+ description:+ '选中该项时的回调。键盘激活会以携带修饰键的合成点击到达;带 href 的行会在浏览器导航前运行,带修饰键的点击则交给浏览器处理。',+ },+ {+ name: 'href',+ type: 'string',+ description:+ '该行导航到的地址。此时该行渲染为带 role="menuitem" 的真实链接,带修饰键的点击或中键点击保留浏览器语义(新标签页)。',+ },+ {+ name: 'target',+ type: "'_blank' | '_self'",+ description: '链接目标。仅与 href 一起使用。',+ },+ {+ name: 'rel',+ type: 'string',+ description: '链接关系。target="_blank" 时自动加入 noopener noreferrer。',+ },{name: 'endContent',type: 'ReactNode',@@ -96,7 +141,8 @@ export const docsZh = {{name: 'hasCloseOnSelect',type: 'boolean',- description: '激活该项时是否关闭菜单。若操作要在该项上就地反馈结果,请设为 false。',+ description:+ '激活该项时是否关闭菜单。若操作要在该项上就地反馈结果,请设为 false。',default: 'true',},{@@ -128,6 +174,11 @@ export const docsDense = {icon: 'icon before label',label: 'primary label text',description: 'secondary text below label',+ onClick:+ 'selection callback (event); keyboard activation = synthesized click w/ modifiers; skipped for a modified click on an href row',+ href: 'row is a real anchor w/ role=menuitem; modified/middle click keeps browser meaning',+ target: "link target ('_blank' | '_self'), with href",+ rel: 'link rel; noopener noreferrer added for _blank',endContent: 'additional content after label+description',hasCloseOnSelect:'false keeps the menu open on activation (in-place result on the item)',diff --git a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuItem.tsxindex 0eab43234c..5c1a698919 100644--- a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx@@ -13,6 +13,7 @@* Composes Item for the shared start content + label + description + end content layout.* Passes role="menuitem" so Item puts onClick on the root div instead of* creating an invisible button (keyboard access is provided by the parent menu).+ * With an `href` the root is a real anchor carrying the role.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/DropdownMenu/DropdownMenu.doc.mjs@@ -23,10 +24,16 @@* - /packages/cli/assets/templates/blocks/components/DropdownMenu/ (showcase blocks)*/-import {useCallback, type PointerEvent, type ReactNode} from 'react';+import {+ useCallback,+ type MouseEvent,+ type PointerEvent,+ type ReactNode,+} from 'react';import * as stylex from '@stylexjs/stylex';import {renderIconSlot, type IconType} from '../Icon';import {Item} from '../Item';+import {useLinkComponent} from '../Link/useLinkComponent';import {colorVars,spacingVars,@@ -37,6 +44,7 @@ import {mergeProps} from '../utils';import type {BaseProps} from '../BaseProps';import {useDropdownMenuContext} from './DropdownMenuContext';import {focusMenuItemOnHover} from './menuItemHover';+import {isModifiedClick} from './menuItemRoles';import {themeProps} from '../utils/themeProps';const menuItemStyles = stylex.create({@@ -106,8 +114,27 @@ export interface DropdownMenuItemProps extends Pick<label: ReactNode;/** Secondary description text displayed below the label. */description?: ReactNode;- /** Callback when the item is selected. */- onClick?: () => void;+ /**+ * Callback when the item is selected. Receives the activating click; a+ * keyboard activation (Enter / Space) arrives as a synthesized click that+ * carries the key's modifiers. On a row with an `href` it runs before the+ * browser navigates, and is skipped for a modified click (⌘, Ctrl, Shift,+ * Alt, a middle button), which is left to the browser.+ */+ onClick?: (event: MouseEvent) => void;+ /**+ * Address the row navigates to. The row then renders as a real anchor with+ * `role="menuitem"` — a modified click and a middle click keep the+ * browser's meaning (a new tab), and `LinkProvider` routes it.+ */+ href?: string;+ /** Link target. Only used with `href`. */+ target?: '_blank' | '_self';+ /**+ * Link relationship. `noopener noreferrer` is added for `target="_blank"`.+ * Only used with `href`.+ */+ rel?: string;/** Whether the item is disabled. @default false */isDisabled?: boolean;/** Additional content to render after the label/description. */@@ -153,6 +180,9 @@ export function DropdownMenuItem({label,description,onClick,+ href,+ target,+ rel,isDisabled = false,endContent,hasCloseOnSelect = true,@@ -165,15 +195,48 @@ export function DropdownMenuItem({const ctx = useDropdownMenuContext();const menuSize = ctx?.menuSize ?? 'md';- const handleClick = useCallback(() => {- if (isDisabled) {- return;- }- onClick?.();- if (hasCloseOnSelect) {- ctx?.closeMenu();- }- }, [isDisabled, onClick, hasCloseOnSelect, ctx]);+ const handleClick = useCallback(+ (event: MouseEvent) => {+ if (isDisabled) {+ // A disabled link row has no href, but a stray click must still not+ // navigate anywhere.+ event.preventDefault();+ return;+ }+ // A modified click on a link row is the browser's: it opens the+ // address its own way, so the row's handler stays out of it.+ // The menu still closes: the row acted.+ const isBrowserNavigation = href != null && isModifiedClick(event);+ if (!isBrowserNavigation) {+ onClick?.(event);+ }+ if (hasCloseOnSelect) {+ ctx?.closeMenu();+ }+ },+ [isDisabled, href, onClick, hasCloseOnSelect, ctx],+ );++ // A middle click fires `auxclick`, never `click`, so the row's own click+ // handler never sees it: the tab opened and the menu stayed open behind+ // it. The browser does the navigating; the row only has to close.+ const handleAuxClick = useCallback(+ (event: MouseEvent) => {+ if (isDisabled) {+ event.preventDefault();+ return;+ }+ // Button 1 is the middle button. A right click opens the context menu+ // and must leave the row's menu alone.+ if (href == null || event.button !== 1) {+ return;+ }+ if (hasCloseOnSelect) {+ ctx?.closeMenu();+ }+ },+ [isDisabled, href, hasCloseOnSelect, ctx],+ );const handlePointerMove = useCallback((e: PointerEvent<HTMLElement>) => focusMenuItemOnHover(e, isDisabled),@@ -182,9 +245,16 @@ export function DropdownMenuItem({const isDestructive = variant === 'destructive';+ const LinkComponent = useLinkComponent();+return (<Itemref={ref}+ // A row that navigates IS the link: its root is the application's+ // anchor, so a modified click, a middle click, copying the address and+ // the status bar all keep the browser's meaning. A row without an+ // address keeps the default root.+ as={href != null ? LinkComponent : undefined}role="menuitem"tabIndex={isDisabled ? undefined : -1}onPointerMove={handlePointerMove}@@ -200,6 +270,10 @@ export function DropdownMenuItem({description={description}endContent={endContent}onClick={handleClick}+ onAuxClick={handleAuxClick}+ href={href}+ target={target}+ rel={rel}isDisabled={isDisabled}xstyle={[menuItemStyles.root,diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsxindex f514a317ff..a5c9d21aa5 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx@@ -77,6 +77,7 @@ import {MENU_ITEM_ROLES,MENU_ITEM_SELECTOR,MENU_BOUNDARY_SELECTOR,+ activateMenuItem,} from './menuItemRoles';import {DropdownMenuContext,@@ -492,7 +493,9 @@ export function DropdownMenuSubMenu(focused &&MENU_ITEM_ROLES.has(focused.getAttribute('role') ?? '')) {- focused.click();+ // The synthesized click keeps the key's modifiers, so a modified+ // Enter on a link row opens the way a modified click would.+ activateMenuItem(focused, e);}return;}diff --git a/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx b/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsxindex 4ee8994c3e..df89ccf461 100644--- a/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx+++ b/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx@@ -9,7 +9,7 @@* @position Shared implementation for menu bottom-sheet presentations*/-import {useRef, type ReactElement} from 'react';+import React, {useRef, type ReactElement} from 'react';import * as stylex from '@stylexjs/stylex';import {Divider} from '../Divider';import {Heading} from '../Heading';@@ -20,6 +20,7 @@ import {colorVars, spacingVars} from '../theme/tokens.stylex';import {rtlStyles} from '../utils';import {getInteractionModality} from '../utils/interactionModality';import type {DropdownMenuItemData, DropdownMenuOption} from './DropdownMenu';+import {isModifiedClick} from './menuItemRoles';/** The action rows: ListItem renders its action as a button (or a link). */const SHEET_ROW_SELECTOR = 'button:not(:disabled), a[href]';@@ -62,7 +63,7 @@ export function MenuBottomSheetActionList({onOpenSubmenu,}: {items: DropdownMenuOption[];- onSelect: (item: DropdownMenuItemData) => void;+ onSelect: (item: DropdownMenuItemData, event: React.MouseEvent) => void;onOpenSubmenu: (item: DropdownMenuItemData) => void;}) {const listRef = useRef<HTMLUListElement>(null);@@ -80,6 +81,27 @@ export function MenuBottomSheetActionList({): ReactElement => {const isSubmenu = item.items != null && item.items.length > 0;const isDestructive = item.variant === 'destructive';+ const isLink = !isSubmenu && item.href != null;++ const handleActivate = (event: React.MouseEvent) => {+ if (isLink && item.isDisabled) {+ // A disabled link row goes nowhere.+ event.preventDefault();+ return;+ }+ if (getInteractionModality() === 'pointer') {+ (event.currentTarget as HTMLElement).blur();+ }+ if (isSubmenu) {+ onOpenSubmenu(item);+ } else if (isLink && isModifiedClick(event)) {+ // A modified click on a link row is the browser's (a new tab); the+ // row's handler stays out of it, the sheet still closes.+ onSelect({...item, onClick: undefined}, event);+ } else {+ onSelect(item, event);+ }+ };return (<ListItem@@ -107,16 +129,15 @@ export function MenuBottomSheetActionList({)}isDisabled={item.isDisabled}- onClick={event => {- if (getInteractionModality() === 'pointer') {- (event.currentTarget as HTMLElement).blur();- }- if (isSubmenu) {- onOpenSubmenu(item);- } else {- onSelect(item);- }- }}+ // A row with an address is a real link in the sheet too: the+ // ListItem renders its anchor, and the row's select handler rides the+ // capture phase — ListItem leaves a click on its inner anchor to the+ // anchor, so `onClick` alone would never run for a link row.+ href={isLink ? item.href : undefined}+ target={isLink ? item.target : undefined}+ rel={isLink ? item.rel : undefined}+ onClick={isLink ? undefined : handleActivate}+ onClickCapture={isLink ? handleActivate : undefined}xstyle={isDestructive && styles.destructiveAction}/>);diff --git a/packages/core/src/DropdownMenu/menuItemRoles.ts b/packages/core/src/DropdownMenu/menuItemRoles.tsindex 1531de8cee..570da61f1f 100644--- a/packages/core/src/DropdownMenu/menuItemRoles.ts+++ b/packages/core/src/DropdownMenu/menuItemRoles.ts@@ -2,7 +2,7 @@/*** @file menuItemRoles.ts- * @output Shared menu-item role set + focus selector.+ * @output Shared menu-item role set + focus selector + keyboard activation.* @position Internal; used by DropdownMenu and ContextMenu so their* roving-focus, typeahead, and Enter/Space activation stay in sync.*@@ -29,3 +29,47 @@ export const MENU_ITEM_SELECTOR: string = [...MENU_ITEM_ROLES]* level scopes item collection and key handling to its own container.*/export const MENU_BOUNDARY_SELECTOR = '[role="menu"]';++/**+ * Whether a click carries a modifier or a non-primary button: on a row that+ * is a link the browser gives it a meaning of its own (a new tab, a+ * download), which the row must leave alone.+ */+export function isModifiedClick(event: {+ metaKey: boolean;+ ctrlKey: boolean;+ shiftKey: boolean;+ altKey: boolean;+ button: number;+}): boolean {+ return (+ event.metaKey ||+ event.ctrlKey ||+ event.shiftKey ||+ event.altKey ||+ event.button !== 0+ );+}++/**+ * Activate a menu row from the keyboard (Enter / Space): a synthesized click+ * that carries the key's modifiers, so a ⌘-Enter on a row that is a link opens+ * it the way a ⌘-click would. `detail` stays 0, the mark of a+ * non-pointer activation.+ */+export function activateMenuItem(+ row: HTMLElement,+ key: {metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean},+): void {+ row.dispatchEvent(+ new MouseEvent('click', {+ bubbles: true,+ cancelable: true,+ composed: true,+ metaKey: key.metaKey,+ ctrlKey: key.ctrlKey,+ shiftKey: key.shiftKey,+ altKey: key.altKey,+ }),+ );+}diff --git a/packages/core/src/Item/Item.doc.mjs b/packages/core/src/Item/Item.doc.mjsindex 084afb38f3..58d5614428 100644--- a/packages/core/src/Item/Item.doc.mjs+++ b/packages/core/src/Item/Item.doc.mjs@@ -8,7 +8,17 @@ export const docs = {group: 'Item',category: 'Table & List',isHiddenFromOverview: true,- keywords: ["item","list-item","media-object","row","cell","entity","contact","notification","preview"],+ keywords: [+ 'item',+ 'list-item',+ 'media-object',+ 'row',+ 'cell',+ 'entity',+ 'contact',+ 'notification',+ 'preview',+ ],playground: {defaults: {label: 'Item label',@@ -16,46 +26,186 @@ export const docs = {},},theming: {- targets: [- {className: 'astryx-item', visualProps: ['density', 'align']},- ],+ targets: [{className: 'astryx-item', visualProps: ['density', 'align']}],vars: [- {name: '--_item-label-color', description: 'Color of the label line. Unset by default (the label uses the primary text token); a parent sets it to recolor the label it renders, as the destructive dropdown/context menu item does.', default: 'var(--color-text-primary)', private: true},- {name: '--_item-description-color', description: 'Companion to --_item-label-color for the secondary description line.', default: 'var(--color-text-secondary)', private: true},- {name: '--_item-inset-inline', description: 'Inline inset of the row. Item derives its paddingInline from this variable, and List reads it to cancel the inset when edgeCompensation="inline". Set paddingInline on `item` in a theme and both stay in sync.', default: 'var(--spacing-2) (var(--spacing-3) for density="spacious")', private: true},- ],- derived: [- {property: 'paddingInline', vars: ['--_item-inset-inline']},+ {+ name: '--_item-label-color',+ description:+ 'Color of the label line. Unset by default (the label uses the primary text token); a parent sets it to recolor the label it renders, as the destructive dropdown/context menu item does.',+ default: 'var(--color-text-primary)',+ private: true,+ },+ {+ name: '--_item-description-color',+ description:+ 'Companion to --_item-label-color for the secondary description line.',+ default: 'var(--color-text-secondary)',+ private: true,+ },+ {+ name: '--_item-inset-inline',+ description:+ 'Inline inset of the row. Item derives its paddingInline from this variable, and List reads it to cancel the inset when edgeCompensation="inline". Set paddingInline on `item` in a theme and both stay in sync.',+ default: 'var(--spacing-2) (var(--spacing-3) for density="spacious")',+ private: true,+ },],+ derived: [{property: 'paddingInline', vars: ['--_item-inset-inline']}],},components: [{name: 'Item',displayName: 'Item',- description: 'A universal item primitive that unifies the "start content + label + description + end content" layout pattern. Use as a building block for list items, menu items, contact rows, notifications, and more.',+ description:+ 'A universal item primitive that unifies the "start content + label + description + end content" layout pattern. Use as a building block for list items, menu items, contact rows, notifications, and more.',props: [- {name: 'label', type: 'ReactNode', description: 'Primary text identifying this item. Accepts string (auto-truncated) or ReactNode (for rich content).', required: true},- {name: 'marker', type: 'ReactNode', description: 'Marker rendered before startContent as a direct flex child. Use for list bullets/counters that need custom baseline alignment.'},- {name: 'startContent', type: 'ReactNode', description: 'Content rendered before the label/description area, such as an icon, avatar, or checkbox.', slotElements: [{__element: 'Avatar', props: {name: 'Ada Lovelace', size: 'sm'}}, {__element: 'Icon', props: {icon: 'info', size: 'sm', color: 'secondary'}}]},- {name: 'description', type: 'ReactNode', description: 'Secondary text: subtitle, description, or supporting info.'},- {name: 'endContent', type: 'ReactNode', description: 'Content rendered after the label/description area, such as badges, metadata, timestamps, or action buttons.', slotElements: [{__element: 'Badge', props: {label: 3}}, {__element: 'Text', props: {color: 'secondary'}, children: '2h ago'}]},- {name: 'as', type: "'div' | 'li' | 'span'", description: 'HTML element to render as the root.', default: "'div'"},- {name: 'align', type: "'center' | 'start'", description: 'Vertical alignment of start/end content slots.', default: "'center'"},- {name: 'density', type: "'compact' | 'balanced' | 'spacious'", description: 'Spacing density. "compact" uses 4px block padding, "balanced" uses 8px, and "spacious" uses 12px block and inline padding.', default: "'balanced'"},- {name: 'labelLines', type: 'number', description: 'Max lines before label truncates with ellipsis.'},- {name: 'descriptionLines', type: 'number', description: 'Max lines before description truncates with ellipsis.'},- {name: 'layout', type: "'stacked' | 'inline'", description: 'How the label and description sit together. stacked puts the description on its own line below the label; inline keeps both on one line, description ellipsizing first, so the row fits a fixed-height host.', default: "'stacked'"},- {name: 'onClick', type: '(event: MouseEvent) => void', description: 'Click handler. Makes the item clickable with button semantics.'},- {name: 'interactiveRef', type: 'RefObject<HTMLElement | null>', description: 'Ref to a nested control (e.g. a checkbox in startContent) that owns the item\'s keyboard access and action. The row becomes an enlarged click/tap target that delegates surface clicks to it (useClickableContainer) and renders no invisible button/anchor, so the row adds no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href; those are ignored when set.'},- {name: 'href', type: 'string', description: 'Link URL. Makes the item a link via an invisible anchor element. The destination follows the shared navigation rule described on the Link `href` prop.'},- {name: 'target', type: "'_blank' | '_self'", description: 'Link target. Only used with href. target="_blank" automatically adds noopener noreferrer.'},- {name: 'rel', type: 'string', description: 'Link relationship tokens. noopener noreferrer are merged automatically for target="_blank".'},- {name: 'isHighlighted', type: 'boolean', description: 'Highlighted state (hover/keyboard focus appearance).', default: 'false'},- {name: 'isSelected', type: 'boolean', description: 'Selected state.', default: 'false'},- {name: 'isDisabled', type: 'boolean', description: 'Disabled state.', default: 'false'},- {name: 'ref', type: 'React.Ref<HTMLDivElement>', description: 'Ref forwarded to the root element.'},- {name: 'xstyle', type: 'StyleXStyles', description: 'StyleX styles for layout customization. Must be a stylex.create() value.'},- {name: 'data-testid', type: 'string', description: 'Test selector for automated testing frameworks.'},+ {+ name: 'label',+ type: 'ReactNode',+ description:+ 'Primary text identifying this item. Accepts string (auto-truncated) or ReactNode (for rich content).',+ required: true,+ },+ {+ name: 'marker',+ type: 'ReactNode',+ description:+ 'Marker rendered before startContent as a direct flex child. Use for list bullets/counters that need custom baseline alignment.',+ },+ {+ name: 'startContent',+ type: 'ReactNode',+ description:+ 'Content rendered before the label/description area, such as an icon, avatar, or checkbox.',+ slotElements: [+ {__element: 'Avatar', props: {name: 'Ada Lovelace', size: 'sm'}},+ {+ __element: 'Icon',+ props: {icon: 'info', size: 'sm', color: 'secondary'},+ },+ ],+ },+ {+ name: 'description',+ type: 'ReactNode',+ description:+ 'Secondary text: subtitle, description, or supporting info.',+ },+ {+ name: 'endContent',+ type: 'ReactNode',+ description:+ 'Content rendered after the label/description area, such as badges, metadata, timestamps, or action buttons.',+ slotElements: [+ {__element: 'Badge', props: {label: 3}},+ {+ __element: 'Text',+ props: {color: 'secondary'},+ children: '2h ago',+ },+ ],+ },+ {+ name: 'as',+ type: "'div' | 'li' | 'span' | ElementType",+ description:+ "What the root renders as: an HTML element, or a component for a caller that needs the root to be something else. A menu row that navigates passes the application's link component here, so the row's root IS the anchor. Give a component only when the row carries a role, and only when no interactive node sits in startContent or endContent.",+ default: "'div'",+ },+ {+ name: 'align',+ type: "'center' | 'start'",+ description: 'Vertical alignment of start/end content slots.',+ default: "'center'",+ },+ {+ name: 'density',+ type: "'compact' | 'balanced' | 'spacious'",+ description:+ 'Spacing density. "compact" uses 4px block padding, "balanced" uses 8px, and "spacious" uses 12px block and inline padding.',+ default: "'balanced'",+ },+ {+ name: 'labelLines',+ type: 'number',+ description: 'Max lines before label truncates with ellipsis.',+ },+ {+ name: 'descriptionLines',+ type: 'number',+ description: 'Max lines before description truncates with ellipsis.',+ },+ {+ name: 'layout',+ type: "'stacked' | 'inline'",+ description:+ 'How the label and description sit together. stacked puts the description on its own line below the label; inline keeps both on one line, description ellipsizing first, so the row fits a fixed-height host.',+ default: "'stacked'",+ },+ {+ name: 'onClick',+ type: '(event: MouseEvent) => void',+ description:+ 'Click handler. Makes the item clickable with button semantics.',+ },+ {+ name: 'interactiveRef',+ type: 'RefObject<HTMLElement | null>',+ description:+ "Ref to a nested control (e.g. a checkbox in startContent) that owns the item's keyboard access and action. The row becomes an enlarged click/tap target that delegates surface clicks to it (useClickableContainer) and renders no invisible button/anchor, so the row adds no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href; those are ignored when set.",+ },+ {+ name: 'href',+ type: 'string',+ description:+ 'Link URL. Makes the item a link via an invisible anchor element. A row whose root is already a link component (see `as`) carries the address on that root instead, and no invisible anchor is rendered.',+ },+ {+ name: 'target',+ type: "'_blank' | '_self'",+ description:+ 'Link target. Only used with href. target="_blank" automatically adds noopener noreferrer.',+ },+ {+ name: 'rel',+ type: 'string',+ description:+ 'Link relationship tokens. noopener noreferrer are merged automatically for target="_blank".',+ },+ {+ name: 'isHighlighted',+ type: 'boolean',+ description: 'Highlighted state (hover/keyboard focus appearance).',+ default: 'false',+ },+ {+ name: 'isSelected',+ type: 'boolean',+ description: 'Selected state.',+ default: 'false',+ },+ {+ name: 'isDisabled',+ type: 'boolean',+ description: 'Disabled state.',+ default: 'false',+ },+ {+ name: 'ref',+ type: 'React.Ref<HTMLDivElement>',+ description: 'Ref forwarded to the root element.',+ },+ {+ name: 'xstyle',+ type: 'StyleXStyles',+ description:+ 'StyleX styles for layout customization. Must be a stylex.create() value.',+ },+ {+ name: 'data-testid',+ type: 'string',+ description: 'Test selector for automated testing frameworks.',+ },],},],@@ -63,20 +213,70 @@ export const docs = {description:'A single, flexible item primitive that unifies the "start content + label + description + end content" pattern across Astryx. Use it wherever you need a structured row: dropdown menus, selectors, contact lists, notifications, file browsers, and activity feeds.',bestPractices: [- {guidance: true, description: 'Use named slots (startContent, label, description, endContent) for the common layout. These cover the 80% case.'},- {guidance: true, description: 'Use density="compact" for menus and dense lists, "balanced" for standard rows, and "spacious" for roomier layouts.'},- {guidance: true, description: 'Set labelLines and descriptionLines to control truncation when content length varies.'},- {guidance: true, description: 'Use align="start" when start or end content is taller than a single line of text.'},- {guidance: false, description: "Don't nest interactive elements (buttons, links) inside an interactive Item; it creates confusing focus and click targets."},- {guidance: false, description: "Don't use Item for navigation between views; use proper navigation components instead."},- {guidance: false, description: "Don't add read/unread or inbox-specific behavior directly; compose a thin wrapper like PreviewItem instead."},+ {+ guidance: true,+ description:+ 'Use named slots (startContent, label, description, endContent) for the common layout. These cover the 80% case.',+ },+ {+ guidance: true,+ description:+ 'Use density="compact" for menus and dense lists, "balanced" for standard rows, and "spacious" for roomier layouts.',+ },+ {+ guidance: true,+ description:+ 'Set labelLines and descriptionLines to control truncation when content length varies.',+ },+ {+ guidance: true,+ description:+ 'Use align="start" when start or end content is taller than a single line of text.',+ },+ {+ guidance: false,+ description:+ "Don't nest interactive elements (buttons, links) inside an interactive Item; it creates confusing focus and click targets.",+ },+ {+ guidance: false,+ description:+ "Don't use Item for navigation between views; use proper navigation components instead.",+ },+ {+ guidance: false,+ description:+ "Don't add read/unread or inbox-specific behavior directly; compose a thin wrapper like PreviewItem instead.",+ },],anatomy: [- {name: 'Marker', required: false, description: 'Optional list bullet/counter rendered before start content.'},- {name: 'Start content', required: false, description: 'Leading visual: avatar, icon, image, or checkbox.'},- {name: 'Label', required: true, description: 'Primary text identifying the item.'},- {name: 'Description', required: false, description: 'Secondary supporting text below the label.'},- {name: 'End content', required: false, description: 'End-aligned content: badges, timestamps, or action buttons.'},+ {+ name: 'Marker',+ required: false,+ description:+ 'Optional list bullet/counter rendered before start content.',+ },+ {+ name: 'Start content',+ required: false,+ description: 'Leading visual: avatar, icon, image, or checkbox.',+ },+ {+ name: 'Label',+ required: true,+ description: 'Primary text identifying the item.',+ },+ {+ name: 'Description',+ required: false,+ description: 'Secondary supporting text below the label.',+ },+ {+ name: 'End content',+ required: false,+ description:+ 'End-aligned content: badges, timestamps, or action buttons.',+ },],},};@@ -87,23 +287,29 @@ export const docsZh = {{name: 'Item',displayName: 'Item',- description: '通用项目原语,统一 "起始内容 + 标签 + 描述 + 结束内容" 布局模式。用作列表项、菜单项、联系人行、通知等的构建块。',+ description:+ '通用项目原语,统一 "起始内容 + 标签 + 描述 + 结束内容" 布局模式。用作列表项、菜单项、联系人行、通知等的构建块。',propDescriptions: {- label: '标识此项目的主要文本。接受字符串(自动截断)或 ReactNode(用于富内容)。',- marker: '在 startContent 之前渲染的标记,作为直接 flex 子元素。用于需要自定义基线对齐的列表项目符号/计数器。',+ label:+ '标识此项目的主要文本。接受字符串(自动截断)或 ReactNode(用于富内容)。',+ marker:+ '在 startContent 之前渲染的标记,作为直接 flex 子元素。用于需要自定义基线对齐的列表项目符号/计数器。',startContent: '在标签/描述区域之前渲染的内容,例如图标、头像或复选框。',description: '次要文本:副标题、描述或辅助信息。',- endContent: '在标签/描述区域之后渲染的内容,例如徽章、元数据、时间戳或操作按钮。',+ endContent:+ '在标签/描述区域之后渲染的内容,例如徽章、元数据、时间戳或操作按钮。',as: '根元素的 HTML 元素。',align: '起始/结束内容插槽的垂直对齐方式。',- density: '间距密度。"compact" 使用 4px 块内距,"balanced" 使用 8px,"spacious" 使用 12px 块内距和内联内距。',+ density:+ '间距密度。"compact" 使用 4px 块内距,"balanced" 使用 8px,"spacious" 使用 12px 块内距和内联内距。',labelLines: '标签截断前的最大行数。',descriptionLines: '描述截断前的最大行数。',onClick: '点击处理函数。使项目可点击,具有按钮语义。',interactiveRef:'指向嵌套控件(如 startContent 中的复选框)的 ref,该控件承载项目的键盘访问和操作。行成为更大的点击/触摸目标,将表面点击委托给该控件(useClickableContainer),且不渲染不可见按钮/锚点,因此行不会增加第二个 Tab 停留点(WCAG 4.1.2)。与 onClick/href 互斥——设置后二者将被忽略。',href: '链接 URL。通过不可见锚点元素使项目成为链接。',- target: '链接目标。仅与 href 一起使用。target="_blank" 会自动添加 noopener noreferrer。',+ target:+ '链接目标。仅与 href 一起使用。target="_blank" 会自动添加 noopener noreferrer。',rel: '链接关系标记。target="_blank" 会自动合并 noopener noreferrer。',isHighlighted: '高亮状态(悬停/键盘焦点外观)。',isSelected: '选中状态。',@@ -118,59 +324,126 @@ export const docsZh = {description:'通用项目原语,统一 Astryx 中 "起始内容 + 标签 + 描述 + 结束内容" 的布局模式。适用于下拉菜单、选择器、联系人列表、通知、文件浏览器和活动流等场景。',bestPractices: [- {guidance: true, description: '使用命名插槽(startContent、label、description、endContent)处理常见布局。'},- {guidance: true, description: '菜单和密集列表使用 density="compact",标准行使用 "balanced",宽松布局使用 "spacious"。'},- {guidance: true, description: '设置 labelLines 和 descriptionLines 控制内容长度不定时的截断。'},- {guidance: true, description: '当起始或结束内容高于单行文本时使用 align="start"。'},- {guidance: false, description: '不要在交互式 Item 内嵌套交互元素(按钮、链接)。'},- {guidance: false, description: '不要使用 Item 进行视图间导航:使用适当的导航组件。'},- {guidance: false, description: '不要直接添加已读/未读行为:组合一个薄包装器如 PreviewItem。'},+ {+ guidance: true,+ description:+ '使用命名插槽(startContent、label、description、endContent)处理常见布局。',+ },+ {+ guidance: true,+ description:+ '菜单和密集列表使用 density="compact",标准行使用 "balanced",宽松布局使用 "spacious"。',+ },+ {+ guidance: true,+ description:+ '设置 labelLines 和 descriptionLines 控制内容长度不定时的截断。',+ },+ {+ guidance: true,+ description: '当起始或结束内容高于单行文本时使用 align="start"。',+ },+ {+ guidance: false,+ description: '不要在交互式 Item 内嵌套交互元素(按钮、链接)。',+ },+ {+ guidance: false,+ description: '不要使用 Item 进行视图间导航:使用适当的导航组件。',+ },+ {+ guidance: false,+ description:+ '不要直接添加已读/未读行为:组合一个薄包装器如 PreviewItem。',+ },],anatomy: [- {name: '标记', required: false, description: '在起始内容之前渲染的可选列表项目符号/计数器。'},- {name: '起始内容', required: false, description: '前导视觉:头像、图标、图片或复选框。'},+ {+ name: '标记',+ required: false,+ description: '在起始内容之前渲染的可选列表项目符号/计数器。',+ },+ {+ name: '起始内容',+ required: false,+ description: '前导视觉:头像、图标、图片或复选框。',+ },{name: '标签', required: true, description: '标识项目的主要文本。'},{name: '描述', required: false, description: '标签下方的次要辅助文本。'},- {name: '结束内容', required: false, description: '末端对齐内容:徽章、时间戳或操作按钮。'},+ {+ name: '结束内容',+ required: false,+ description: '末端对齐内容:徽章、时间戳或操作按钮。',+ },],},};/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */export const docsDense = {- description: 'universal item primitive w/ startContent+label+description+endContent layout. building block for list items, menu items, contacts, notifications',+ description:+ 'universal item primitive w/ startContent+label+description+endContent layout. building block for list items, menu items, contacts, notifications',usage: {description:'Flexible item primitive unifying the "start content + label + description + end content" pattern. Use for structured rows in menus, lists, contacts, notifications, file browsers.',bestPractices: [- {guidance: true, description: 'Named slots (startContent, label, description, endContent) for the 80% case.'},- {guidance: true, description: 'density="compact" for menus/dense lists, "balanced" for standard rows, "spacious" for roomier layouts.'},- {guidance: true, description: 'labelLines/descriptionLines for truncation control.'},- {guidance: true, description: 'align="start" when start/end content is taller than one text line.'},- {guidance: false, description: "Don't nest interactive elements inside interactive Item."},- {guidance: false, description: "Don't use for view navigation; use nav components."},- {guidance: false, description: "Don't add inbox-specific behavior; compose a wrapper."},+ {+ guidance: true,+ description:+ 'Named slots (startContent, label, description, endContent) for the 80% case.',+ },+ {+ guidance: true,+ description:+ 'density="compact" for menus/dense lists, "balanced" for standard rows, "spacious" for roomier layouts.',+ },+ {+ guidance: true,+ description: 'labelLines/descriptionLines for truncation control.',+ },+ {+ guidance: true,+ description:+ 'align="start" when start/end content is taller than one text line.',+ },+ {+ guidance: false,+ description: "Don't nest interactive elements inside interactive Item.",+ },+ {+ guidance: false,+ description: "Don't use for view navigation; use nav components.",+ },+ {+ guidance: false,+ description: "Don't add inbox-specific behavior; compose a wrapper.",+ },],},components: [{name: 'Item',displayName: 'Item',- description: 'universal item primitive w/ startContent+label+description+endContent layout',+ description:+ 'universal item primitive w/ startContent+label+description+endContent layout',propDescriptions: {- label: 'Primary text. String auto-truncates; ReactNode for rich content.',+ label:+ 'Primary text. String auto-truncates; ReactNode for rich content.',marker: 'List bullet/counter before startContent as direct flex child.',- startContent: 'Content before label/description: avatar, icon, checkbox, ReactNode.',+ startContent:+ 'Content before label/description: avatar, icon, checkbox, ReactNode.',description: 'Secondary text below label.',- endContent: 'Content after label/description: badges, timestamps, actions.',+ endContent:+ 'Content after label/description: badges, timestamps, actions.',as: 'Root HTML element.',align: 'Vertical alignment of start/end content slots.',- density: 'Spacing: "compact" (4px), "balanced" (8px), or "spacious" (12px).',+ density:+ 'Spacing: "compact" (4px), "balanced" (8px), or "spacious" (12px).',labelLines: 'Max label lines before truncation.',descriptionLines: 'Max description lines before truncation.',onClick: 'Click handler; enables button semantics.',interactiveRef:- 'Ref to a nested control that owns the item\'s keyboard access/action; row delegates surface clicks to it (useClickableContainer), no invisible button/anchor, no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href.',+ "Ref to a nested control that owns the item's keyboard access/action; row delegates surface clicks to it (useClickableContainer), no invisible button/anchor, no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href.",href: 'Link URL; enables anchor semantics. Follows the shared navigation rule (see Link href).',target:'Link target, only with href. target="_blank" auto-adds noopener noreferrer.',diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsxindex 99d9de31c2..e0d8194194 100644--- a/packages/core/src/Item/Item.tsx+++ b/packages/core/src/Item/Item.tsx@@ -50,10 +50,18 @@ export interface ItemProps extends BaseProps<HTMLElement> {ref?: React.Ref<HTMLElement>;/**- * HTML element to render as the root.+ * What the root renders as: an HTML element, or a component for a caller+ * that needs the root to be something else. A menu row that navigates+ * passes the application's link component here, so the row's root IS the+ * anchor and a modified or middle click keeps the browser's meaning.+ *+ * Give a component only when the row carries a `role`, so the parent owns+ * keyboard access and the row adds no second tab stop; and only when no+ * interactive node sits in `startContent` or `endContent`, since a control+ * nested inside an anchor is invalid.* @default 'div'*/- as?: 'div' | 'li' | 'span';+ as?: 'div' | 'li' | 'span' | React.ElementType;/*** Marker rendered before startContent as a direct flex child.@@ -138,7 +146,9 @@ export interface ItemProps extends BaseProps<HTMLElement> {interactiveRef?: React.RefObject<HTMLElement | null>;/**- * Link URL. Makes the item a link via an invisible anchor element.+ * Link URL. Makes the item a link via an invisible anchor element. A row+ * whose root is already a link component (see `as`) carries the address on+ * that root instead, and no invisible anchor is rendered.*/href?: string;@@ -243,6 +253,11 @@ const styles = stylex.create({cursor: 'default',pointerEvents: 'none' as const,},+ // A row whose root is the link: the browser's anchor paint stays out of it.+ linkRoot: {+ color: 'inherit',+ textDecoration: 'none',+ },disabledContent: {opacity: 0.5,},@@ -438,6 +453,18 @@ export function Item({// handles keyboard access. Skip the invisible button/anchor and put// onClick directly on the root element instead.const hasParentRole = role != null;+ // The root is whatever `as` says it is. A caller that passed a link+ // component means the root itself is the anchor, so the address rides it+ // and the invisible anchor below is not rendered.+ const isLinkRoot = typeof Component !== 'string' && href != null;+ const linkRootProps = isLinkRoot+ ? {+ // A disabled row keeps its place in the tree but goes nowhere.+ href: isDisabled ? undefined : href,+ target: isDisabled ? undefined : target,+ rel: isDisabled ? undefined : rel,+ }+ : null;// aria-selected is only valid on selectable roles (option, tab, treeitem,// grid cells). On the default div/li root the attribute is invalid ARIA// (axe: aria-allowed-attr), so selection stays visual-only there — callers@@ -538,7 +565,7 @@ export function Item({)}>{labelAndDescription}</span>- ) : href != null ? (+ ) : href != null && !isLinkRoot ? (<LinkComponenthref={href}target={target}@@ -593,6 +620,7 @@ export function Item({<Componentref={(isDelegate ? mergedRef : ref) as React.Ref<never>}{...restProps}+ {...linkRootProps}aria-selected={(allowsAriaSelected && isSelected) || undefined}// aria-selected is invalid on roles that don't permit it (listitem, a// bare div, etc.). For those, convey selection via aria-current — valid@@ -611,6 +639,7 @@ export function Item({align === 'start' && styles.alignStart,isInteractive && styles.interactive,isInteractive && interactionOverlayStyles.backgroundColor,+ isLinkRoot && styles.linkRoot,isHighlighted && styles.highlighted,isSelected && styles.selected,isDisabled && !hasParentRole && styles.disabled,