Skip to content

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

TypeScript

fix(SideNav): Section custom styles, Item collapsible+action split (#1666)

Cindy Zhange357a64fdbbc
diff --git a/apps/storybook/stories/SideNav.stories.tsx b/apps/storybook/stories/SideNav.stories.tsx
index 9fab4b815b..bae6ddf214 100644
--- a/apps/storybook/stories/SideNav.stories.tsx
+++ b/apps/storybook/stories/SideNav.stories.tsx
@@ -522,3 +522,70 @@ export const HeaderEndContentWithMenu: Story = {
</XDSSideNav>
),
};
+
+// =============================================================================
+// Collapsible Items
+// =============================================================================
+
+export const CollapsibleItems: Story = {
+ name: 'Collapsible Items',
+ render: () => (
+ <XDSSideNav
+ header={
+ <XDSSideNavHeading
+ icon={
+ <XDSNavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />
+ }
+ heading="My App"
+ />
+ }>
+ <XDSSideNavSection title="Collapsible (no href)">
+ <XDSSideNavItem
+ label="Settings"
+ icon={Cog6ToothIcon}
+ collapsible>
+ <XDSSideNavItem label="General" href="/settings/general" />
+ <XDSSideNavItem label="Security" href="/settings/security" />
+ <XDSSideNavItem label="Notifications" href="/settings/notifications" />
+ </XDSSideNavItem>
+ <XDSSideNavItem
+ label="Documents"
+ icon={DocumentTextIcon}
+ collapsible={{defaultIsCollapsed: true}}>
+ <XDSSideNavItem label="Drafts" href="/documents/drafts" />
+ <XDSSideNavItem label="Published" href="/documents/published" />
+ </XDSSideNavItem>
+ </XDSSideNavSection>
+ <XDSSideNavSection title="Collapsible + href">
+ <XDSSideNavItem
+ label="Settings"
+ icon={Cog6ToothIcon}
+ href="/settings"
+ collapsible>
+ <XDSSideNavItem label="General" href="/settings/general" />
+ <XDSSideNavItem label="Security" href="/settings/security" />
+ <XDSSideNavItem label="Notifications" href="/settings/notifications" />
+ </XDSSideNavItem>
+ <XDSSideNavItem
+ label="Documents"
+ icon={DocumentTextIcon}
+ href="/documents"
+ collapsible={{defaultIsCollapsed: true}}>
+ <XDSSideNavItem label="Drafts" href="/documents/drafts" />
+ <XDSSideNavItem label="Published" href="/documents/published" />
+ </XDSSideNavItem>
+ </XDSSideNavSection>
+ <XDSSideNavSection title="Collapsible + onClick">
+ <XDSSideNavItem
+ label="Settings"
+ icon={Cog6ToothIcon}
+ onClick={() => alert('Settings clicked')}
+ collapsible>
+ <XDSSideNavItem label="General" href="/settings/general" />
+ <XDSSideNavItem label="Security" href="/settings/security" />
+ <XDSSideNavItem label="Notifications" href="/settings/notifications" />
+ </XDSSideNavItem>
+ </XDSSideNavSection>
+ </XDSSideNav>
+ ),
+};
diff --git a/packages/core/src/SideNav/SideNav.doc.mjs b/packages/core/src/SideNav/SideNav.doc.mjs
index 1ad9d0ae8e..aa91dc9ec4 100644
--- a/packages/core/src/SideNav/SideNav.doc.mjs
+++ b/packages/core/src/SideNav/SideNav.doc.mjs
@@ -210,6 +210,12 @@ export const docs = {
'Visually hides the section header while keeping it accessible to screen readers.',
default: 'false',
},
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ 'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value — not an inline style object like style={{}}.',
+ },
],
},
{
@@ -586,6 +592,7 @@ export const docsDense = {
children: 'Section items.',
endContent: 'Right-side content in section header.',
isHeaderHidden: 'Visually hides section header while keeping accessible to screen readers.',
+ xstyle: 'StyleX styles for layout customization.',
},
},
{
diff --git a/packages/core/src/SideNav/XDSSideNav.test.tsx b/packages/core/src/SideNav/XDSSideNav.test.tsx
index 84814a264a..49901ebe06 100644
--- a/packages/core/src/SideNav/XDSSideNav.test.tsx
+++ b/packages/core/src/SideNav/XDSSideNav.test.tsx
@@ -625,6 +625,26 @@ describe('XDSSideNavSection', () => {
);
expect(screen.getByTestId('nav-section')).toBeInTheDocument();
});
+
+ it('forwards className to root element', () => {
+ render(
+ <XDSSideNavSection title="Main" className="custom-section">
+ <XDSSideNavItem label="Dashboard" />
+ </XDSSideNavSection>,
+ );
+ const group = screen.getByRole('group');
+ expect(group.className).toContain('custom-section');
+ });
+
+ it('forwards style to root element', () => {
+ render(
+ <XDSSideNavSection title="Main" style={{marginTop: 16}}>
+ <XDSSideNavItem label="Dashboard" />
+ </XDSSideNavSection>,
+ );
+ const group = screen.getByRole('group');
+ expect(group.style.marginTop).toBe('16px');
+ });
});
// =============================================================================
@@ -851,6 +871,141 @@ describe('XDSSideNavItem (collapsed)', () => {
// Mobile nav close-on-activate
// =============================================================================
+// =============================================================================
+// XDSSideNavItem — collapsible + href (independent toggle)
+// =============================================================================
+
+describe('XDSSideNavItem — collapsible + href', () => {
+ it('renders a link that navigates when both collapsible and href are set', () => {
+ render(
+ <XDSSideNavItem
+ label="Settings"
+ href="/settings"
+ collapsible
+ data-testid="parent">
+ <XDSSideNavItem label="General" href="/settings/general" />
+ </XDSSideNavItem>,
+ );
+ const link = screen.getByRole('link', {name: 'Settings'});
+ expect(link).toHaveAttribute('href', '/settings');
+ });
+
+ it('renders a separate toggle button for the chevron', () => {
+ render(
+ <XDSSideNavItem label="Settings" href="/settings" collapsible>
+ <XDSSideNavItem label="General" href="/settings/general" />
+ </XDSSideNavItem>,
+ );
+ const toggle = screen.getByRole('button', {name: /collapse settings/i});
+ expect(toggle).toBeInTheDocument();
+ expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('toggle button collapses children without navigating', async () => {
+ const user = userEvent.setup();
+ render(
+ <XDSSideNavItem label="Settings" href="/settings" collapsible>
+ <XDSSideNavItem label="General" href="/settings/general" />
+ </XDSSideNavItem>,
+ );
+ const toggle = screen.getByRole('button', {name: /collapse settings/i});
+ await user.click(toggle);
+ // After collapsing, aria-hidden on children container
+ expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ expect(toggle).toHaveAccessibleName('Expand Settings');
+ });
+
+ it('link does not toggle collapse when clicked', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ render(
+ <XDSSideNavItem
+ label="Settings"
+ href="/settings"
+ collapsible
+ onClick={onClick}>
+ <XDSSideNavItem label="General" href="/settings/general" />
+ </XDSSideNavItem>,
+ );
+ const link = screen.getByRole('link', {name: 'Settings'});
+ await user.click(link);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ // Children should still be visible (not collapsed)
+ const toggle = screen.getByRole('button', {name: /collapse settings/i});
+ expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('link does not have aria-expanded (toggle button owns it)', () => {
+ render(
+ <XDSSideNavItem label="Settings" href="/settings" collapsible>
+ <XDSSideNavItem label="General" href="/settings/general" />
+ </XDSSideNavItem>,
+ );
+ const link = screen.getByRole('link', {name: 'Settings'});
+ expect(link).not.toHaveAttribute('aria-expanded');
+ });
+
+ it('without href or onClick, clicking the item toggles collapse', async () => {
+ const user = userEvent.setup();
+ render(
+ <XDSSideNavItem label="Settings" collapsible>
+ <XDSSideNavItem label="General" />
+ </XDSSideNavItem>,
+ );
+ const button = screen.getByRole('button', {name: 'Settings'});
+ expect(button).toHaveAttribute('aria-expanded', 'true');
+ await user.click(button);
+ expect(button).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('with onClick (no href), clicking the label fires onClick', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ render(
+ <XDSSideNavItem label="Settings" onClick={onClick} collapsible>
+ <XDSSideNavItem label="General" />
+ </XDSSideNavItem>,
+ );
+ const primaryButton = screen.getByRole('button', {name: 'Settings'});
+ await user.click(primaryButton);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ // Children should still be visible
+ const toggle = screen.getByRole('button', {name: /collapse settings/i});
+ expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('with onClick (no href), toggle collapses without firing onClick', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ render(
+ <XDSSideNavItem label="Settings" onClick={onClick} collapsible>
+ <XDSSideNavItem label="General" />
+ </XDSSideNavItem>,
+ );
+ const toggle = screen.getByRole('button', {name: /collapse settings/i});
+ await user.click(toggle);
+ expect(onClick).not.toHaveBeenCalled();
+ expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('collapsed children are inert (not focusable)', async () => {
+ const user = userEvent.setup();
+ render(
+ <XDSSideNavItem label="Settings" collapsible>
+ <XDSSideNavItem label="General" href="/settings/general" />
+ </XDSSideNavItem>,
+ );
+ // Collapse the item
+ const button = screen.getByRole('button', {name: 'Settings'});
+ await user.click(button);
+ // The children container should have inert attribute
+ const childrenContainer = document.getElementById(
+ button.getAttribute('aria-controls')!,
+ );
+ expect(childrenContainer).toHaveAttribute('inert');
+ });
+});
+
import {XDSSideNavRenderContext} from './XDSSideNavRenderContext';
import {XDSAppShellMobileContext} from '../AppShell/XDSAppShellMobileContext';
diff --git a/packages/core/src/SideNav/XDSSideNavItem.tsx b/packages/core/src/SideNav/XDSSideNavItem.tsx
index 8d21ecf6d1..98c5d0f1f8 100644
--- a/packages/core/src/SideNav/XDSSideNavItem.tsx
+++ b/packages/core/src/SideNav/XDSSideNavItem.tsx
@@ -26,6 +26,7 @@ import {
durationVars,
easeVars,
borderVars,
+ radiusVars,
} from '../theme/tokens.stylex';
import {XDSIcon} from '../Icon';
import type {XDSIconType} from '../Icon';
@@ -93,6 +94,9 @@ const styles = stylex.create({
expandChevron: {
display: 'inline-flex',
alignItems: 'center',
+ justifyContent: 'center',
+ width: spacingVars['--spacing-6'],
+ height: spacingVars['--spacing-6'],
transitionProperty: 'transform',
transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
@@ -101,6 +105,52 @@ const styles = stylex.create({
expandChevronExpanded: {
transform: 'rotate(180deg)',
},
+ // Standalone toggle button for the chevron when collapsible + href.
+ expandToggle: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexShrink: 0,
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ color: 'inherit',
+ cursor: 'pointer',
+ borderRadius: radiusVars['--radius-element'],
+ ':hover': {
+ '@media (hover: hover)': {
+ backgroundColor: colorVars['--color-overlay-hover'],
+ },
+ },
+ ':active': {
+ backgroundColor: colorVars['--color-overlay-pressed'],
+ },
+ },
+ // Primary action element inside the split-action row (link or button).
+ // Flex:1 so it fills remaining space, giving a wide click target.
+ // Resets both link and button appearance so it blends into the row.
+ splitAction: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ flex: 1,
+ minWidth: 0,
+ color: 'inherit',
+ textDecoration: 'none',
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ fontFamily: 'inherit',
+ fontSize: 'inherit',
+ fontWeight: 'inherit',
+ lineHeight: 'inherit',
+ textAlign: 'start',
+ cursor: 'pointer',
+ },
// Popover surface for collapsed items with children
popoverSurface: {
borderWidth: borderVars['--border-width'],
@@ -128,6 +178,57 @@ const EXPANDED_COLLAPSE_STATE = {
isCollapsible: false,
};
+// =============================================================================
+// NavItemElement — resolves link vs button based on props
+// =============================================================================
+
+interface NavItemElementProps {
+ href?: string;
+ as?: XDSLinkComponentType;
+ isDisabled?: boolean;
+ onClick?: (e: React.MouseEvent) => void;
+ ref?: React.Ref<HTMLElement>;
+ children: ReactNode;
+ [key: string]: unknown;
+}
+
+/**
+ * Renders `<a>` (via LinkComponent) when `href` is set, otherwise `<button>`.
+ * Centralizes the link-vs-button decision used across all SideNavItem paths.
+ */
+function NavItemElement({
+ href,
+ as,
+ isDisabled,
+ onClick,
+ ref,
+ children,
+ ...rest
+}: NavItemElementProps) {
+ const LinkComponent = useXDSLinkComponent(as);
+ if (href && !isDisabled) {
+ return (
+ <LinkComponent
+ ref={ref as React.Ref<HTMLAnchorElement>}
+ href={href}
+ onClick={onClick}
+ {...rest}>
+ {children}
+ </LinkComponent>
+ );
+ }
+ return (
+ <button
+ ref={ref as React.Ref<HTMLButtonElement>}
+ type="button"
+ onClick={onClick}
+ disabled={isDisabled}
+ {...rest}>
+ {children}
+ </button>
+ );
+}
+
// =============================================================================
// Types
// =============================================================================
@@ -254,7 +355,6 @@ export function XDSSideNavItem({
const isInDrawer = renderMode === 'drawer' || renderMode === 'drawer-content';
const id = useId();
const hasChildren = !!children;
- const LinkComponent = useXDSLinkComponent(as);
const itemRef = useRef<HTMLDivElement>(null);
// Popover for collapsed items with children
@@ -288,12 +388,18 @@ export function XDSSideNavItem({
const displayIcon = isSelected && selectedIcon ? selectedIcon : icon;
+ // When collapsible + a primary action (href or onClick), the action and
+ // toggle are independent: clicking the label navigates/fires onClick,
+ // clicking the chevron expands/collapses children.
+ const hasPrimaryAction = !!href || !!onClick;
+ const hasIndependentToggle = isItemCollapsible && hasPrimaryAction && !isCollapsed;
+
const handleClick = (e: React.MouseEvent) => {
if (isDisabled) {
e.preventDefault();
return;
}
- if (isItemCollapsible && !isCollapsed) {
+ if (isItemCollapsible && !hasIndependentToggle && !isCollapsed) {
e.preventDefault();
toggleItemCollapse();
return;
@@ -305,6 +411,12 @@ export function XDSSideNavItem({
}
};
+ const handleToggleClick = (e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ toggleItemCollapse();
+ };
+
// Hover handlers for collapsed popover (mirrors TopNavMenu pattern)
const showTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -425,27 +537,18 @@ export function XDSSideNavItem({
'data-testid': testId,
};
- const collapsedElement =
- href && !isDisabled ? (
- <LinkComponent
- ref={ref as React.Ref<HTMLAnchorElement>}
- href={href}
- onClick={handleClick}
- {...collapsedAriaProps}
- {...collapsedItemStyles}>
- {collapsedIcon}
- </LinkComponent>
- ) : (
- <button
- ref={ref as React.Ref<HTMLButtonElement>}
- type="button"
- onClick={handleClick}
- disabled={isDisabled}
- {...collapsedAriaProps}
- {...collapsedItemStyles}>
- {collapsedIcon}
- </button>
- );
+ const collapsedElement = (
+ <NavItemElement
+ ref={ref}
+ href={href}
+ as={as}
+ isDisabled={isDisabled}
+ onClick={handleClick}
+ {...collapsedAriaProps}
+ {...collapsedItemStyles}>
+ {collapsedIcon}
+ </NavItemElement>
+ );
return (
<div ref={itemRef} {...stylex.props(styles.root)}>
@@ -468,7 +571,7 @@ export function XDSSideNavItem({
{!isCollapsed && endContent && (
<span {...stylex.props(styles.endContent)}>{endContent}</span>
)}
- {!isCollapsed && isItemCollapsible && (
+ {!isCollapsed && isItemCollapsible && !hasIndependentToggle && (
<span
{...stylex.props(
styles.expandChevron,
@@ -480,57 +583,88 @@ export function XDSSideNavItem({
</>
);
- const ariaProps = {
- 'aria-current': isSelected ? ('page' as const) : undefined,
- 'aria-disabled': isDisabled || undefined,
- 'aria-expanded': isItemCollapsible ? !isItemCollapsed : undefined,
- 'aria-controls': isItemCollapsible ? `${id}-children` : undefined,
- 'data-testid': testId,
- };
+ const navItemStyleProps = mergeProps(
+ xdsClassName('side-nav-item', {
+ size,
+ selected: isSelected ? 'selected' : null,
+ }),
+ stylex.props(
+ navItemStyles.item,
+ navItemStyles[size],
+ isSelected && navItemStyles.selected,
+ isDisabled && navItemStyles.disabled,
+ ),
+ );
- const itemElement =
- href && !isDisabled ? (
- <LinkComponent
- ref={ref as React.Ref<HTMLAnchorElement>}
+ // ── Split-action path: <div> row with <a> + <button> as siblings ──
+ //
+ // When both collapsible and href are set, we can't nest a <button>
+ // inside an <a>. Instead we use a <div> as the flex row container,
+ // an <a display:contents> for the link (with ::before covering the row),
+ // and a <button> sibling lifted above the overlay via z-index.
+
+ // ── Split-action path: primary element + toggle button as siblings ──
+ //
+ // When collapsible and a primary action (href or onClick) are both set,
+ // we render a <div> row with the primary element and chevron toggle as
+ // siblings. This avoids nesting interactive elements (<button> inside <a>).
+
+ let itemElement;
+
+ if (hasIndependentToggle) {
+ itemElement = (
+ <div
+ aria-current={isSelected ? ('page' as const) : undefined}
+ data-testid={testId}
+ {...navItemStyleProps}>
+ <NavItemElement
+ ref={ref}
+ href={href}
+ as={as}
+ isDisabled={isDisabled}
+ onClick={handleClick}
+ {...stylex.props(styles.splitAction)}>
+ {itemContent}
+ </NavItemElement>
+ <button
+ type="button"
+ onClick={handleToggleClick}
+ aria-label={isItemCollapsed ? `Expand ${label}` : `Collapse ${label}`}
+ aria-expanded={!isItemCollapsed}
+ aria-controls={`${id}-children`}
+ {...stylex.props(styles.expandToggle)}>
+ <span
+ {...stylex.props(
+ styles.expandChevron,
+ !isItemCollapsed && styles.expandChevronExpanded,
+ )}>
+ {getIcon('chevronDown')}
+ </span>
+ </button>
+ </div>
+ );
+ } else {
+ const ariaProps = {
+ 'aria-current': isSelected ? ('page' as const) : undefined,
+ 'aria-disabled': isDisabled || undefined,
+ 'aria-expanded': isItemCollapsible ? !isItemCollapsed : undefined,
+ 'aria-controls': isItemCollapsible ? `${id}-children` : undefined,
+ 'data-testid': testId,
+ };
+
+ itemElement = (
+ <NavItemElement
+ ref={ref}
href={href}
+ as={as}
+ isDisabled={isDisabled}
onClick={handleClick}
{...ariaProps}
- {...mergeProps(
- xdsClassName('side-nav-item', {
- size,
- selected: isSelected ? 'selected' : null,
- }),
- stylex.props(
- navItemStyles.item,
- navItemStyles[size],
- isSelected && navItemStyles.selected,
- isDisabled && navItemStyles.disabled,
- ),
- )}>
+ {...navItemStyleProps}>
{itemContent}
- </LinkComponent>
- ) : (
- <button
- ref={ref as React.Ref<HTMLButtonElement>}
- type="button"
- onClick={handleClick}
- disabled={isDisabled}
- {...ariaProps}
- {...mergeProps(
- xdsClassName('side-nav-item', {
- size,
- selected: isSelected ? 'selected' : null,
- }),
- stylex.props(
- navItemStyles.item,
- navItemStyles[size],
- isSelected && navItemStyles.selected,
- isDisabled && navItemStyles.disabled,
- ),
- )}>
- {itemContent}
- </button>
+ </NavItemElement>
);
+ }
const item = (
<div ref={itemRef} {...stylex.props(styles.root)}>
@@ -541,6 +675,7 @@ export function XDSSideNavItem({
role="group"
aria-labelledby={`${id}-label`}
aria-hidden={isItemCollapsed}
+ inert={isItemCollapsed ? true : undefined}
{...stylex.props(
styles.childrenCollapsible,
isItemCollapsed && styles.childrenCollapsed,
diff --git a/packages/core/src/SideNav/XDSSideNavSection.tsx b/packages/core/src/SideNav/XDSSideNavSection.tsx
index 9d280c46f4..79bc035d80 100644
--- a/packages/core/src/SideNav/XDSSideNavSection.tsx
+++ b/packages/core/src/SideNav/XDSSideNavSection.tsx
@@ -17,6 +17,7 @@
import {useId, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
+import type {StyleXStyles} from '@stylexjs/stylex';
import {
colorVars,
spacingVars,
@@ -108,6 +109,26 @@ export interface XDSSideNavSectionProps {
* @default false
*/
isHeaderHidden?: boolean;
+ /**
+ * StyleX styles created via `stylex.create()`. Merged with the component's
+ * base styles inside a single `stylex.props()` call for optimal deduplication.
+ *
+ * @example
+ * ```
+ * const overrides = stylex.create({ root: { marginBottom: 8 } });
+ * <XDSSideNavSection title="Main" xstyle={overrides.root}>...</XDSSideNavSection>
+ * ```
+ */
+ xstyle?: StyleXStyles;
+ /**
+ * CSS class name(s) appended to the root element.
+ * If you're using StyleX, prefer `xstyle` for optimal style deduplication.
+ */
+ className?: string;
+ /**
+ * Inline styles to apply to the root element.
+ */
+ style?: React.CSSProperties;
/**
* Test ID for the section element.
*/
@@ -138,6 +159,9 @@ export function XDSSideNavSection({
children,
endContent,
isHeaderHidden = false,
+ xstyle,
+ className,
+ style,
'data-testid': testId,
}: XDSSideNavSectionProps) {
const {isCollapsed} = useXDSSideNavCollapse();
@@ -181,10 +205,14 @@ export function XDSSideNavSection({
data-testid={testId}
{...mergeProps(
xdsClassName('side-nav-section'),
- stylex.props(styles.root),
+ stylex.props(styles.root, xstyle),
+ className,
+ style,
)}>
<div
- {...mergeProps(stylex.props(styles.header), {style: shouldHideHeader ? visuallyHiddenStyle : undefined})}>
+ {...mergeProps(stylex.props(styles.header), {
+ style: shouldHideHeader ? visuallyHiddenStyle : undefined,
+ })}>
{headerContent}
</div>
<div {...stylex.props(styles.items)}>{children}</div>