Skip to content

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

TypeScript

feat(sidenav): add actions slot for row controls (#5005)

AKe5e83effd874
diff --git a/.changeset/sidenav-row-control-size.md b/.changeset/sidenav-row-control-size.md
new file mode 100644
index 0000000000..9d767eb586
--- /dev/null
+++ b/.changeset/sidenav-row-control-size.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] SideNavItem: the standalone expand/collapse toggle on a `collapsible` item with an `href` or `onClick` now carries the box of a `size="sm"` icon button. It had no box of its own, so it shrank to the 24px chevron inside it and painted a smaller hover pill than any icon button sitting beside it in the same row. (#4988)
+
+@AKnassa
diff --git a/.changeset/sidenavitem-actions-slot.md b/.changeset/sidenavitem-actions-slot.md
new file mode 100644
index 0000000000..90095d7f00
--- /dev/null
+++ b/.changeset/sidenavitem-actions-slot.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] SideNavItem: new `actions` slot for row-level secondary controls (icon buttons, menus). Content renders as a sibling of the primary link/button — after the expand/collapse toggle, before nested children in DOM and focus order — so interactive controls never nest inside the primary element and every row control is reachable before focus enters the subtree. Passive content (badges, counts) stays in `endContent`; `actions` is hidden while the rail is collapsed, and stays interactive on disabled items since each supplied control owns its own disabled state. An actions row draws its focus ring as a full-row pill for the primary link or button, while the expand/collapse toggle and each supplied action keep their own — adds `focusOutlineProps.focusWithinFirstChild` and `focusOutlineProps.suppressed` for that pairing. Supplied controls inherit the row's control size through `SizeContext`, the way `SideNav` already cascades one size to its footer icons, so an unsized icon button comes out the same box as the built-in toggle; an explicit `size` still wins. (#4988)
+
+@AKnassa
diff --git a/apps/storybook/stories/SideNav.stories.tsx b/apps/storybook/stories/SideNav.stories.tsx
index d1cf2bff72..f393694a0f 100644
--- a/apps/storybook/stories/SideNav.stories.tsx
+++ b/apps/storybook/stories/SideNav.stories.tsx
@@ -24,6 +24,7 @@ import {
QuestionMarkCircleIcon,
DocumentTextIcon,
CubeIcon,
+ PlusIcon,
} from '@heroicons/react/24/outline';
import {
HomeIcon as HomeIconSolid,
@@ -58,9 +59,7 @@ export const Default: Story = {
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="My App"
headingHref="/"
/>
@@ -80,11 +79,7 @@ export const Default: Story = {
href="/projects"
endContent={<Badge label="3" />}
/>
- <SideNavItem
- label="Analytics"
- icon={ChartBarIcon}
- href="/analytics"
- />
+ <SideNavItem label="Analytics" icon={ChartBarIcon} href="/analytics" />
<SideNavItem label="Team" icon={UserGroupIcon} href="/team" />
</SideNavSection>
<SideNavSection title="Documents">
@@ -120,11 +115,7 @@ export const TitleWithoutIcon: Story = {
selectedIcon={FolderIconSolid}
href="/projects"
/>
- <SideNavItem
- label="Analytics"
- icon={ChartBarIcon}
- href="/analytics"
- />
+ <SideNavItem label="Analytics" icon={ChartBarIcon} href="/analytics" />
</SideNavSection>
</SideNav>
),
@@ -140,9 +131,7 @@ export const WithHeaderMenu: Story = {
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="Product Name"
subheading="Business Account"
menu={
@@ -178,9 +167,7 @@ export const SuiteHeader: Story = {
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
superheading="Suite Name"
superheadingHref="/suite"
heading="Product Name"
@@ -217,9 +204,7 @@ export const NestedItems: Story = {
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="My App"
/>
}>
@@ -233,10 +218,7 @@ export const NestedItems: Story = {
<SideNavItem label="Settings" icon={Cog6ToothIcon}>
<SideNavItem label="General" href="/settings/general" />
<SideNavItem label="Security" href="/settings/security" />
- <SideNavItem
- label="Notifications"
- href="/settings/notifications"
- />
+ <SideNavItem label="Notifications" href="/settings/notifications" />
</SideNavItem>
</SideNavSection>
</SideNav>
@@ -253,9 +235,7 @@ export const WithFooter: Story = {
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="My App"
/>
}
@@ -300,9 +280,7 @@ export const DisabledItem: Story = {
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="My App"
/>
}>
@@ -334,9 +312,7 @@ export const HiddenSectionHeader: Story = {
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="My App"
/>
}>
@@ -359,14 +335,12 @@ export const HiddenSectionHeader: Story = {
// =============================================================================
export const EndContent: Story = {
- name: 'End Content (Badges & Menus)',
+ name: 'End Content (Badges)',
render: () => (
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="My App"
headingHref="/"
/>
@@ -378,16 +352,6 @@ export const EndContent: Story = {
selectedIcon={HomeIconSolid}
isSelected
href="/dashboard"
- endContent={
- <MoreMenu
- size="sm"
- items={[
- {label: 'Pin to top', onClick: () => {}},
- {label: 'Rename', onClick: () => {}},
- {label: 'Hide from sidebar', onClick: () => {}},
- ]}
- />
- }
/>
<SideNavItem
label="Projects"
@@ -415,17 +379,7 @@ export const EndContent: Story = {
label="Notifications"
icon={BellIcon}
href="/notifications"
- endContent={
- <Button
- label="Settings"
- icon={
- <Icon icon={Cog6ToothIcon} size="sm" color="secondary" />
- }
- variant="ghost"
- size="sm"
- isIconOnly
- />
- }
+ endContent={<Badge label={5} />}
/>
<SideNavItem
label="Documents"
@@ -458,6 +412,77 @@ export const EndContent: Story = {
),
};
+// =============================================================================
+// Row Actions
+// =============================================================================
+
+export const RowActions: Story = {
+ name: 'Row Actions (Sibling Controls)',
+ render: () => (
+ <SideNav
+ header={
+ <SideNavHeading
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
+ heading="My App"
+ headingHref="/"
+ />
+ }>
+ <SideNavSection title="Projects" isHeaderHidden>
+ <SideNavItem
+ label="Project Alpha"
+ icon={FolderIcon}
+ selectedIcon={FolderIconSolid}
+ isSelected
+ href="/projects/alpha"
+ collapsible
+ actions={
+ <MoreMenu
+ label="Project Alpha actions"
+ items={[
+ {label: 'New session', onClick: () => {}},
+ {label: 'Rename project', onClick: () => {}},
+ {label: 'Archive project', onClick: () => {}},
+ ]}
+ />
+ }>
+ <SideNavItem label="Session 1" href="/projects/alpha/sessions/1" />
+ <SideNavItem label="Session 2" href="/projects/alpha/sessions/2" />
+ </SideNavItem>
+ <SideNavItem
+ label="Project Beta"
+ icon={FolderIcon}
+ href="/projects/beta"
+ collapsible={{defaultIsCollapsed: true}}
+ actions={
+ <MoreMenu
+ label="Project Beta actions"
+ items={[
+ {label: 'New session', onClick: () => {}},
+ {label: 'Rename project', onClick: () => {}},
+ ]}
+ />
+ }>
+ <SideNavItem label="Session 1" href="/projects/beta/sessions/1" />
+ </SideNavItem>
+ <SideNavItem
+ label="Notes"
+ icon={DocumentTextIcon}
+ href="/notes"
+ endContent={<Badge label={4} />}
+ actions={
+ <Button
+ label="New note"
+ icon={<Icon icon={PlusIcon} size="sm" color="secondary" />}
+ variant="ghost"
+ isIconOnly
+ />
+ }
+ />
+ </SideNavSection>
+ </SideNav>
+ ),
+};
+
// =============================================================================
// Header End Content
// =============================================================================
@@ -468,9 +493,7 @@ export const HeaderEndContent: Story = {
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="My App"
headingHref="/"
headerEndContent={<Badge label="3" variant="error" />}
@@ -499,9 +522,7 @@ export const HeaderEndContentWithMenu: Story = {
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="Product Name"
subheading="Business Account"
headerEndContent={<Badge label="New" variant="info" />}
@@ -535,9 +556,7 @@ export const CollapsibleItems: Story = {
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="My App"
/>
}>
@@ -545,10 +564,7 @@ export const CollapsibleItems: Story = {
<SideNavItem label="Settings" icon={Cog6ToothIcon} collapsible>
<SideNavItem label="General" href="/settings/general" />
<SideNavItem label="Security" href="/settings/security" />
- <SideNavItem
- label="Notifications"
- href="/settings/notifications"
- />
+ <SideNavItem label="Notifications" href="/settings/notifications" />
</SideNavItem>
<SideNavItem
label="Documents"
@@ -566,10 +582,7 @@ export const CollapsibleItems: Story = {
collapsible>
<SideNavItem label="General" href="/settings/general" />
<SideNavItem label="Security" href="/settings/security" />
- <SideNavItem
- label="Notifications"
- href="/settings/notifications"
- />
+ <SideNavItem label="Notifications" href="/settings/notifications" />
</SideNavItem>
<SideNavItem
label="Documents"
@@ -588,10 +601,7 @@ export const CollapsibleItems: Story = {
collapsible>
<SideNavItem label="General" href="/settings/general" />
<SideNavItem label="Security" href="/settings/security" />
- <SideNavItem
- label="Notifications"
- href="/settings/notifications"
- />
+ <SideNavItem label="Notifications" href="/settings/notifications" />
</SideNavItem>
</SideNavSection>
</SideNav>
@@ -609,9 +619,7 @@ export const CollapsibleSidebar: Story = {
collapsible
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="My App"
headingHref="/"
/>
@@ -649,21 +657,14 @@ export const CollapsibleSidebar: Story = {
href="/projects"
endContent={<Badge label="3" />}
/>
- <SideNavItem
- label="Analytics"
- icon={ChartBarIcon}
- href="/analytics"
- />
+ <SideNavItem label="Analytics" icon={ChartBarIcon} href="/analytics" />
<SideNavItem label="Team" icon={UserGroupIcon} href="/team" />
</SideNavSection>
<SideNavSection title="Settings">
<SideNavItem label="Settings" icon={Cog6ToothIcon} collapsible>
<SideNavItem label="General" href="/settings/general" />
<SideNavItem label="Security" href="/settings/security" />
- <SideNavItem
- label="Notifications"
- href="/settings/notifications"
- />
+ <SideNavItem label="Notifications" href="/settings/notifications" />
</SideNavItem>
<SideNavItem
label="Documents"
@@ -685,9 +686,7 @@ export const IconlessNestedItems: Story = {
<SideNav
header={
<SideNavHeading
- icon={
- <NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
- }
+ icon={<NavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />}
heading="My App"
/>
}>
@@ -702,21 +701,14 @@ export const IconlessNestedItems: Story = {
<SideNavItem label="Settings" icon={Cog6ToothIcon} collapsible>
<SideNavItem label="General" href="/settings/general" />
<SideNavItem label="Security" href="/settings/security" />
- <SideNavItem
- label="Notifications"
- href="/settings/notifications"
- />
+ <SideNavItem label="Notifications" href="/settings/notifications" />
</SideNavItem>
<SideNavItem label="Reports" collapsible>
<SideNavItem label="Monthly" href="/reports/monthly" />
<SideNavItem label="Quarterly" href="/reports/quarterly" />
<SideNavItem label="Annual" href="/reports/annual" />
</SideNavItem>
- <SideNavItem
- label="Analytics"
- icon={ChartBarIcon}
- href="/analytics"
- />
+ <SideNavItem label="Analytics" icon={ChartBarIcon} href="/analytics" />
</SideNavSection>
</SideNav>
),
diff --git a/packages/core/src/SideNav/SideNav.test.tsx b/packages/core/src/SideNav/SideNav.test.tsx
index 889fe0a919..409f3dd20d 100644
--- a/packages/core/src/SideNav/SideNav.test.tsx
+++ b/packages/core/src/SideNav/SideNav.test.tsx
@@ -11,7 +11,14 @@
import React from 'react';
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
-import {render, screen, act, fireEvent, waitFor} from '@testing-library/react';
+import {
+ render,
+ screen,
+ act,
+ fireEvent,
+ waitFor,
+ within,
+} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {useRef, useState, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
@@ -1546,6 +1553,318 @@ describe('SideNavItem — collapsible + href', () => {
});
});
+// =============================================================================
+// SideNavItem — actions slot (row-level secondary controls, #4988)
+// =============================================================================
+
+describe('SideNavItem — actions slot', () => {
+ const rowAction = (onClick?: (e: React.MouseEvent) => void) => (
+ <button type="button" data-testid="row-action" onClick={onClick}>
+ ⋯
+ </button>
+ );
+
+ it('renders actions outside the primary interactive element', () => {
+ render(
+ <SideNavItem label="Project" href="/project" actions={rowAction()} />,
+ );
+ const action = screen.getByTestId('row-action');
+ const link = screen.getByRole('link', {name: 'Project'});
+ // Sibling, not nested: the action's closest interactive element is itself.
+ expect(within(link).queryByTestId('row-action')).toBeNull();
+ expect(action.closest('a, button')).toBe(action);
+ });
+
+ it('places actions after the primary element and before nested children', () => {
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ collapsible
+ actions={rowAction()}>
+ <SideNavItem label="Session" href="/project/session" />
+ </SideNavItem>,
+ );
+ const primary = screen.getByRole('link', {name: 'Project'});
+ const action = screen.getByTestId('row-action');
+ const group = screen.getByRole('group');
+ // Compare real node positions, not serialized markup.
+ expect(
+ primary.compareDocumentPosition(action) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ action.compareDocumentPosition(group) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it('reaches every row-level control before nested items when tabbing', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ collapsible
+ actions={rowAction()}>
+ <SideNavItem label="Session" href="/project/session" />
+ </SideNavItem>,
+ );
+ await user.tab();
+ expect(screen.getByRole('link', {name: 'Project'})).toHaveFocus();
+ await user.tab();
+ expect(
+ screen.getByRole('button', {name: /collapse project/i}),
+ ).toHaveFocus();
+ await user.tab();
+ expect(screen.getByTestId('row-action')).toHaveFocus();
+ await user.tab();
+ expect(screen.getByRole('link', {name: 'Session'})).toHaveFocus();
+ });
+
+ it('clicking an action does not activate the item', async () => {
+ const user = userEvent.setup();
+ const onItemClick = vi.fn();
+ const onActionClick = vi.fn();
+ render(
+ <SideNavItem
+ label="Project"
+ onClick={onItemClick}
+ actions={rowAction(onActionClick)}
+ />,
+ );
+ await user.click(screen.getByTestId('row-action'));
+ expect(onActionClick).toHaveBeenCalledTimes(1);
+ expect(onItemClick).not.toHaveBeenCalled();
+ });
+
+ it('clicking an action does not toggle collapse of a whole-row toggle item', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNavItem label="Project" collapsible actions={rowAction()}>
+ <SideNavItem label="Session" />
+ </SideNavItem>,
+ );
+ const rowToggle = screen.getByRole('button', {name: 'Project'});
+ expect(rowToggle).toHaveAttribute('aria-expanded', 'true');
+ await user.click(screen.getByTestId('row-action'));
+ expect(rowToggle).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('whole-row toggle still collapses when actions are present', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNavItem label="Project" collapsible actions={rowAction()}>
+ <SideNavItem label="Session" />
+ </SideNavItem>,
+ );
+ expect(screen.getByTestId('row-action')).toBeInTheDocument();
+ const rowToggle = screen.getByRole('button', {name: 'Project'});
+ await user.click(rowToggle);
+ expect(rowToggle).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('adds a row wrapper only when actions are present', () => {
+ const {unmount} = render(<SideNavItem label="Project" href="/project" />);
+ // Without actions, the link itself is the styled row element.
+ expect(screen.getByRole('link', {name: 'Project'})).toHaveClass(
+ 'astryx-side-nav-item',
+ );
+ unmount();
+
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ data-testid="row"
+ actions={rowAction()}
+ />,
+ );
+ // With actions, a wrapper div is the styled row; the link sits inside it.
+ const link = screen.getByRole('link', {name: 'Project'});
+ expect(link).not.toHaveClass('astryx-side-nav-item');
+ const row = screen.getByTestId('row');
+ expect(row).toHaveClass('astryx-side-nav-item');
+ expect(row).toContainElement(link);
+ expect(row).toContainElement(screen.getByTestId('row-action'));
+ });
+
+ it('adds no row wrapper for a falsy actions value', () => {
+ // `actions={canEdit ? <Menu /> : null}` is the ordinary consumer shape.
+ // A wrapper there would change markup, focus order and the ring's
+ // owner for a row that has no row controls at all.
+ const {rerender} = render(
+ <SideNavItem label="Project" href="/project" actions={null} />,
+ );
+ expect(screen.getByRole('link', {name: 'Project'})).toHaveClass(
+ 'astryx-side-nav-item',
+ );
+
+ rerender(<SideNavItem label="Project" href="/project" actions={false} />);
+ expect(screen.getByRole('link', {name: 'Project'})).toHaveClass(
+ 'astryx-side-nav-item',
+ );
+ });
+
+ it('keeps aria wiring on the toggle when actions are present', () => {
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ collapsible
+ actions={rowAction()}>
+ <SideNavItem label="Session" />
+ </SideNavItem>,
+ );
+ expect(screen.getByTestId('row-action')).toBeInTheDocument();
+ const toggle = screen.getByRole('button', {name: /collapse project/i});
+ const group = screen.getByRole('group');
+ expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ expect(toggle).toHaveAttribute('aria-controls', group.id);
+ expect(screen.getByRole('link', {name: 'Project'})).not.toHaveAttribute(
+ 'aria-expanded',
+ );
+ });
+
+ it('keeps endContent inside the primary element when actions are present', () => {
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ endContent={<span data-testid="badge">3</span>}
+ actions={rowAction()}
+ />,
+ );
+ const link = screen.getByRole('link', {name: /Project/});
+ expect(within(link).getByTestId('badge')).toBeInTheDocument();
+ expect(within(link).queryByTestId('row-action')).toBeNull();
+ expect(screen.getByTestId('row-action')).toBeInTheDocument();
+ });
+
+ it('keeps collapsed children inert while the action stays in the row', () => {
+ render(
+ <SideNavItem
+ label="Project"
+ collapsible={{defaultIsCollapsed: true}}
+ actions={rowAction()}>
+ <SideNavItem label="Session" href="/project/session" />
+ </SideNavItem>,
+ );
+ const rowToggle = screen.getByRole('button', {name: 'Project'});
+ const group = document.getElementById(
+ rowToggle.getAttribute('aria-controls')!,
+ );
+ expect(group).toHaveAttribute('inert');
+ expect(screen.getByTestId('row-action')).toBeInTheDocument();
+ });
+
+ it('does not render actions in the collapsed rail', () => {
+ const {unmount} = renderCollapsed(
+ <SideNavItem
+ label="Project"
+ icon={StubIcon}
+ href="/project"
+ actions={rowAction()}
+ />,
+ );
+ expect(screen.getByLabelText('Project')).toBeInTheDocument();
+ expect(screen.queryByTestId('row-action')).toBeNull();
+ unmount();
+
+ renderCollapsed(
+ <SideNavItem label="Project" icon={StubIcon} actions={rowAction()}>
+ <SideNavItem label="Session" href="/project/session" />
+ </SideNavItem>,
+ );
+ expect(screen.getByLabelText('Project')).toBeInTheDocument();
+ expect(screen.queryByTestId('row-action')).toBeNull();
+ });
+
+ it('keeps actions clickable on a disabled item', async () => {
+ const user = userEvent.setup();
+ const onActionClick = vi.fn();
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ isDisabled
+ actions={rowAction(onActionClick)}
+ />,
+ );
+ // The row's disabled styling must not swallow the sibling action:
+ // the action control owns its own disabled state.
+ await user.click(screen.getByTestId('row-action'));
+ expect(onActionClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('places actions after the toggle when endContent is also present', () => {
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ collapsible
+ endContent={<span data-testid="badge">3</span>}
+ actions={rowAction()}>
+ <SideNavItem label="Session" href="/project/session" />
+ </SideNavItem>,
+ );
+ const link = screen.getByRole('link', {name: /Project/});
+ const toggle = screen.getByRole('button', {name: /collapse project/i});
+ const action = screen.getByTestId('row-action');
+ expect(within(link).getByTestId('badge')).toBeInTheDocument();
+ expect(
+ link.compareDocumentPosition(toggle) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ toggle.compareDocumentPosition(action) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it('reaches the action after the whole-row toggle and before nested items', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNavItem label="Project" collapsible actions={rowAction()}>
+ <SideNavItem label="Session" href="/project/session" />
+ </SideNavItem>,
+ );
+ await user.tab();
+ expect(screen.getByRole('button', {name: 'Project'})).toHaveFocus();
+ await user.tab();
+ expect(screen.getByTestId('row-action')).toHaveFocus();
+ await user.tab();
+ expect(screen.getByRole('link', {name: 'Session'})).toHaveFocus();
+ });
+
+ it('renders the custom link component inside the row wrapper', () => {
+ render(
+ <LinkProvider component={CustomLink}>
+ <SideNavItem label="Project" href="/project" actions={rowAction()} />
+ </LinkProvider>,
+ );
+ const link = screen.getByRole('link', {name: 'Project'});
+ expect(link).toHaveAttribute('data-custom-link');
+ expect(link.parentElement).toHaveClass('astryx-side-nav-item');
+ });
+
+ it('controlled collapse reports toggle intent without flipping until the prop changes', async () => {
+ const user = userEvent.setup();
+ const onCollapsedChange = vi.fn();
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ collapsible={{isCollapsed: false, onCollapsedChange}}
+ actions={rowAction()}>
+ <SideNavItem label="Session" href="/project/session" />
+ </SideNavItem>,
+ );
+ const toggle = screen.getByRole('button', {name: /collapse project/i});
+ await user.click(toggle);
+ expect(onCollapsedChange).toHaveBeenCalledWith(true);
+ // Controlled mode: stays expanded until the consumer flips the prop.
+ expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ });
+});
+
import {SideNavRenderContext} from './SideNavRenderContext';
import {AppShellMobileContext} from '../AppShell/AppShellMobileContext';
@@ -1625,6 +1944,28 @@ describe('SideNavItem — mobile drawer close-on-activate', () => {
await user.click(screen.getByTestId('item'));
expect(closeMobileNav).not.toHaveBeenCalled();
});
+
+ it('does not close the mobile nav when a row action is clicked', async () => {
+ const user = userEvent.setup();
+ const onActionClick = vi.fn();
+ const {closeMobileNav} = renderInDrawer(
+ <SideNavItem
+ label="Home"
+ href="/"
+ actions={
+ <button
+ type="button"
+ data-testid="drawer-row-action"
+ onClick={onActionClick}>
+ ⋯
+ </button>
+ }
+ />,
+ );
+ await user.click(screen.getByTestId('drawer-row-action'));
+ expect(onActionClick).toHaveBeenCalledTimes(1);
+ expect(closeMobileNav).not.toHaveBeenCalled();
+ });
});
// =============================================================================
@@ -1899,10 +2240,18 @@ describe('SideNav audit regressions', () => {
// =============================================================================
// A15 — the shared focus ring
//
-// jsdom does not derive `:focus-visible` from `.focus()` or from Tab, so the
-// painted ring cannot be read back here; the geometry is measured in a real
-// browser instead. These pin the composition — that the focusable element
-// carries the classes `focusOutlineStyles.focusVisible` compiles to.
+// jsdom does not derive `:focus-visible` from `.focus()` for an element
+// matched directly, so the ring a tab stop draws on itself cannot be read
+// back here; the geometry is measured in a real browser instead. These pin
+// the composition — that the focusable element carries the classes
+// `focusOutlineStyles.focusVisible` compiles to.
+//
+// Composition is only proof for a tab stop. A row wrapper is not one, so
+// `:focus-visible` atoms sitting on it can never match, and asserting them
+// there proves nothing: the actions-row tests below passed with the
+// wrapper's ring deleted outright. A wrapper's ring is guarded by `:has()`,
+// which jsdom *does* re-evaluate against live focus, so those rules are read
+// out of the stylesheet and matched against the DOM instead.
// =============================================================================
const sharedFocusRingClasses = stylex
@@ -1923,6 +2272,120 @@ function expectNoSharedFocusRing(el: Element) {
}
}
+/** Every style rule in the live sheet, flattened out of any grouping rule. */
+function allStyleRules(): CSSStyleRule[] {
+ const out: CSSStyleRule[] = [];
+ const walk = (rules: CSSRuleList) => {
+ for (const rule of Array.from(rules)) {
+ const nested = (rule as CSSGroupingRule).cssRules;
+ if (nested) {
+ walk(nested);
+ }
+ if ((rule as CSSStyleRule).selectorText) {
+ out.push(rule as CSSStyleRule);
+ }
+ }
+ };
+ for (const sheet of Array.from(document.styleSheets)) {
+ try {
+ walk(sheet.cssRules);
+ } catch {
+ // A sheet we cannot read cannot be one StyleX injected.
+ }
+ }
+ return out;
+}
+
+/**
+ * A rule's declared value for `prop`, read out of its text.
+ *
+ * Not `rule.style`: these values are `var()`s, and jsdom's CSS object model
+ * drops longhands it cannot parse, so they read back as an empty string there.
+ */
+function declaredValue(rule: CSSStyleRule, prop: string): string | undefined {
+ const body = /\{([^}]*)\}/.exec(rule.cssText)?.[1] ?? '';
+ return new RegExp(`(?:^|;)\\s*${prop}:\\s*([^;]+)`).exec(body)?.[1].trim();
+}
+
+/** A rule's `outline-style` — the discriminator for a painting focus ring. */
+function outlineStyleOf(rule: CSSStyleRule): string | undefined {
+ return declaredValue(rule, 'outline-style');
+}
+
+/**
+ * What the live sheet unconditionally declares for `prop` on `el`, gathered
+ * from every bare-class rule the element carries. StyleX emits one atomic
+ * class per property, so a well-formed element yields exactly one value —
+ * comparing those values compares real CSS without pinning a generated hash.
+ */
+function declaredOn(el: Element, prop: string): string[] {
+ const classes = new Set(el.className.split(' '));
+ return allStyleRules()
+ .filter(rule => {
+ const bare = rule.selectorText.replace(/:not\(#\\?#\)/g, '');
+ const owner = /^\.([^:\s]+)$/.exec(bare)?.[1];
+ return owner != null && classes.has(owner);
+ })
+ .map(rule => declaredValue(rule, prop))
+ .filter(value => value != null);
+}
+
+/**
+ * The selectors that actually paint the shared ring on `el`, read out of the
+ * live stylesheet with StyleX's `:not(#\#)` specificity padding stripped so
+ * jsdom can evaluate them.
+ *
+ * `outline-style` is the discriminator: StyleX emits one rule per property,
+ * and no outline paints while that one resolves to `none`.
+ */
+function ringSelectorsFor(el: Element): string[] {
+ const classes = new Set(el.className.split(' '));
+ return allStyleRules()
+ .filter(rule => {
+ const painted = outlineStyleOf(rule);
+ if (!painted || painted === 'none') {
+ return false;
+ }
+ const owner = /^\.([^:\s]+)/.exec(rule.selectorText)?.[1];
+ return owner != null && classes.has(owner);
+ })
+ .map(rule => rule.selectorText.replace(/:not\(#\\?#\)/g, ''));
+}
+
+/**
+ * Whether `el`'s ring is painting for whatever holds focus right now.
+ *
+ * `:focus-visible` is substituted with `:focus` before matching. jsdom
+ * derives `:focus-visible` from a heuristic over the last interaction, so it
+ * answers differently depending on which tests ran before — the same
+ * assertion passes alone and fails in the file. `:focus` is unambiguous, and
+ * the ring's modality is pinned separately, on the selector text, by the
+ * keyboard-only test below.
+ */
+function ringIsPainting(el: Element): boolean {
+ return ringSelectorsFor(el).some(selector =>
+ el.matches(selector.replace(/:focus-visible/g, ':focus')),
+ );
+}
+
+/**
+ * Whether `el` unconditionally declares `outline-style: none`, which is what
+ * keeps the UA's own focus ring off an element whose ring an ancestor paints.
+ * Computed style cannot answer this: `none` is also the CSS initial value.
+ */
+function suppressesOwnOutline(el: Element): boolean {
+ const classes = new Set(el.className.split(' '));
+ return allStyleRules().some(rule => {
+ if (outlineStyleOf(rule) !== 'none') {
+ return false;
+ }
+ // Unconditional only — a bare class once the padding is stripped.
+ const bare = rule.selectorText.replace(/:not\(#\\?#\)/g, '');
+ const owner = /^\.([^:\s]+)$/.exec(bare)?.[1];
+ return owner != null && classes.has(owner);
+ });
+}
+
describe('SideNav focus ring (A15)', () => {
it('draws the shared ring on a link item', () => {
render(<SideNavItem label="Dashboard" href="/dashboard" />);
@@ -1970,6 +2433,173 @@ describe('SideNav focus ring (A15)', () => {
expectNoSharedFocusRing(row);
});
+ it('rings the row wrapper of an actions row, not the truncated primary', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ actions={
+ <button type="button" data-testid="row-action">
+ More
+ </button>
+ }
+ />,
+ );
+
+ const link = screen.getByRole('link', {name: 'Project'});
+ const row = link.parentElement!;
+ expect(row.tagName).toBe('DIV');
+ expect(row).toContainElement(screen.getByTestId('row-action'));
+
+ // Same pill as an ordinary row: the ring lives on the wrapper, whose box
+ // includes the actions. Putting it on the primary would clip to the
+ // truncated split-action element (square, not full-row).
+ expect(ringIsPainting(row)).toBe(false);
+ await user.tab();
+ expect(link).toHaveFocus();
+ expect(ringIsPainting(row)).toBe(true);
+ // And exactly one ring: nothing paints a second one on the primary.
+ expect(ringSelectorsFor(link)).toEqual([]);
+ });
+
+ it('leaves the wrapper ring to the primary, not the chevron toggle', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNavItem
+ label="Settings"
+ href="/settings"
+ collapsible
+ actions={
+ <button type="button" data-testid="row-action">
+ More
+ </button>
+ }>
+ <SideNavItem label="General" href="/settings/general" />
+ </SideNavItem>,
+ );
+
+ const link = screen.getByRole('link', {name: 'Settings'});
+ const toggle = screen.getByRole('button', {name: 'Collapse Settings'});
+ const row = link.parentElement!;
+ expect(row).toContainElement(screen.getByTestId('row-action'));
+
+ await user.tab();
+ expect(link).toHaveFocus();
+ expect(ringIsPainting(row)).toBe(true);
+
+ // The toggle owns its own ring, as it does in a split-action row with no
+ // actions. Keeping the wrapper lit too would stack a full-row outline
+ // around the chevron's own — two rings for one tab stop.
+ await user.tab();
+ expect(toggle).toHaveFocus();
+ expectSharedFocusRing(toggle);
+ expect(ringIsPainting(row)).toBe(false);
+ });
+
+ it('does not ring the row wrapper when a supplied action takes focus', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ actions={
+ <button type="button" data-testid="row-action">
+ More
+ </button>
+ }
+ />,
+ );
+
+ const row = screen.getByRole('link', {name: 'Project'}).parentElement!;
+ await user.tab();
+ expect(ringIsPainting(row)).toBe(true);
+
+ // An action draws whatever ring its own component draws. Focus is not on
+ // the row, so the row must not light up around it.
+ await user.tab();
+ expect(screen.getByTestId('row-action')).toHaveFocus();
+ expect(ringIsPainting(row)).toBe(false);
+ });
+
+ it('rings the wrapper of a whole-row toggle carrying actions', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNavItem
+ label="Project"
+ collapsible
+ actions={
+ <button type="button" data-testid="row-action">
+ More
+ </button>
+ }>
+ <SideNavItem label="Session" href="/project/session" />
+ </SideNavItem>,
+ );
+
+ // No href and no onClick, so the primary *is* the collapse toggle and
+ // keeps the chevron inside it — a different row shape from the split.
+ const primary = screen.getByRole('button', {name: 'Project'});
+ const row = primary.parentElement!;
+
+ await user.tab();
+ expect(primary).toHaveFocus();
+ expect(ringIsPainting(row)).toBe(true);
+
+ await user.tab();
+ expect(screen.getByTestId('row-action')).toHaveFocus();
+ expect(ringIsPainting(row)).toBe(false);
+ });
+
+ it('keeps the UA focus ring off the primary the wrapper rings for', () => {
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ actions={
+ <button type="button" data-testid="row-action">
+ More
+ </button>
+ }
+ />,
+ );
+
+ const link = screen.getByRole('link', {name: 'Project'});
+ // Dropping the shared ring off the primary also drops the
+ // `outline-style: none` default that came with it, and a bare <a> keeps
+ // the browser's own focus ring — which would paint inside the wrapper's.
+ expect(suppressesOwnOutline(link)).toBe(true);
+ });
+
+ it('paints the actions-row ring for keyboard focus only', () => {
+ render(
+ <SideNavItem
+ label="Project"
+ href="/project"
+ actions={
+ <button type="button" data-testid="row-action">
+ More
+ </button>
+ }
+ />,
+ );
+
+ const link = screen.getByRole('link', {name: 'Project'});
+ const row = link.parentElement!;
+ // The wrapper is not a tab stop, so its ring has to be guarded by a
+ // relational selector. `:focus-within` or `:focus` would light the row
+ // for mouse users too; only `:focus-visible` keeps it to the keyboard.
+ const selectors = ringSelectorsFor(row);
+ expect(selectors.length).toBeGreaterThan(0);
+ for (const selector of selectors) {
+ expect(selector).toContain(':focus-visible');
+ }
+
+ // The guard is scoped to the wrapper's first child. Reordering the row
+ // would hand the ring to the toggle or the actions instead.
+ expect(row.firstElementChild).toBe(link);
+ });
+
it('draws the shared ring on a heading rendered as one link', () => {
render(<SideNavHeading heading="My App" headingHref="/" />);
expectSharedFocusRing(screen.getByRole('link', {name: /My App/}));
@@ -2165,6 +2795,76 @@ describe('SideNav footer icon row sizing', () => {
});
});
+describe('SideNav row control sizing', () => {
+ /**
+ * The height an icon-only `Button` of this size declares — the box every
+ * control sharing a nav row is measured against.
+ */
+ function iconButtonHeight(size: 'sm' | 'md' | 'lg'): string[] {
+ const {unmount} = render(
+ <Button
+ label="sized reference"
+ size={size}
+ isIconOnly
+ icon={<span />}
+ data-testid="sized-ref"
+ />,
+ );
+ const height = declaredOn(screen.getByTestId('sized-ref'), 'height');
+ unmount();
+ // Guard against a vacuous pass: nothing below means anything if the
+ // reference itself declares no height.
+ expect(height).toHaveLength(1);
+ return height;
+ }
+
+ function collapsibleRow(actions: ReactNode) {
+ return (
+ <SideNavItem
+ label="Project"
+ href="/project"
+ collapsible
+ actions={actions}>
+ <SideNavItem label="Session" href="/project/session" />
+ </SideNavItem>
+ );
+ }
+
+ const iconAction = (props?: {size?: 'sm' | 'md' | 'lg'}) => (
+ <Button
+ label="Project actions"
+ isIconOnly
+ icon={<span />}
+ data-testid="row-action"
+ {...props}
+ />
+ );
+
+ it('sizes the expand toggle like the icon buttons it sits beside', () => {
+ const sm = iconButtonHeight('sm');
+ render(collapsibleRow(iconAction()));
+ const toggle = screen.getByRole('button', {name: /collapse project/i});
+ expect(declaredOn(toggle, 'height')).toEqual(sm);
+ // Square, so its hover pill reads as the same box as the action's.
+ expect(declaredOn(toggle, 'width')).toEqual(sm);
+ });
+
+ it('cascades that size to an action the consumer did not size', () => {
+ const sm = iconButtonHeight('sm');
+ // Without the cascade an unsized Button falls back to `md`; if the two
+ // compiled to one height the assertion below could not fail.
+ expect(sm).not.toEqual(iconButtonHeight('md'));
+ render(collapsibleRow(iconAction()));
+ expect(declaredOn(screen.getByTestId('row-action'), 'height')).toEqual(sm);
+ });
+
+ it('lets an explicit size on an action win over the cascade', () => {
+ const lg = iconButtonHeight('lg');
+ render(collapsibleRow(iconAction({size: 'lg'})));
+ expect(declaredOn(screen.getByTestId('row-action'), 'height')).toEqual(lg);
+ });
+});
+
describe('SideNavHeading hover/click guard', () => {
// tabIndex={-1} matches real menu items; a bare role=menuitem div is not
// focusable.
diff --git a/packages/core/src/SideNav/SideNavItem.doc.mjs b/packages/core/src/SideNav/SideNavItem.doc.mjs
index c3759e39f4..9ac7defe1d 100644
--- a/packages/core/src/SideNav/SideNavItem.doc.mjs
+++ b/packages/core/src/SideNav/SideNavItem.doc.mjs
@@ -55,7 +55,7 @@ export const docs = {
{
name: 'endContent',
type: 'ReactNode',
- description: 'Right-side content such as badges or counts.',
+ description: 'Passive right-side content only (badges, counts). Interactive controls go in actions.',
slotElements: [
{
__element: 'Icon',
@@ -72,6 +72,18 @@ export const docs = {
},
],
},
+ {
+ name: 'actions',
+ type: 'ReactNode',
+ description:
+ 'Row-level secondary controls (icon buttons, menus) rendered as siblings of the primary element at the trailing edge of the row — after the expand/collapse toggle, before any nested children in DOM and focus order. Each control owns its accessible name and behavior. Controls inherit the row control size through SizeContext, so an unsized icon button matches the built-in expand/collapse toggle; an explicit size still wins. Hidden while the SideNav rail is collapsed. Use endContent for passive content (badges, counts); use actions for anything interactive.',
+ slotElements: [
+ {
+ __element: 'Button',
+ props: {label: 'Rename', variant: 'ghost', size: 'sm'},
+ },
+ ],
+ },
{
name: 'children',
type: 'ReactNode',
@@ -152,7 +164,13 @@ export const docsZh = {
{
name: 'endContent',
type: 'ReactNode',
- description: '右侧内容,如徽章或计数。',
+ description: '仅用于被动右侧内容(徽章、计数)。交互控件请使用 actions。',
+ },
+ {
+ name: 'actions',
+ type: 'ReactNode',
+ description:
+ '行级次要控件(图标按钮、菜单),作为主元素的同级节点渲染在行尾——位于展开/折叠切换按钮之后、任何嵌套子项之前(DOM 与焦点顺序一致)。每个控件自行负责其无障碍名称与行为。控件通过 SizeContext 继承行内控件尺寸,因此未指定尺寸的图标按钮会与内置的展开/折叠切换按钮保持同一尺寸;显式指定的 size 优先。侧边栏折叠为图标栏时隐藏。被动内容(徽章、计数)请使用 endContent;交互内容请使用 actions。',
},
{
name: 'children',
@@ -188,7 +206,10 @@ export const docsDense = {
isDisabled: 'Disabled state.',
href: 'Navigation URL.',
onClick: 'Click handler.',
- endContent: 'Right-side content such as badges or counts.',
+ endContent:
+ 'Passive right-side content only (badges, counts). Interactive controls go in actions.',
+ actions:
+ 'Row-level secondary controls (icon buttons, menus) rendered as siblings of the primary element, after the expand/collapse toggle and before nested children in DOM/focus order. Inherit the row control size via SizeContext (explicit size wins). Hidden when rail collapsed. Passive content goes in endContent; interactive content goes here.',
children: 'Sub-items for nesting.',
collapsible: 'Enables collapse for items w/ children. true=uncontrolled, object=controlled mode.',
size: "Row size variant: 'sm' | 'md' | 'lg'.",
diff --git a/packages/core/src/SideNav/SideNavItem.tsx b/packages/core/src/SideNav/SideNavItem.tsx
index f1504cb08b..1197085b72 100644
--- a/packages/core/src/SideNav/SideNavItem.tsx
+++ b/packages/core/src/SideNav/SideNavItem.tsx
@@ -8,7 +8,7 @@
* @output Exports SideNavItem component and SideNavItemProps
* @position Core implementation; used inside SideNav children
*
- * Navigation item with icon, selected state, and nesting.
+ * Navigation item with icon, selected state, row-level actions, and nesting.
*
* Collapsed items with children open their submenu flyout through
* `useMenuHover`, the shared hover-intent hook (same one `SideNavHeading` and
@@ -51,6 +51,7 @@ import {mergeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {Tooltip} from '../Tooltip';
import {navItemStyles, type NavItemSize} from '../NavItem/navItemStyles.stylex';
+import {SizeProvider} from '../SizeContext/SizeContext';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';
import {
@@ -92,6 +93,18 @@ const styles = stylex.create({
display: 'flex',
alignItems: 'center',
},
+ // Row-level secondary controls (actions slot) — siblings of the primary
+ // element at the trailing edge of the row. pointerEvents opts back in when
+ // a disabled row's navItemStyles.disabled sets pointer-events: none on the
+ // wrapper: the slot is passthrough, so each control owns its own disabled
+ // state (keyboard focus already reaches it either way).
+ actions: {
+ flexShrink: 0,
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-1'],
+ pointerEvents: 'auto',
+ },
children: {
paddingInlineStart: spacingVars['--spacing-6'],
},
@@ -136,7 +149,13 @@ const styles = stylex.create({
transform: 'rotate(180deg)',
},
// Standalone toggle button for the chevron when collapsible + href.
+ // Boxed like a `size="sm"` icon Button so it and whatever sits in
+ // `actions` paint one size of hover pill; without a box of its own it
+ // shrank to the 24px chevron beside a 28px menu button.
+ // SYNC: matches ROW_CONTROL_SIZE below.
expandToggle: {
+ width: sizeVars['--size-element-sm'],
+ height: sizeVars['--size-element-sm'],
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
@@ -210,6 +229,16 @@ const styles = stylex.create({
},
});
+/**
+ * Cascaded to the `actions` slot through `SizeContext` so a consumer's row
+ * controls come out the same height as the built-in expand/collapse toggle,
+ * the way `SideNav` already cascades one size to its footer icons. An
+ * explicit `size` on a supplied control still wins.
+ *
+ * SYNC: `styles.expandToggle` carries the matching box.
+ */
+const ROW_CONTROL_SIZE = 'sm';
+
// Non-collapsed state for popover children — ensures nested items render expanded
const EXPANDED_COLLAPSE_STATE = {
isCollapsed: false,
@@ -312,9 +341,24 @@ export interface SideNavItemProps extends BaseProps<HTMLElement> {
*/
onClick?: (e: React.MouseEvent) => void;
/**
- * Right-side content (badges, counts).
+ * Passive right-side content only (badges, counts). Interactive
+ * controls (icon buttons, menus) go in `actions`. `endContent`
+ * renders inside the primary link or button.
*/
endContent?: ReactNode;
+ /**
+ * Row-level secondary controls (icon buttons, menus) rendered as siblings
+ * of the primary element at the trailing edge of the row — after the
+ * expand/collapse toggle, and before any nested children in DOM and focus
+ * order. Content is passthrough: each control owns its accessible name,
+ * keyboard behavior, and disabled state. Hidden while the SideNav rail is
+ * collapsed.
+ *
+ * Controls inherit the row's control size through `SizeContext`, so an
+ * unsized icon button comes out the same box as the built-in
+ * expand/collapse toggle. An explicit `size` still wins.
+ */
+ actions?: ReactNode;
/**
* Sub-items for nesting.
*/
@@ -351,7 +395,10 @@ export interface SideNavItemProps extends BaseProps<HTMLElement> {
/**
* Navigation item for SideNav.
*
- * Supports icons, selected state, nesting, and end content like badges or counts.
+ * Supports icons, selected state, nesting, and end content like badges or
+ * counts. Interactive row-level controls (menus, icon buttons) go in
+ * `actions`, which renders them as siblings of the primary element — never
+ * nested inside it — before any nested children in DOM and focus order.
*
* @example
* ```
@@ -366,6 +413,13 @@ export interface SideNavItemProps extends BaseProps<HTMLElement> {
* <SideNavItem label="General" href="/settings/general" />
* <SideNavItem label="Security" href="/settings/security" />
* </SideNavItem>
+ * <SideNavItem
+ * label="Projects"
+ * href="/projects"
+ * collapsible
+ * actions={<MoreMenu label="Project actions" items={items} />}>
+ * <SideNavItem label="Alpha" href="/projects/alpha" />
+ * </SideNavItem>
* ```
*/
export function SideNavItem({
@@ -378,6 +432,7 @@ export function SideNavItem({
href,
onClick,
endContent,
+ actions,
children,
collapsible: itemCollapsible,
size = 'md',
@@ -435,6 +490,7 @@ export function SideNavItem({
const hasPrimaryAction = !!href || !!onClick;
const hasIndependentToggle =
isItemCollapsible && hasPrimaryAction && !isCollapsed;
+ const hasActions = !!actions;
const handleClick = (e: React.MouseEvent) => {
if (isDisabled) {
@@ -617,25 +673,50 @@ export function SideNavItem({
isDisabled && navItemStyles.disabled,
] as const;
- // Two shapes of the same row appearance:
- // - `rowProps` for the split-action path, where the row is a plain <div>
- // container and its children take focus (so the ring belongs on them);
- // - `focusableRowProps` for every other path, where the row element is
- // itself the focusable control.
+ // Three shapes of the same row appearance:
+ // - `rowProps` — split-action path (toggle, no actions): presentational
+ // <div>; the ring belongs on each child tab stop.
+ // - `focusableRowProps` — ordinary row: the row element is the control.
+ // - `actionsRowProps` — same pill, but the ring is drawn for the primary
+ // only. The wrapper is not a tab stop, so `:focus-visible` on it would
+ // never match, and matching any descendant instead would light the whole
+ // row around the chevron's or an action's own ring.
const rowProps = mergeProps(itemThemeProps, stylex.props(...itemStyleArgs));
const focusableRowProps = mergeProps(
itemThemeProps,
focusOutlineProps.focusVisible(...itemStyleArgs),
);
+ const actionsRowProps = mergeProps(
+ itemThemeProps,
+ focusOutlineProps.focusWithinFirstChild(...itemStyleArgs),
+ );
+
+ // Row-wrapper path: primary element + row controls as siblings.
+ //
+ // Used when the row carries more than one control: an independent
+ // expand/collapse toggle (collapsible + href/onClick), consumer-supplied
+ // actions, or both. A <div> is the styled flex row; the primary link or
+ // button, the chevron toggle, and the actions slot render as siblings so
+ // no interactive element nests inside another, and every row-level
+ // control precedes the nested children group in DOM and focus order.
+ const hasRowWrapper = hasIndependentToggle || hasActions;
- // Split-action path: collapsible plus a primary action renders the primary
- // element and the chevron toggle as siblings in a <div> row, since a
- // <button> cannot nest inside an <a>.
let itemElement;
- if (hasIndependentToggle) {
+ if (hasRowWrapper) {
+ // aria-expanded/-controls stay on the primary element only when the
+ // whole row is the collapse toggle (no independent chevron button).
+ const rowPrimaryAriaProps = hasIndependentToggle
+ ? {'aria-current': isSelected ? ('page' as const) : undefined}
+ : {
+ 'aria-current': isSelected ? ('page' as const) : undefined,
+ 'aria-disabled': isDisabled || undefined,
+ 'aria-expanded': isItemCollapsible ? !isItemCollapsed : undefined,
+ 'aria-controls': isItemCollapsible ? `${id}-children` : undefined,
+ };
+
itemElement = (
- <div data-testid={testId} {...rowProps}>
+ <div data-testid={testId} {...(hasActions ? actionsRowProps : rowProps)}>
<NavItemElement
ref={ref}
href={href}
@@ -643,34 +724,45 @@ export function SideNavItem({
isDisabled={isDisabled}
onClick={handleClick}
{...rest}
- aria-current={isSelected ? ('page' as const) : undefined}
- {...focusOutlineProps.focusVisible(styles.splitAction)}>
+ {...rowPrimaryAriaProps}
+ {...(hasActions
+ ? // The wrapper rings for this element; suppressing here is what
+ // keeps the UA's own ring from painting inside that one.
+ focusOutlineProps.suppressed(styles.splitAction)
+ : focusOutlineProps.focusVisible(styles.splitAction))}>
{itemContent}
</NavItemElement>
- <button
- type="button"
- onClick={handleToggleClick}
- aria-label={
- isItemCollapsed
- ? t('@astryx.sideNavItem.expand', {label})
- : t('@astryx.sideNavItem.collapse', {label})
- }
- aria-expanded={!isItemCollapsed}
- aria-controls={`${id}-children`}
- {...focusOutlineProps.focusVisible(
- styles.expandToggle,
- interactionOverlayStyles.backgroundColor,
- )}>
- <Icon
- icon="chevronDown"
- size="lg"
- color="inherit"
- xstyle={[
- styles.expandChevron,
- !isItemCollapsed && styles.expandChevronExpanded,
- ]}
- />
- </button>
+ {hasIndependentToggle && (
+ <button
+ type="button"
+ onClick={handleToggleClick}
+ aria-label={
+ isItemCollapsed
+ ? t('@astryx.sideNavItem.expand', {label})
+ : t('@astryx.sideNavItem.collapse', {label})
+ }
+ aria-expanded={!isItemCollapsed}
+ aria-controls={`${id}-children`}
+ {...focusOutlineProps.focusVisible(
+ styles.expandToggle,
+ interactionOverlayStyles.backgroundColor,
+ )}>
+ <Icon
+ icon="chevronDown"
+ size="lg"
+ color="inherit"
+ xstyle={[
+ styles.expandChevron,
+ !isItemCollapsed && styles.expandChevronExpanded,
+ ]}
+ />
+ </button>
+ )}
+ {hasActions && (
+ <span {...stylex.props(styles.actions)}>
+ <SizeProvider value={ROW_CONTROL_SIZE}>{actions}</SizeProvider>
+ </span>
+ )}
</div>
);
} else {
diff --git a/packages/core/src/utils/focusOutline.stylex.ts b/packages/core/src/utils/focusOutline.stylex.ts
index b7ccead6df..3a0b664cd9 100644
--- a/packages/core/src/utils/focusOutline.stylex.ts
+++ b/packages/core/src/utils/focusOutline.stylex.ts
@@ -124,6 +124,52 @@ export const focusOutlineStyles = stylex.create({
},
outlineOffset: {default: '0', ':has(:focus-visible)': FOCUS_OUTLINE_OFFSET},
},
+ /**
+ * Like {@link focusOutlineStyles.focusWithin}, but only for the element's
+ * FIRST child — for a wrapper that paints the ring on behalf of one primary
+ * control while its siblings ring themselves.
+ *
+ * `focusWithin` matches any descendant, so a row holding more than one tab
+ * stop lights the whole row *on top of* the focused control's own ring: two
+ * outlines for one tab stop. Scoping to `> :first-child` keeps the ring the
+ * primary's, and leaves every sibling control ringing itself.
+ *
+ * The wrapper owns the coupling: the primary has to be its first child, and
+ * the wrapper must not be a tab stop (its own `:focus-visible` would never
+ * match). Pair it with {@link focusOutlineStyles.suppressed} on the primary.
+ */
+ focusWithinFirstChild: {
+ outlineWidth: {
+ default: '0',
+ ':has(> :first-child:focus-visible)': focusOutlineLonghands.outlineWidth,
+ },
+ outlineStyle: {
+ default: 'none',
+ ':has(> :first-child:focus-visible)': focusOutlineLonghands.outlineStyle,
+ },
+ outlineColor: {
+ default: null,
+ ':has(> :first-child:focus-visible)': focusOutlineLonghands.outlineColor,
+ },
+ outlineOffset: {
+ default: '0',
+ ':has(> :first-child:focus-visible)': FOCUS_OUTLINE_OFFSET,
+ },
+ },
+ /**
+ * Draws no ring, and keeps the UA's own off — for an element whose ring an
+ * ancestor paints.
+ *
+ * The reset is not optional. Every other style here suppresses the browser
+ * default through its `default` branch, so dropping the ring from a control
+ * drops that suppression with it, and a bare `<a>` or `<button>` goes back
+ * to the UA focus ring — painted *inside* the ancestor's.
+ */
+ suppressed: {
+ outlineWidth: '0',
+ outlineStyle: 'none',
+ outlineOffset: '0',
+ },
publishFocusVisibleVars: {
'--_focus-outline': {
default: 'none',
@@ -168,6 +214,10 @@ function makeFocusOutlineProps(style: StyleXPropsArg) {
export const focusOutlineProps = {
focusVisible: makeFocusOutlineProps(focusOutlineStyles.focusVisible),
focusWithin: makeFocusOutlineProps(focusOutlineStyles.focusWithin),
+ focusWithinFirstChild: makeFocusOutlineProps(
+ focusOutlineStyles.focusWithinFirstChild,
+ ),
+ suppressed: makeFocusOutlineProps(focusOutlineStyles.suppressed),
publishFocusVisibleVars: makeFocusOutlineProps(
focusOutlineStyles.publishFocusVisibleVars,
),