Skip to content

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

TypeScript

SideNav: fix the blocking findings from the component audit (52.6 → 79.1) (#4880)

Cindy Zhangf4868b246603
diff --git a/.changeset/sidenav-audit-hardening.md b/.changeset/sidenav-audit-hardening.md
new file mode 100644
index 0000000000..7ab499275e
--- /dev/null
+++ b/.changeset/sidenav-audit-hardening.md
@@ -0,0 +1,11 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] SideNav: a hardening pass over the family, driven by the component audit. Accessibility, theming, passthrough and code-health defects across `SideNavItem`, `SideNavHeading`, `SideNavSection`, `SideNavCollapseButton` and the `navItemStyles` module the TopNav drawer modes share — the motion guards, the untranslated flyout name, the hand-rolled visually-hidden block, the dropped `...rest`, the missing theming state, the uncleaned timers, and the hand-rolled hover intent, which is now the shared `useMenuHover`. Nav rows also adopt the shared focus outline from #4654, so a keyboard-focused row is ringed with the system's `2px --color-accent` at `3px` offset in every theme instead of falling through to the browser's own ring; in a split-action row the link and the chevron toggle are ringed individually, since they are separate tab stops.
+
+Three visual fixes came out of review. The collapsed submenu flyout was painting a second, square-cornered surface inside the popover's rounded one, and insetting its own content by 4px instead of standing off the rail — both gone, with the gap moved to the positioned layer where `DropdownMenu` keeps it. The selected row now survives `forced-colors: active`: it marked the current page with a 6% background tint, which forced colors flatten away entirely, and it now paints `Highlight`/`HighlightText` like `ToggleButton` and `SegmentedControlItem`. And the footer icon row comes out one size, with the collapse chevron centred rather than seated 2.42px high on a stray text baseline.
+
+Four changes are visible to a consumer. **Hover on a collapsed item's flyout** is now gated on `(hover: hover)` and only closes on `mouseleave` if hover opened it, and a click-to-dismiss no longer springs back open under a stationary pointer. **The footer icon rows cascade a `sm` size** through `SizeContext`, so an unsized `Button` passed to `footerIcons` now matches the built-in collapse button instead of rendering a size larger — pass an explicit `size` to opt out. **`SideNavCollapseButton` takes a `size`**, for placements outside the nav that have no row to inherit from. And **`SideNavCollapseButton` takes the controlled `collapsible` config** — the same `{isCollapsed, onCollapsedChange}` object handed to SideNav — which is how a button rendered outside the sidenav now stays in step with it. `handleRef` on both components is deprecated in its favour: the state the consumer already owns reaches the button through props, with no imperative handle in between.
+
+@cixzhang
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index d0a3f55f17..aaeadd20fe 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -935,6 +935,10 @@
"defaultMessage": "Collapse {label}",
"description": "Screen-reader-only label on the same chevron when the group is expanded. Example: `Collapse Settings`. Pairs with `sideNavItem.expand`."
},
+ "@astryx.sideNavItem.submenuLabel": {
+ "defaultMessage": "{label} submenu",
+ "description": "Accessible name for the flyout dialog that opens from a collapsed (icon-only) SideNav item to show its sub-items. {label} is the parent item's label. Example: `Settings submenu`."
+ },
"@astryx.tableFiltering.filterByColumn": {
"defaultMessage": "Filter {header}",
"description": "Triple-use string on per-column filter controls: visible label, placeholder, AND aria label. `{header}` is the column header — example: `Filter Name`. Keep short."
diff --git a/packages/core/src/NavItem/navItemStyles.stylex.ts b/packages/core/src/NavItem/navItemStyles.stylex.ts
index 3b266dc9bc..7d0703f931 100644
--- a/packages/core/src/NavItem/navItemStyles.stylex.ts
+++ b/packages/core/src/NavItem/navItemStyles.stylex.ts
@@ -11,8 +11,13 @@
* disabled state) so all nav-like components stay in sync — especially important
* when TopNav items render inside MobileNav drawers alongside SideNav items.
*
- * Individual components layer their own overrides (e.g. collapsed mode, indentation,
- * focus outlines) via stylex.props composition.
+ * Individual components layer their own overrides (e.g. collapsed mode,
+ * indentation) via stylex.props composition.
+ *
+ * The focus ring is not defined here. Compose
+ * `focusOutlineProps.focusVisible` (utils/focusOutline.stylex.ts) at the call
+ * site, on whichever element actually takes focus — in a split-action row that
+ * is the link and the toggle, not the row that contains them.
*/
export type NavItemSize = 'sm' | 'md' | 'lg';
@@ -79,15 +84,36 @@ export const navItemStyles = stylex.create({
/** Selected/active page indicator — deemphasized background, medium weight */
selected: {
- backgroundColor: colorVars['--color-neutral'],
+ // Forced colors flatten `--color-neutral` away, leaving the current page
+ // unmarked; Highlight/HighlightText is the platform convention, as in
+ // ToggleButton and SegmentedControlItem. No `forced-color-adjust: none`
+ // here — a nav row is not a native control, so the keywords land without
+ // it, and it would inherit into `endContent` and pin a Badge's own fill.
+ backgroundColor: {
+ default: colorVars['--color-neutral'],
+ '@media (forced-colors: active)': 'Highlight',
+ },
+ color: {
+ default: null,
+ '@media (forced-colors: active)': 'HighlightText',
+ },
fontWeight: fontWeightVars['--font-weight-medium'],
':hover': {
'@media (hover: hover)': {
- backgroundColor: colorVars['--color-neutral'],
+ backgroundColor: {
+ default: colorVars['--color-neutral'],
+ // Nested, not a sibling `(hover: hover) and (forced-colors:
+ // active)` block: as siblings `item`'s hover overlay ties on
+ // specificity and wins on source order, erasing the fill.
+ '@media (forced-colors: active)': 'Highlight',
+ },
},
},
':active': {
- backgroundColor: colorVars['--color-neutral'],
+ backgroundColor: {
+ default: colorVars['--color-neutral'],
+ '@media (forced-colors: active)': 'Highlight',
+ },
},
},
diff --git a/packages/core/src/SideNav/SideNav.doc.mjs b/packages/core/src/SideNav/SideNav.doc.mjs
index 4b3b78848a..bbe19f7358 100644
--- a/packages/core/src/SideNav/SideNav.doc.mjs
+++ b/packages/core/src/SideNav/SideNav.doc.mjs
@@ -21,7 +21,7 @@ export const docs = {
targets: [
{className: 'astryx-side-nav', visualProps: ['mode']},
{className: 'astryx-side-nav-heading'},
- {className: 'astryx-side-nav-item', visualProps: ['size'], states: ['selected']},
+ {className: 'astryx-side-nav-item', visualProps: ['size'], states: ['selected', 'disabled']},
{className: 'astryx-side-nav-section'},
],
},
@@ -85,7 +85,7 @@ export const docs = {
{
name: 'footerIcons',
type: 'ReactNode',
- description: 'Footer icon bar.',
+ description: "Footer icon bar. The row cascades a 'sm' size to the interactive children it contains, so its icons and the built-in collapse button come out one height; pass an explicit size on a child to opt out.",
slotElements: [
{
__element: 'Icon',
@@ -99,7 +99,7 @@ export const docs = {
{
name: 'collapsible',
type: 'boolean | { defaultIsCollapsed?: boolean; isCollapsed?: boolean; onCollapsedChange?: (isCollapsed: boolean) => void; hasButton?: boolean; buttonLabel?: string }',
- description: 'Enables collapse behavior. true for uncontrolled with default toggle button, or an object for controlled mode and advanced config (defaultIsCollapsed, isCollapsed + onCollapsedChange, hasButton, buttonLabel).',
+ description: 'Enables collapse behavior. true for uncontrolled with default toggle button, or an object for controlled mode and advanced config (defaultIsCollapsed, isCollapsed + onCollapsedChange, hasButton, buttonLabel). A controlled config can also be passed to a SideNavCollapseButton rendered outside this SideNav, so both share one state.',
default: 'false',
},
{
@@ -111,7 +111,7 @@ export const docs = {
{
name: 'handleRef',
type: 'Ref<SideNavImperativeCollapseHandle>',
- description: 'Imperative collapse handle for SideNavCollapseButton instances rendered outside this SideNav. Separate from `ref`, which continues to expose the root HTMLElement.',
+ description: 'Deprecated. Imperative collapse handle for SideNavCollapseButton instances rendered outside this SideNav; hand both the same controlled collapsible config instead. Separate from `ref`, which continues to expose the root HTMLElement.',
},
{
name: 'xstyle',
@@ -131,6 +131,9 @@ export const docs = {
bestPractices: [
{guidance: true, description: 'Use sections to group related navigation items and help users scan for their destination.'},
{guidance: true, description: 'Pair outline and filled icon variants so the selected state is visually distinct.'},
+ {guidance: true, description: 'Mark the current page with isSelected — it sets aria-current="page", so the current destination is announced rather than carried by color alone.'},
+ {guidance: true, description: 'SideNav renders a navigation landmark, and a collapsible item follows the WAI-ARIA APG Disclosure pattern (https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/): the toggle carries aria-expanded and aria-controls, and the group it owns is inert while collapsed. Keep item labels short — they are the accessible name in both expanded and icon-only modes.'},
+ {guidance: true, description: 'While the nav is collapsed, an item with children shows them in a submenu flyout. On a device that can hover, pointing at the item opens it after a short delay and moving away closes it; a flyout opened by clicking stays open until it is dismissed. On touch, it opens on tap. Do not put an action in there that has no other route to it.'},
{guidance: false, description: 'Include a SideNavHeading when a TopNav is already providing app identity; this duplicates branding.'},
{guidance: false, description: 'Use for filtering content; use tabs or filter buttons instead.'},
],
@@ -150,6 +153,9 @@ export const docsZh = {
bestPractices: [
{guidance: true, description: 'Use sections to group related navigation items and help users scan for their destination.'},
{guidance: true, description: 'Pair outline and filled icon variants so the selected state is visually distinct.'},
+ {guidance: true, description: 'Mark the current page with isSelected — it sets aria-current="page", so the current destination is announced rather than carried by color alone.'},
+ {guidance: true, description: 'SideNav renders a navigation landmark, and a collapsible item follows the WAI-ARIA APG Disclosure pattern (https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/): the toggle carries aria-expanded and aria-controls, and the group it owns is inert while collapsed. Keep item labels short — they are the accessible name in both expanded and icon-only modes.'},
+ {guidance: true, description: 'While the nav is collapsed, an item with children shows them in a submenu flyout. On a device that can hover, pointing at the item opens it after a short delay and moving away closes it; a flyout opened by clicking stays open until it is dismissed. On touch, it opens on tap. Do not put an action in there that has no other route to it.'},
{guidance: false, description: 'Include a SideNavHeading when a TopNav is already providing app identity; this duplicates branding.'},
{guidance: false, description: 'Use for filtering content; use tabs or filter buttons instead.'},
],
@@ -169,6 +175,9 @@ export const docsDense = {
bestPractices: [
{guidance: true, description: 'Use sections to group related navigation items and help users scan for their destination.'},
{guidance: true, description: 'Pair outline and filled icon variants so the selected state is visually distinct.'},
+ {guidance: true, description: 'Mark the current page with isSelected — it sets aria-current="page", so the current destination is announced rather than carried by color alone.'},
+ {guidance: true, description: 'SideNav renders a navigation landmark, and a collapsible item follows the WAI-ARIA APG Disclosure pattern (https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/): the toggle carries aria-expanded and aria-controls, and the group it owns is inert while collapsed. Keep item labels short — they are the accessible name in both expanded and icon-only modes.'},
+ {guidance: true, description: 'While the nav is collapsed, an item with children shows them in a submenu flyout. On a device that can hover, pointing at the item opens it after a short delay and moving away closes it; a flyout opened by clicking stays open until it is dismissed. On touch, it opens on tap. Do not put an action in there that has no other route to it.'},
{guidance: false, description: 'Include a SideNavHeading when a TopNav is already providing app identity; this duplicates branding.'},
{guidance: false, description: 'Use for filtering content; use tabs or filter buttons instead.'},
],
diff --git a/packages/core/src/SideNav/SideNav.test.tsx b/packages/core/src/SideNav/SideNav.test.tsx
index 6c8b0c0ef4..7fece66d65 100644
--- a/packages/core/src/SideNav/SideNav.test.tsx
+++ b/packages/core/src/SideNav/SideNav.test.tsx
@@ -10,16 +10,22 @@
*/
import React from 'react';
-import {describe, it, expect, vi} from 'vitest';
-import {render, screen, act, fireEvent} from '@testing-library/react';
+import {describe, it, expect, vi, afterEach} from 'vitest';
+import {render, screen, act, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {useRef, useState, type ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {getForcedColorsRules} from '../__tests__/forcedColors';
+import {Button} from '../Button';
import {SideNav} from './SideNav';
import {SideNavCollapseButton} from './SideNavCollapseButton';
import {SideNavHeading} from './SideNavHeading';
import {SideNavItem} from './SideNavItem';
import {SideNavSection} from './SideNavSection';
import {LinkProvider} from '../Link/LinkProvider';
+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
+import pseudoCatalog from '../../locales/pseudo.json';
import {
SideNavCollapseContext,
type SideNavImperativeCollapseHandle,
@@ -1174,6 +1180,231 @@ describe('SideNavItem (collapsed)', () => {
});
});
+// =============================================================================
+// SideNavItem — collapsed submenu hover intent (useMenuHover adoption, C12)
+// =============================================================================
+
+/**
+ * Pin the ambient pointer modality: the global `matchMedia` stub never
+ * matches, which reads as a coarse pointer, so hover assertions must opt in.
+ */
+function stubPointerModality(modality: 'fine' | 'coarse') {
+ vi.stubGlobal('matchMedia', (query: string) => ({
+ matches: modality === 'fine' && query.includes('hover: hover'),
+ media: query,
+ onchange: null,
+ addListener: () => {},
+ removeListener: () => {},
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ dispatchEvent: () => false,
+ }));
+}
+
+/** The hook's hover-intent delays: 150 ms to show, 200 ms to hide. */
+const SHOW_DELAY = 150;
+const HIDE_DELAY = 200;
+
+describe('SideNavItem — collapsed submenu hover intent', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ function renderFlyout() {
+ renderCollapsed(
+ <SideNavItem label="Settings" icon={StubIcon} data-testid="parent">
+ <SideNavItem label="General" href="/settings/general" />
+ <SideNavItem label="Security" href="/settings/security" />
+ </SideNavItem>,
+ );
+ return screen.getByTestId('parent');
+ }
+
+ const advance = (ms: number) =>
+ act(() => {
+ vi.advanceTimersByTime(ms);
+ });
+
+ it('opens the flyout only after the hover-intent delay', () => {
+ stubPointerModality('fine');
+ vi.useFakeTimers();
+ const trigger = renderFlyout();
+
+ fireEvent.mouseEnter(trigger);
+ // A pointer merely passing over the icon must not open anything.
+ advance(SHOW_DELAY - 1);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ advance(1);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('closes a hover-opened flyout when the pointer leaves', () => {
+ stubPointerModality('fine');
+ vi.useFakeTimers();
+ const trigger = renderFlyout();
+
+ fireEvent.mouseEnter(trigger);
+ advance(SHOW_DELAY);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ fireEvent.mouseLeave(trigger);
+ advance(HIDE_DELAY);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('keeps a click-opened flyout open when the pointer leaves', () => {
+ stubPointerModality('fine');
+ vi.useFakeTimers();
+ const trigger = renderFlyout();
+
+ fireEvent.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // Clicking is a commitment: the flyout outlives the pointer.
+ fireEvent.mouseLeave(trigger);
+ advance(HIDE_DELAY * 2);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('does not spring back open when a click dismisses it under a stationary pointer', () => {
+ stubPointerModality('fine');
+ vi.useFakeTimers();
+ const trigger = renderFlyout();
+
+ fireEvent.mouseEnter(trigger);
+ advance(SHOW_DELAY);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // The pointer never left, so dismissing fires a fresh mouseenter as the
+ // flyout unmounts — which used to reopen what the user just closed.
+ fireEvent.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ fireEvent.mouseEnter(trigger);
+ advance(SHOW_DELAY);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ // One-shot, not a latch: a deliberate leave-and-return opens it again.
+ fireEvent.mouseLeave(trigger);
+ fireEvent.mouseEnter(trigger);
+ advance(SHOW_DELAY);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('schedules no hover timers on a coarse pointer', () => {
+ stubPointerModality('coarse');
+ vi.useFakeTimers();
+ const trigger = renderFlyout();
+
+ // A touch tap synthesises mouseenter. On a device that cannot hover there
+ // is no hover intent to read, so nothing may be scheduled from it.
+ fireEvent.mouseEnter(trigger);
+ expect(vi.getTimerCount()).toBe(0);
+
+ advance(SHOW_DELAY * 2);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ // Tapping still opens it — the touch path goes through click, untouched.
+ fireEvent.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('does not open the hover popover after the item unmounts', () => {
+ stubPointerModality('fine');
+ vi.useFakeTimers();
+ const {unmount} = render(
+ <SideNavCollapseContext
+ value={{isCollapsed: true, toggle: () => {}, isCollapsible: true}}>
+ <SideNavItem label="Settings" icon={StubIcon} data-testid="parent">
+ <SideNavItem label="General" href="/settings/general" />
+ </SideNavItem>
+ </SideNavCollapseContext>,
+ );
+
+ fireEvent.mouseEnter(screen.getByTestId('parent'));
+ expect(vi.getTimerCount()).toBeGreaterThan(0);
+
+ unmount();
+
+ // The hook owns the timer cleanup now; it still has to hold.
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('leaves arrow keys in the flyout to the browser', async () => {
+ stubPointerModality('fine');
+ const user = userEvent.setup();
+ renderCollapsed(
+ <SideNavItem label="Settings" icon={StubIcon} data-testid="parent">
+ <SideNavItem label="General" href="/settings/general" />
+ <SideNavItem label="Security" href="/settings/security" />
+ </SideNavItem>,
+ );
+
+ const trigger = screen.getByTestId('parent');
+ await user.click(trigger);
+
+ // The flyout renders as a native popover, which jsdom leaves
+ // `display: none`, so its contents are outside the default a11y-tree
+ // queries.
+ const first = screen.getByRole('link', {name: 'General', hidden: true});
+ first.focus();
+
+ // A dialog of links, not a menu of menuitems: wiring the hook's
+ // list-focus half would preventDefault every arrow key and find no
+ // `[role="menuitem"]` to move to.
+ const notPrevented = fireEvent.keyDown(first, {key: 'ArrowDown'});
+ expect(notPrevented).toBe(true);
+ expect(first).toHaveFocus();
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('opens from the keyboard, moves focus into the flyout, and restores it on Escape', async () => {
+ stubPointerModality('fine');
+ const user = userEvent.setup();
+ renderCollapsed(
+ <SideNavItem label="Settings" icon={StubIcon} data-testid="parent">
+ <SideNavItem label="General" href="/settings/general" />
+ <SideNavItem label="Security" href="/settings/security" />
+ </SideNavItem>,
+ );
+
+ const trigger = screen.getByTestId('parent');
+ trigger.focus();
+ await user.keyboard('{Enter}');
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ // Keyboard opens move focus in; hover opens leave it on the trigger.
+ await waitFor(() =>
+ expect(
+ screen.getByRole('link', {name: 'General', hidden: true}),
+ ).toHaveFocus(),
+ );
+
+ await user.keyboard('{Escape}');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await waitFor(() => expect(trigger).toHaveFocus());
+ });
+
+ it('leaves focus on the trigger when hover opens the flyout', () => {
+ stubPointerModality('fine');
+ vi.useFakeTimers();
+ const trigger = renderFlyout();
+ trigger.focus();
+
+ fireEvent.mouseEnter(trigger);
+ advance(SHOW_DELAY);
+ act(() => {
+ vi.advanceTimersToNextFrame();
+ });
+
+ // `skipAutoFocus`: a mid-hover pointer user keeps their caret.
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(trigger).toHaveFocus();
+ });
+});
+
// =============================================================================
// Mobile nav close-on-activate
// =============================================================================
@@ -1393,3 +1624,541 @@ describe('SideNavItem — mobile drawer close-on-activate', () => {
expect(closeMobileNav).not.toHaveBeenCalled();
});
});
+
+// =============================================================================
+// Keyboard operation (audit §6 V6)
+// =============================================================================
+
+describe('SideNav keyboard operation', () => {
+ it('reaches every nav item with Tab, in document order', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNav>
+ <SideNavSection title="Main">
+ <SideNavItem label="Dashboard" href="/dashboard" />
+ <SideNavItem label="Projects" href="/projects" />
+ <SideNavItem label="Settings" onClick={() => {}} />
+ </SideNavSection>
+ </SideNav>,
+ );
+
+ await user.tab();
+ expect(screen.getByRole('link', {name: 'Dashboard'})).toHaveFocus();
+ await user.tab();
+ expect(screen.getByRole('link', {name: 'Projects'})).toHaveFocus();
+ await user.tab();
+ expect(screen.getByRole('button', {name: 'Settings'})).toHaveFocus();
+ });
+
+ it('skips a disabled item in the tab order', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNav>
+ <SideNavItem label="Dashboard" onClick={() => {}} />
+ <SideNavItem label="Archived" onClick={() => {}} isDisabled />
+ <SideNavItem label="Settings" onClick={() => {}} />
+ </SideNav>,
+ );
+
+ await user.tab();
+ expect(screen.getByRole('button', {name: 'Dashboard'})).toHaveFocus();
+ await user.tab();
+ expect(screen.getByRole('button', {name: 'Settings'})).toHaveFocus();
+ });
+
+ it('toggles a collapsible group with Enter and with Space', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNavItem label="Settings" onClick={() => {}} collapsible>
+ <SideNavItem label="General" href="/settings/general" />
+ </SideNavItem>,
+ );
+
+ const toggle = screen.getByRole('button', {name: 'Collapse Settings'});
+ toggle.focus();
+
+ await user.keyboard('{Enter}');
+ expect(toggle).toHaveAttribute('aria-expanded', 'false');
+
+ await user.keyboard(' ');
+ expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('activates a button item with Enter', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ render(<SideNavItem label="Log out" onClick={onClick} />);
+
+ await user.tab();
+ await user.keyboard('{Enter}');
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('opens the collapsed submenu from the keyboard and closes it with Escape', async () => {
+ const user = userEvent.setup();
+ renderCollapsed(
+ <SideNavItem label="Settings" icon={StubIcon} data-testid="parent">
+ <SideNavItem label="General" href="/settings/general" />
+ </SideNavItem>,
+ );
+
+ const trigger = screen.getByTestId('parent');
+ trigger.focus();
+ await user.keyboard('{Enter}');
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ await user.keyboard('{Escape}');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+});
+
+// =============================================================================
+// Focus management (audit §6 V7)
+// =============================================================================
+
+describe('SideNav focus management', () => {
+ it('keeps focus on the toggle when a group collapses', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNavItem label="Settings" href="/settings" collapsible>
+ <SideNavItem label="General" href="/settings/general" />
+ </SideNavItem>,
+ );
+
+ const toggle = screen.getByRole('button', {name: 'Collapse Settings'});
+ await user.click(toggle);
+
+ expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ expect(toggle).toHaveFocus();
+ });
+
+ it('does not leave focus on a child that the group just hid', async () => {
+ const user = userEvent.setup();
+ render(
+ <SideNavItem label="Settings" href="/settings" collapsible>
+ <SideNavItem label="General" href="/settings/general" />
+ </SideNavItem>,
+ );
+
+ const child = screen.getByRole('link', {name: 'General'});
+ child.focus();
+
+ const toggle = screen.getByRole('button', {name: 'Collapse Settings'});
+ await user.click(toggle);
+
+ // The collapsed group is `inert`: focus may land neither inside it nor
+ // on <body>.
+ expect(document.activeElement).not.toBe(child);
+ expect(document.activeElement).not.toBe(document.body);
+ expect(toggle).toHaveFocus();
+ });
+
+ it('returns focus to the trigger when the collapsed submenu closes', async () => {
+ const user = userEvent.setup();
+ renderCollapsed(
+ <SideNavItem label="Settings" icon={StubIcon} data-testid="parent">
+ <SideNavItem label="General" href="/settings/general" />
+ </SideNavItem>,
+ );
+
+ const trigger = screen.getByTestId('parent');
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ await user.keyboard('{Escape}');
+ // The layer restores focus asynchronously after it closes.
+ await waitFor(() => expect(trigger).toHaveFocus());
+ });
+});
+
+// =============================================================================
+// Audit regressions — the defects this pass fixed
+// =============================================================================
+
+describe('SideNav audit regressions', () => {
+ it('names the collapsed submenu dialog from the catalog, not a concatenation', async () => {
+ const user = userEvent.setup();
+ renderCollapsed(
+ <SideNavItem label="Settings" icon={StubIcon} data-testid="parent">
+ <SideNavItem label="General" href="/settings/general" />
+ </SideNavItem>,
+ );
+
+ await user.click(screen.getByTestId('parent'));
+ const dialog = document.querySelector('[role="dialog"]');
+ expect(dialog).not.toBeNull();
+ expect(dialog).toHaveAttribute('aria-label', 'Settings submenu');
+ });
+
+ it('translates the collapsed submenu dialog name', async () => {
+ const user = userEvent.setup();
+ render(
+ <InternationalizationProvider
+ locale="pseudo"
+ messages={{pseudo: pseudoCatalog}}>
+ <SideNavCollapseContext
+ value={{isCollapsed: true, toggle: () => {}, isCollapsible: true}}>
+ <SideNavItem label="Settings" icon={StubIcon} data-testid="parent">
+ <SideNavItem label="General" href="/settings/general" />
+ </SideNavItem>
+ </SideNavCollapseContext>
+ </InternationalizationProvider>,
+ );
+
+ await user.click(screen.getByTestId('parent'));
+ const label = document
+ .querySelector('[role="dialog"]')
+ ?.getAttribute('aria-label');
+
+ // A concatenated `${label} submenu` would stay plain English here.
+ expect(label).toContain('Settings');
+ expect(label).not.toBe('Settings submenu');
+ });
+
+ it('forwards unrecognised props on SideNavItem through to the control', () => {
+ render(
+ <SideNavItem
+ label="Dashboard"
+ href="/dashboard"
+ data-analytics="nav-dashboard"
+ aria-describedby="hint"
+ />,
+ );
+
+ const link = screen.getByRole('link', {name: 'Dashboard'});
+ expect(link).toHaveAttribute('data-analytics', 'nav-dashboard');
+ expect(link).toHaveAttribute('aria-describedby', 'hint');
+ });
+
+ it('forwards unrecognised props on a collapsed SideNavItem', () => {
+ renderCollapsed(
+ <SideNavItem
+ label="Dashboard"
+ icon={StubIcon}
+ href="/dashboard"
+ data-analytics="nav-dashboard"
+ />,
+ );
+
+ expect(screen.getByRole('link')).toHaveAttribute(
+ 'data-analytics',
+ 'nav-dashboard',
+ );
+ });
+
+ it('exposes a disabled item as a theming state', () => {
+ render(<SideNavItem label="Archived" onClick={() => {}} isDisabled />);
+
+ expect(screen.getByRole('button', {name: 'Archived'})).toHaveAttribute(
+ 'data-disabled',
+ 'disabled',
+ );
+ });
+
+ it('keeps a hidden section header readable by assistive technology', () => {
+ render(
+ <SideNavSection title="Main" isHeaderHidden>
+ <SideNavItem label="Dashboard" href="/dashboard" />
+ </SideNavSection>,
+ );
+
+ expect(screen.getByRole('group')).toHaveAccessibleName('Main');
+ expect(screen.getByText('Main')).toBeInTheDocument();
+ });
+
+ it('keeps a SideNavCollapseButton outside the sidenav in step with it', async () => {
+ const user = userEvent.setup();
+
+ function App() {
+ const [isCollapsed, setIsCollapsed] = useState(false);
+ const collapsible = {isCollapsed, onCollapsedChange: setIsCollapsed};
+ return (
+ <>
+ <SideNavCollapseButton collapsible={collapsible} />
+ <SideNav collapsible={{...collapsible, hasButton: false}}>
+ <SideNavItem label="Dashboard" href="/dashboard" />
+ </SideNav>
+ </>
+ );
+ }
+
+ render(<App />);
+
+ await user.click(screen.getByRole('button', {name: 'Collapse sidebar'}));
+ const expand = await screen.findByRole('button', {name: 'Expand sidebar'});
+
+ await user.click(expand);
+ expect(
+ await screen.findByRole('button', {name: 'Collapse sidebar'}),
+ ).toBeInTheDocument();
+ });
+});
+
+// =============================================================================
+// 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.
+// =============================================================================
+
+const sharedFocusRingClasses = stylex
+ .props(focusOutlineStyles.focusVisible)
+ .className!.split(' ');
+
+function expectSharedFocusRing(el: Element) {
+ const classes = el.className.split(' ');
+ for (const c of sharedFocusRingClasses) {
+ expect(classes).toContain(c);
+ }
+}
+
+function expectNoSharedFocusRing(el: Element) {
+ const classes = el.className.split(' ');
+ for (const c of sharedFocusRingClasses) {
+ expect(classes).not.toContain(c);
+ }
+}
+
+describe('SideNav focus ring (A15)', () => {
+ it('draws the shared ring on a link item', () => {
+ render(<SideNavItem label="Dashboard" href="/dashboard" />);
+ expectSharedFocusRing(screen.getByRole('link', {name: 'Dashboard'}));
+ });
+
+ it('draws the shared ring on a button item', () => {
+ render(<SideNavItem label="Dashboard" onClick={() => {}} />);
+ expectSharedFocusRing(screen.getByRole('button', {name: 'Dashboard'}));
+ });
+
+ it('draws the shared ring on a collapsed icon-only item', () => {
+ renderCollapsed(
+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />,
+ );
+ expectSharedFocusRing(screen.getByRole('link', {name: 'Dashboard'}));
+ });
+
+ it('draws the shared ring on a collapsed submenu trigger', () => {
+ renderCollapsed(
+ <SideNavItem label="Settings" icon={StubIcon}>
+ <SideNavItem label="General" href="/settings/general" />
+ </SideNavItem>,
+ );
+ expectSharedFocusRing(screen.getByRole('button', {name: 'Settings'}));
+ });
+
+ it('rings each focusable of a split-action row, and not the row itself', () => {
+ render(
+ <SideNavItem label="Settings" href="/settings" collapsible>
+ <SideNavItem label="General" href="/settings/general" />
+ </SideNavItem>,
+ );
+
+ const link = screen.getByRole('link', {name: 'Settings'});
+ const toggle = screen.getByRole('button', {name: 'Collapse Settings'});
+ expectSharedFocusRing(link);
+ expectSharedFocusRing(toggle);
+
+ // A presentational <div> holding two independent tab stops; ringing it
+ // too would paint a second outline around the whole row.
+ const row = link.parentElement!;
+ expect(row.tagName).toBe('DIV');
+ expect(row).toContainElement(toggle);
+ expectNoSharedFocusRing(row);
+ });
+
+ 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/}));
+ });
+
+ it('draws the shared ring on a collapsed heading link', () => {
+ renderCollapsed(
+ <SideNavHeading heading="My App" headingHref="/" icon={<span>i</span>} />,
+ );
+ expectSharedFocusRing(screen.getByRole('link', {name: 'My App'}));
+ });
+
+ it('draws the shared ring on the heading menu trigger', () => {
+ render(<SideNavHeading heading="My App" menu={<div>menu</div>} />);
+ expectSharedFocusRing(screen.getByRole('button', {name: 'Open menu'}));
+ });
+});
+
+// jsdom cannot emulate forced-colors rendering, so these assert that the
+// compiled output carries the rules the selected row relies on. The rendered
+// behaviour was measured in Chromium under `forced-colors: active` — see the
+// evidence on #4880.
+describe('forced colors (WCAG 1.4.11)', () => {
+ it('compiles forced-colors overrides so the current page survives Windows High Contrast', () => {
+ render(
+ <SideNav>
+ <SideNavSection title="Main">
+ <SideNavItem label="Dashboard" href="/dashboard" isSelected />
+ <SideNavItem label="Projects" href="/projects" />
+ </SideNavSection>
+ </SideNav>,
+ );
+ const css = getForcedColorsRules();
+ // `--color-neutral` is a background: forced colors flatten it to Canvas
+ // and the selected row loses every trace of being selected. Highlight /
+ // HighlightText is the platform convention that survives.
+ expect(css).toContain('background-color: highlight;');
+ expect(css).toContain('color: highlighttext;');
+ // The hover fill has to hold the Highlight too, or hovering the current
+ // page repaints it with the ordinary hover overlay and erases the state.
+ // Nesting it inside the hover media query is what wins that fight: the
+ // rule compiles to a triple-class selector, which outranks `item`'s
+ // single-class hover overlay no matter the source order.
+ expect(css).toMatch(
+ /@media \(hover: hover\)[\s\S]*?forced-colors: active[\s\S]*?:hover[\s\S]*?background-color: highlight/,
+ );
+ });
+
+ it('does not opt nav rows out of UA colour remapping', () => {
+ render(
+ <SideNav>
+ <SideNavSection title="Main">
+ <SideNavItem label="Dashboard" href="/dashboard" isSelected />
+ </SideNavSection>
+ </SideNav>,
+ );
+ // A nav row is not a native form control — it resets `appearance` and
+ // paints its own background, so the system keywords land without
+ // `forced-color-adjust: none`. Setting it would inherit into
+ // `endContent`, keeping a Badge's authored fill instead of remapping it.
+ const row = screen.getByRole('link', {name: 'Dashboard'});
+ expect(getComputedStyle(row).forcedColorAdjust).not.toBe('none');
+ });
+});
+
+// =============================================================================
+// Footer icon row — one size for the whole row
+// =============================================================================
+
+describe('SideNav footer icon row sizing', () => {
+ /**
+ * The class(es) a `size="sm"` Button carries that a `size="md"` one does
+ * not — i.e. whatever StyleX compiled the sm height into. Comparing class
+ * sets keeps the assertion off the generated hashes.
+ */
+ function sizeOnlyClasses(size: 'sm' | 'lg'): string[] {
+ const {unmount} = render(
+ <>
+ <Button
+ label="sized reference"
+ size={size}
+ isIconOnly
+ icon={<span />}
+ data-testid="sized-ref"
+ />
+ <Button
+ label="md reference"
+ size="md"
+ isIconOnly
+ icon={<span />}
+ data-testid="md-ref"
+ />
+ </>,
+ );
+ const sized = new Set(screen.getByTestId('sized-ref').classList);
+ const md = new Set(screen.getByTestId('md-ref').classList);
+ const only = [...sized].filter(c => !md.has(c));
+ unmount();
+ // Guard against a vacuous pass: if the two sizes compiled to the same
+ // classes there is nothing to assert and every check would trivially hold.
+ expect(only.length).toBeGreaterThan(0);
+ return only;
+ }
+
+ it('renders the built-in collapse button at the row size, not the Button default', () => {
+ const smClasses = sizeOnlyClasses('sm');
+ render(
+ <SideNav collapsible>
+ <SideNavSection title="Main">
+ <SideNavItem label="Dashboard" href="/dashboard" />
+ </SideNavSection>
+ </SideNav>,
+ );
+ const collapseButton = screen.getByRole('button', {
+ name: /collapse sidebar/i,
+ });
+ for (const className of smClasses) {
+ expect(collapseButton).toHaveClass(className);
+ }
+ });
+
+ it('cascades the same size to footerIcons the consumer did not size', () => {
+ const smClasses = sizeOnlyClasses('sm');
+ render(
+ <SideNav
+ collapsible
+ footerIcons={
+ <Button label="Help" isIconOnly icon={<span />} data-testid="help" />
+ }>
+ <SideNavSection title="Main">
+ <SideNavItem label="Dashboard" href="/dashboard" />
+ </SideNavSection>
+ </SideNav>,
+ );
+ const help = screen.getByTestId('help');
+ for (const className of smClasses) {
+ expect(help).toHaveClass(className);
+ }
+ });
+
+ it('lets an explicit size on a footer icon win over the cascade', () => {
+ const lgClasses = sizeOnlyClasses('lg');
+ render(
+ <SideNav
+ collapsible
+ footerIcons={
+ <Button
+ label="Help"
+ size="lg"
+ isIconOnly
+ icon={<span />}
+ data-testid="help"
+ />
+ }>
+ <SideNavSection title="Main">
+ <SideNavItem label="Dashboard" href="/dashboard" />
+ </SideNavSection>
+ </SideNav>,
+ );
+ const help = screen.getByTestId('help');
+ for (const className of lgClasses) {
+ expect(help).toHaveClass(className);
+ }
+ });
+
+ it('honours an explicit size on SideNavCollapseButton outside the nav', () => {
+ const lgClasses = sizeOnlyClasses('lg');
+ render(
+ <SideNavCollapseContext
+ value={{isCollapsed: false, toggle: () => {}, isCollapsible: true}}>
+ <SideNavCollapseButton size="lg" data-testid="collapse" />
+ </SideNavCollapseContext>,
+ );
+ const collapse = screen.getByTestId('collapse');
+ for (const className of lgClasses) {
+ expect(collapse).toHaveClass(className);
+ }
+ });
+
+ it('centres the chevron instead of seating it on a text baseline', () => {
+ renderExpanded(<SideNavCollapseButton data-testid="collapse" />);
+ // Icon renders its own `astryx-icon` span around the svg; the RTL-mirror
+ // wrapper this component adds is that span's parent.
+ const iconSpan = screen
+ .getByTestId('collapse')
+ .querySelector('span.astryx-icon');
+ const mirror = iconSpan?.parentElement;
+ // The RTL-mirror wrapper is a flex item of Button's icon slot, so it
+ // blockifies; as a block it gets a line box and the glyph sits on the
+ // baseline, 2.42px above centre (measured in Chromium). A flex container
+ // has no line box.
+ expect(mirror && getComputedStyle(mirror).display).toBe('flex');
+ });
+});
diff --git a/packages/core/src/SideNav/SideNav.tsx b/packages/core/src/SideNav/SideNav.tsx
index 439d654208..702b428197 100644
--- a/packages/core/src/SideNav/SideNav.tsx
+++ b/packages/core/src/SideNav/SideNav.tsx
@@ -36,6 +36,7 @@ import {mergeProps, mergeRefs} from '../utils';
import {
SideNavCollapseContext,
type SideNavCollapseState,
+ type SideNavCollapsibleConfig,
type SideNavImperativeCollapseHandle,
} from './SideNavCollapseContext';
import {SideNavCollapseButton} from './SideNavCollapseButton';
@@ -45,6 +46,7 @@ import {useResizable} from '../Resizable/useResizable';
import type {ResizableConfig} from '../Resizable/useResizable';
import {ResizeHandle} from '../Resizable/ResizeHandle';
import {themeProps} from '../utils/themeProps';
+import {SizeProvider} from '../SizeContext/SizeContext';
import {useTranslator} from '../i18n';
// =============================================================================
@@ -185,6 +187,13 @@ const styles = stylex.create({
},
});
+/**
+ * Cascaded to the icon rows through `SizeContext` so the built-in collapse
+ * button and the consumer's `footerIcons` come out one height. An explicit
+ * `size` on a child still wins.
+ */
+const FOOTER_ICON_SIZE = 'sm';
+
// =============================================================================
// Types
// =============================================================================
@@ -197,6 +206,9 @@ export interface SideNavProps extends BaseProps<HTMLElement> {
* Imperative collapse handle for SideNavCollapseButton instances rendered
* outside this SideNav. This intentionally stays separate from `ref`, which
* continues to expose the root HTMLElement.
+ *
+ * @deprecated Hand the same controlled `collapsible` config to SideNav and
+ * to the outside button instead.
*/
handleRef?: React.Ref<SideNavImperativeCollapseHandle>;
@@ -270,21 +282,14 @@ export interface SideNavProps extends BaseProps<HTMLElement> {
* - `true` — enables collapse with default toggle button and uncontrolled state
* - Object — enables collapse with advanced configuration:
* - `defaultIsCollapsed` — start collapsed (uncontrolled)
- * - `isCollapsed` + `onCollapsedChange` — controlled mode
+ * - `isCollapsed` + `onCollapsedChange` — controlled mode. Pass the same
+ * object to a `SideNavCollapseButton` rendered outside this SideNav
* - `hasButton` — render built-in collapse button (default: true)
* - `buttonLabel` — accessibility label for the collapse button
*
* @default false
*/
- collapsible?:
- | boolean
- | {
- defaultIsCollapsed?: boolean;
- isCollapsed?: boolean;
- onCollapsedChange?: (isCollapsed: boolean) => void;
- hasButton?: boolean;
- buttonLabel?: string;
- };
+ collapsible?: boolean | SideNavCollapsibleConfig;
}
// =============================================================================
@@ -375,6 +380,8 @@ export function SideNav({
const toggle = useCallback(() => {
const next = !collapsed;
+ // Deprecated `handleRef` path only: an out-of-tree button reads this
+ // snapshot while rendering, which can happen before SideNav re-renders.
collapseStateRef.current = {
...collapseStateRef.current,
isCollapsed: next,
@@ -429,7 +436,9 @@ export function SideNav({
style,
)}>
{header}
- <div {...stylex.props(styles.topbarIcons)}>{footerIcons}</div>
+ <div {...stylex.props(styles.topbarIcons)}>
+ <SizeProvider value={FOOTER_ICON_SIZE}>{footerIcons}</SizeProvider>
+ </div>
</div>
);
}
@@ -441,7 +450,13 @@ export function SideNav({
if (renderMode === 'drawer') {
return (
- <MobileNav header={header} data-testid={testId}>
+ <MobileNav
+ header={header}
+ data-testid={testId}
+ xstyle={xstyle}
+ className={className}
+ style={style}
+ {...props}>
{topContent}
{children}
{hasDrawerFooter && (
@@ -449,7 +464,9 @@ export function SideNav({
{footer}
{footerIcons && (
<div {...stylex.props(styles.drawerFooterIcons)}>
- {footerIcons}
+ <SizeProvider value={FOOTER_ICON_SIZE}>
+ {footerIcons}
+ </SizeProvider>
</div>
)}
</div>
@@ -472,7 +489,9 @@ export function SideNav({
{footer}
{footerIcons && (
<div {...stylex.props(styles.drawerFooterIcons)}>
- {footerIcons}
+ <SizeProvider value={FOOTER_ICON_SIZE}>
+ {footerIcons}
+ </SizeProvider>
</div>
)}
</div>
@@ -544,8 +563,10 @@ export function SideNav({
styles.footerRow,
collapsed && styles.footerRowCollapsed,
)}>
- {showCollapseButton && <SideNavCollapseButton />}
- {footerIcons}
+ <SizeProvider value={FOOTER_ICON_SIZE}>
+ {showCollapseButton && <SideNavCollapseButton />}
+ {footerIcons}
+ </SizeProvider>
</div>
</div>
)}
diff --git a/packages/core/src/SideNav/SideNavCollapseButton.doc.mjs b/packages/core/src/SideNav/SideNavCollapseButton.doc.mjs
index 742425280d..1fca97e6dd 100644
--- a/packages/core/src/SideNav/SideNavCollapseButton.doc.mjs
+++ b/packages/core/src/SideNav/SideNavCollapseButton.doc.mjs
@@ -7,18 +7,28 @@ export const docs = {
subComponentOf: 'SideNav',
displayName: 'Side Nav Collapse Button',
isHiddenFromOverview: true,
- description: 'Toggle button for sidenav collapse. Place inside SideNav (reads context automatically) or outside (pass handleRef). Renders as an icon-only ghost button by default.',
+ description: 'Toggle button for sidenav collapse. Place inside SideNav (reads context automatically) or outside it (hand the same controlled collapsible config to both). Renders as an icon-only ghost button by default.',
props: [
+ {
+ name: 'collapsible',
+ type: '{isCollapsed: boolean, onCollapsedChange: (isCollapsed: boolean) => void}',
+ description: 'The same controlled collapsible config passed to SideNav. Only needed when the button is rendered outside the sidenav, where collapse context cannot reach it.',
+ },
{
name: 'handleRef',
type: 'RefObject<SideNavImperativeCollapseHandle | null>',
- description: 'Imperative collapse handle from SideNav. Only needed when the button is rendered outside the sidenav.',
+ description: 'Deprecated. Imperative collapse handle from SideNav; pass collapsible instead.',
},
{
name: 'label',
type: 'string',
description: 'Custom button label. When provided, renders as a text button with chevron. When omitted, renders icon-only.',
},
+ {
+ name: 'size',
+ type: "'sm' | 'md' | 'lg'",
+ description: "Button size. Defaults to the size its container cascades — 'sm' inside a SideNav footer — and to 'md' with no container. Set it when the button sits outside a sized container and has to match its neighbours.",
+ },
{
name: 'children',
type: 'ReactNode',
@@ -31,18 +41,28 @@ export const docsZh = {
name: 'SideNavCollapseButton',
isHiddenFromOverview: true,
displayName: 'Side Nav Collapse Button',
- description: '侧边栏折叠切换按钮。放置在 SideNav 内部(自动读取上下文)或外部(传入 handleRef)。默认渲染为仅图标的 ghost 按钮。',
+ description: '侧边栏折叠切换按钮。放置在 SideNav 内部(自动读取上下文)或外部(向两者传入同一个受控 collapsible 配置)。默认渲染为仅图标的 ghost 按钮。',
props: [
+ {
+ name: 'collapsible',
+ type: '{isCollapsed: boolean, onCollapsedChange: (isCollapsed: boolean) => void}',
+ description: '与 SideNav 相同的受控 collapsible 配置。仅在按钮渲染在侧边栏外部、无法读取折叠上下文时需要。',
+ },
{
name: 'handleRef',
type: 'RefObject<SideNavImperativeCollapseHandle | null>',
- description: '来自 SideNav 的命令式折叠句柄。仅在按钮渲染在侧边栏外部时需要。',
+ description: '已废弃。来自 SideNav 的命令式折叠句柄;请改用 collapsible。',
},
{
name: 'label',
type: 'string',
description: '自定义按钮标签。提供时渲染为带箭头的文本按钮。省略时渲染为仅图标按钮。',
},
+ {
+ name: 'size',
+ type: "'sm' | 'md' | 'lg'",
+ description: "按钮尺寸。默认使用容器级联的尺寸(SideNav 页脚内为 'sm'),无容器时为 'md'。当按钮位于已设定尺寸的容器之外且需要与相邻元素保持一致时显式设置。",
+ },
{
name: 'children',
type: 'ReactNode',
@@ -55,10 +75,12 @@ export const docsDense = {
name: 'SideNavCollapseButton',
isHiddenFromOverview: true,
displayName: 'Side Nav Collapse Button',
- description: 'Toggle button for sidenav collapse. Place inside SideNav (reads context) or outside (pass handleRef). Icon-only ghost button by default.',
+ description: 'Toggle button for sidenav collapse. Place inside SideNav (reads context) or outside (pass the same controlled collapsible config both get). Icon-only ghost button by default.',
propDescriptions: {
- handleRef: 'Imperative collapse handle from SideNav. Only needed when button rendered outside sidenav.',
+ collapsible: 'Controlled collapsible config, same object SideNav gets. Only needed when button rendered outside sidenav.',
+ handleRef: 'Deprecated — pass collapsible instead.',
label: 'Custom label. Text button w/ chevron when provided, icon-only when omitted.',
+ size: "Button size. Inherits from the container ('sm' in a SideNav footer), else 'md'.",
children: 'Custom content. Overrides default chevron icon + label.',
},
};
diff --git a/packages/core/src/SideNav/SideNavCollapseButton.tsx b/packages/core/src/SideNav/SideNavCollapseButton.tsx
index af7d41abdd..01612794a7 100644
--- a/packages/core/src/SideNav/SideNavCollapseButton.tsx
+++ b/packages/core/src/SideNav/SideNavCollapseButton.tsx
@@ -9,7 +9,7 @@
* @position Composable toggle button for sidenav collapse
*
* Place inside SideNav (reads context automatically) or outside
- * (pass handleRef to connect). Customizable via label/children.
+ * (pass the same controlled `collapsible` config both get).
*
* SYNC: When modified, update:
* - /packages/core/src/SideNav/SideNav.doc.mjs
@@ -17,7 +17,7 @@
* - /packages/cli/assets/templates/blocks/components/SideNav/ (showcase blocks)
*/
-import React, {type ReactNode} from 'react';
+import React, {useCallback, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {durationVars, easeVars} from '../theme/tokens.stylex';
import {Icon} from '../Icon';
@@ -27,21 +27,34 @@ import {composeEventHandlers, rtlStyles} from '../utils';
import {
useSideNavCollapse,
type SideNavCollapseState,
+ type SideNavControlledCollapsible,
type SideNavImperativeCollapseHandle,
} from './SideNavCollapseContext';
import {useAppShellMobile} from '../AppShell/AppShellMobileContext';
import {useTranslator} from '../i18n';
+import type {ElementSize} from '../SizeContext/SizeContext';
// =============================================================================
// Styles
// =============================================================================
const styles = stylex.create({
+ // A flex container, so the glyph is a flex item. Left to blockify as a flex
+ // item of Button's icon slot, this span gets a line box and seats the
+ // chevron on its text baseline — 2.42px above the button's centre.
+ chevronMirror: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
chevron: {
display: 'inline-flex',
alignItems: 'center',
transitionProperty: 'transform',
- transitionDuration: durationVars['--duration-fast'],
+ transitionDuration: {
+ default: durationVars['--duration-fast'],
+ '@media (prefers-reduced-motion: reduce)': '0s',
+ },
transitionTimingFunction: easeVars['--ease-standard'],
},
chevronCollapsed: {
@@ -56,8 +69,16 @@ const styles = stylex.create({
export interface SideNavCollapseButtonProps extends BaseProps<HTMLButtonElement> {
ref?: React.Ref<HTMLButtonElement>;
/**
- * Imperative handle from SideNav. Only needed when the button is rendered
- * outside the sidenav, where collapse context is unavailable.
+ * The same controlled `collapsible` config given to SideNav
+ * (`{isCollapsed, onCollapsedChange}`). Needed only when the button is
+ * rendered outside the sidenav, where collapse context cannot reach it.
+ */
+ collapsible?: SideNavControlledCollapsible;
+
+ /**
+ * Imperative handle from SideNav.
+ *
+ * @deprecated Pass `collapsible` instead.
*/
handleRef?: React.RefObject<SideNavImperativeCollapseHandle | null>;
@@ -67,6 +88,13 @@ export interface SideNavCollapseButtonProps extends BaseProps<HTMLButtonElement>
*/
label?: string;
+ /**
+ * Button size. Defaults to the size its container cascades — `sm` in a
+ * SideNav footer — or `md` outside one. Set it for placements with no row
+ * to inherit from, e.g. a button placed in a `TopNav`.
+ */
+ size?: ElementSize;
+
/**
* Custom button content. Overrides the default chevron icon and label.
*/
@@ -82,7 +110,8 @@ export interface SideNavCollapseButtonProps extends BaseProps<HTMLButtonElement>
*
* Place anywhere inside SideNav (header, topContent, footer, footerIcons)
* and it reads collapse state from context automatically. For placement
- * outside the sidenav (e.g. in TopNav or content area), pass handleRef.
+ * outside the sidenav (e.g. in TopNav or content area), hold the state and
+ * hand the same `collapsible` config to both.
*
* @example
* ```
@@ -93,22 +122,27 @@ export interface SideNavCollapseButtonProps extends BaseProps<HTMLButtonElement>
*
* @example
* ```
- * const ref = useRef(null);
- * <TopNav endContent={<SideNavCollapseButton handleRef={ref} />} />
- * <SideNav handleRef={ref} collapsible>...</SideNav>
+ * const [isCollapsed, setIsCollapsed] = useState(false);
+ * const collapsible = {isCollapsed, onCollapsedChange: setIsCollapsed};
+ * <TopNav endContent={<SideNavCollapseButton collapsible={collapsible} />} />
+ * <SideNav collapsible={{...collapsible, hasButton: false}}>...</SideNav>
* ```
*/
export function SideNavCollapseButton({
ref,
+ collapsible,
handleRef,
label,
+ size,
children,
onClick: onClickProp,
...props
}: SideNavCollapseButtonProps) {
const t = useTranslator();
- const {isCollapsed, toggle, isCollapsible} =
- useSideNavCollapseState(handleRef);
+ const {isCollapsed, toggle, isCollapsible} = useSideNavCollapseState(
+ collapsible,
+ handleRef,
+ );
const {isMobile} = useAppShellMobile();
// Hide when not collapsible, or when in mobile mode (sidenav is in
@@ -127,6 +161,7 @@ export function SideNavCollapseButton({
: t('@astryx.sideNavCollapseButton.collapseSidebar'))
}
variant="ghost"
+ size={size}
{...props}
onClick={composeEventHandlers(onClickProp, toggle)}
icon={
@@ -135,7 +170,7 @@ export function SideNavCollapseButton({
// into) the state rotation: both are `transform`, so on a single
// element one would overwrite the other and the chevron would stop
// mirroring under RTL. See utils/rtlStyles.ts.
- <span {...stylex.props(rtlStyles.mirror)}>
+ <span {...stylex.props(styles.chevronMirror, rtlStyles.mirror)}>
{/* `sm` (1rem) matches what this glyph already renders at: Button's
icon slot pins its wrapper to 16px, and the registry SVG is
1em, so the chevron is 16px today. */}
@@ -156,11 +191,30 @@ export function SideNavCollapseButton({
SideNavCollapseButton.displayName = 'SideNavCollapseButton';
function useSideNavCollapseState(
+ collapsible: SideNavControlledCollapsible | undefined,
handleRef:
React.RefObject<SideNavImperativeCollapseHandle | null> | undefined,
): SideNavCollapseState {
const contextCollapseState = useSideNavCollapse();
+ const {isCollapsed, onCollapsedChange} = collapsible ?? {};
+ const toggleCollapsible = useCallback(
+ () => onCollapsedChange?.(!isCollapsed),
+ [isCollapsed, onCollapsedChange],
+ );
+
+ const toggleHandle = useCallback(() => {
+ handleRef?.current?.getCollapseState()?.toggle();
+ }, [handleRef]);
+
+ if (collapsible != null) {
+ return {
+ isCollapsed: isCollapsed ?? false,
+ toggle: toggleCollapsible,
+ isCollapsible: true,
+ };
+ }
+
if (handleRef == null) {
return contextCollapseState;
}
@@ -169,9 +223,7 @@ function useSideNavCollapseState(
return {
isCollapsed: externalCollapseState?.isCollapsed ?? false,
- toggle: () => {
- handleRef.current?.getCollapseState()?.toggle();
- },
+ toggle: toggleHandle,
isCollapsible: externalCollapseState?.isCollapsible ?? true,
};
}
diff --git a/packages/core/src/SideNav/SideNavCollapseContext.ts b/packages/core/src/SideNav/SideNavCollapseContext.ts
index b634aec1fd..e223ec8f4f 100644
--- a/packages/core/src/SideNav/SideNavCollapseContext.ts
+++ b/packages/core/src/SideNav/SideNavCollapseContext.ts
@@ -10,8 +10,8 @@
*
* Provides collapse state to SideNavCollapseButton and other
* sidenav children. Set by SideNav when isCollapsible is true.
- * Also provides a small imperative handle for ref-based collapse buttons
- * rendered outside the SideNav tree.
+ * A button rendered outside the SideNav tree is out of context's reach and
+ * takes the controlled `collapsible` config as a prop instead.
*/
import {createContext, use} from 'react';
@@ -25,18 +25,38 @@ export interface SideNavCollapseState {
isCollapsible: boolean;
}
+/** Object form of SideNav's `collapsible` prop. */
+export interface SideNavCollapsibleConfig {
+ defaultIsCollapsed?: boolean;
+ isCollapsed?: boolean;
+ onCollapsedChange?: (isCollapsed: boolean) => void;
+ hasButton?: boolean;
+ buttonLabel?: string;
+}
+
+/**
+ * The controlled form: the consumer holds the state, so it can be handed to
+ * both SideNav and a SideNavCollapseButton rendered outside it.
+ */
+export interface SideNavControlledCollapsible extends SideNavCollapsibleConfig {
+ isCollapsed: boolean;
+ onCollapsedChange: (isCollapsed: boolean) => void;
+}
+/**
+ * @deprecated Pass the same controlled `collapsible` config to SideNav and to
+ * the out-of-tree SideNavCollapseButton instead. The state then reaches the
+ * button through props rather than through a ref.
+ */
export interface SideNavImperativeCollapseHandle {
getCollapseState: () => SideNavCollapseState | null;
}
-export const SideNavCollapseContext = createContext<SideNavCollapseState>(
- {
- isCollapsed: false,
- toggle: () => {},
- isCollapsible: false,
- },
-);
+export const SideNavCollapseContext = createContext<SideNavCollapseState>({
+ isCollapsed: false,
+ toggle: () => {},
+ isCollapsible: false,
+});
SideNavCollapseContext.displayName = 'SideNavCollapseContext';
/**
diff --git a/packages/core/src/SideNav/SideNavHeading.tsx b/packages/core/src/SideNav/SideNavHeading.tsx
index 2735890b61..71c0415fc2 100644
--- a/packages/core/src/SideNav/SideNavHeading.tsx
+++ b/packages/core/src/SideNav/SideNavHeading.tsx
@@ -36,6 +36,7 @@ import {Link} from '../Link';
import {Icon} from '../Icon';
import {Tooltip} from '../Tooltip';
import {navItemStyles} from '../NavItem/navItemStyles.stylex';
+import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {useSideNavCollapse} from './SideNavCollapseContext';
import {useLinkComponent} from '../Link/useLinkComponent';
import type {LinkComponentType} from '../Link/types';
@@ -415,7 +416,11 @@ export function SideNavHeading({
data-testid={testId}
{...mergeProps(
themeProps('side-nav-heading'),
- stylex.props(navItemStyles.item, styles.rootCollapsed, xstyle),
+ focusOutlineProps.focusVisible(
+ navItemStyles.item,
+ styles.rootCollapsed,
+ xstyle,
+ ),
className,
style,
)}>
@@ -434,7 +439,7 @@ export function SideNavHeading({
{...triggerProps}
{...mergeProps(
themeProps('side-nav-heading'),
- stylex.props(
+ focusOutlineProps.focusVisible(
navItemStyles.item,
styles.rootCollapsed,
styles.menuTrigger,
@@ -452,7 +457,7 @@ export function SideNavHeading({
{...contentProps}>
<button
type="button"
- {...stylex.props(styles.popoverHeading)}
+ {...focusOutlineProps.focusVisible(styles.popoverHeading)}
onClick={triggerProps.onClick}>
{icon && <span {...stylex.props(styles.icon)}>{icon}</span>}
<span {...stylex.props(styles.textContainer)}>
@@ -549,7 +554,10 @@ export function SideNavHeading({
{hasAnyHref && headingHref && menu ? (
<LinkComponent
href={headingHref}
- {...stylex.props(styles.heading, styles.headingLink)}>
+ {...focusOutlineProps.focusVisible(
+ styles.heading,
+ styles.headingLink,
+ )}>
{heading}
</LinkComponent>
) : (
@@ -586,7 +594,7 @@ export function SideNavHeading({
const popoverHeadingContent = (
<button
type="button"
- {...stylex.props(styles.popoverHeading)}
+ {...focusOutlineProps.focusVisible(styles.popoverHeading)}
onClick={triggerProps.onClick}>
{icon && <span {...stylex.props(styles.icon)}>{icon}</span>}
{renderTextContent(
@@ -609,7 +617,11 @@ export function SideNavHeading({
data-testid={testId}
{...mergeProps(
themeProps('side-nav-heading'),
- stylex.props(styles.root, styles.menuTrigger, xstyle),
+ focusOutlineProps.focusVisible(
+ styles.root,
+ styles.menuTrigger,
+ xstyle,
+ ),
className,
style,
)}
@@ -646,7 +658,10 @@ export function SideNavHeading({
triggerProps.onClick();
}}
{...popover.triggerProps}
- {...stylex.props(styles.chevron, styles.interactive)}>
+ {...focusOutlineProps.focusVisible(
+ styles.chevron,
+ styles.interactive,
+ )}>
<Icon
icon="chevronDown"
size="sm"
@@ -701,7 +716,7 @@ export function SideNavHeading({
<LinkComponent
href={headingHref}
aria-label={heading}
- {...stylex.props(styles.icon)}>
+ {...focusOutlineProps.focusVisible(styles.icon)}>
{icon}
</LinkComponent>
) : (
@@ -717,7 +732,10 @@ export function SideNavHeading({
triggerProps.onClick();
}}
{...popover.triggerProps}
- {...stylex.props(styles.chevron, styles.interactive)}>
+ {...focusOutlineProps.focusVisible(
+ styles.chevron,
+ styles.interactive,
+ )}>
<Icon
icon="chevronDown"
size="sm"
@@ -770,7 +788,7 @@ export function SideNavHeading({
<LinkComponent
href={headingHref}
aria-label={heading}
- {...stylex.props(styles.icon)}>
+ {...focusOutlineProps.focusVisible(styles.icon)}>
{icon}
</LinkComponent>
) : (
diff --git a/packages/core/src/SideNav/SideNavItem.doc.mjs b/packages/core/src/SideNav/SideNavItem.doc.mjs
index 3b09b0e7af..c3759e39f4 100644
--- a/packages/core/src/SideNav/SideNavItem.doc.mjs
+++ b/packages/core/src/SideNav/SideNavItem.doc.mjs
@@ -91,6 +91,12 @@ export const docs = {
description: 'Enables collapse behavior for items with children. Pass true for uncontrolled (starts expanded), or an object for controlled mode.',
default: 'false',
},
+ {
+ name: 'size',
+ type: "'sm' | 'md' | 'lg'",
+ description: 'Size variant for the nav item row.',
+ default: "'md'",
+ },
],
};
@@ -159,6 +165,12 @@ export const docsZh = {
description: '启用带子项的折叠行为。传 true 为非受控模式(默认展开),或传对象用于受控模式。',
default: 'false',
},
+ {
+ name: 'size',
+ type: "'sm' | 'md' | 'lg'",
+ description: '导航项的尺寸变体。',
+ default: "'md'",
+ },
],
};
@@ -179,5 +191,6 @@ export const docsDense = {
endContent: 'Right-side content such as badges or counts.',
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 41ccdb57b5..dc516ef7bd 100644
--- a/packages/core/src/SideNav/SideNavItem.tsx
+++ b/packages/core/src/SideNav/SideNavItem.tsx
@@ -4,12 +4,17 @@
/**
* @file SideNavItem.tsx
- * @input Uses React, ReactNode, StyleX, Icon, IconType
+ * @input Uses React, ReactNode, StyleX, Icon, IconType, useMenuHover
* @output Exports SideNavItem component and SideNavItemProps
* @position Core implementation; used inside SideNav children
*
* Navigation item with icon, selected state, and nesting.
*
+ * Collapsed items with children open their submenu flyout through
+ * `useMenuHover`, the shared hover-intent hook (same one `SideNavHeading` and
+ * `TopNavMenu` use). Hover is a progressive enhancement over the popover's
+ * click behavior and is inert on coarse pointers.
+ *
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/SideNav/SideNav.doc.mjs
* - /packages/core/src/SideNav/SideNav.test.tsx
@@ -35,17 +40,18 @@ import {
typeScaleVars,
durationVars,
easeVars,
- borderVars,
radiusVars,
} from '../theme/tokens.stylex';
import {Icon, renderIconSlot, type IconType} from '../Icon';
import {useLinkComponent} from '../Link/useLinkComponent';
import type {LinkComponentType} from '../Link/types';
import {usePopover} from '../Popover/usePopover';
+import {useMenuHover} from '../hooks/useMenuHover';
import {mergeProps, mergeRefs} from '../utils';
import type {BaseProps} from '../BaseProps';
import {Tooltip} from '../Tooltip';
import {navItemStyles, type NavItemSize} from '../NavItem/navItemStyles.stylex';
+import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {
useSideNavCollapse,
SideNavCollapseContext,
@@ -91,7 +97,10 @@ const styles = stylex.create({
display: 'grid',
gridTemplateRows: '1fr',
transitionProperty: 'grid-template-rows',
- transitionDuration: durationVars['--duration-medium'],
+ transitionDuration: {
+ default: durationVars['--duration-medium'],
+ '@media (prefers-reduced-motion: reduce)': '0s',
+ },
transitionTimingFunction: easeVars['--ease-standard'],
},
childrenCollapsed: {
@@ -114,7 +123,10 @@ const styles = stylex.create({
// target, not the glyph size, so keep the glyph on the inherited size.
fontSize: 'inherit',
transitionProperty: 'transform',
- transitionDuration: durationVars['--duration-fast'],
+ transitionDuration: {
+ default: durationVars['--duration-fast'],
+ '@media (prefers-reduced-motion: reduce)': '0s',
+ },
transitionTimingFunction: easeVars['--ease-standard'],
flexShrink: 0,
},
@@ -146,10 +158,14 @@ const styles = stylex.create({
},
// Primary action element inside the split-action row (link or button).
// Flex:1 so it fills remaining space, giving a wide click target.
+ // `alignSelf: stretch` makes it fill the row's height too — without it the
+ // element collapses to its line box (20px), under the 24px WCAG 2.5.8
+ // target-size floor even though the row it sits in is 32px tall.
// Resets both link and button appearance so it blends into the row.
splitAction: {
display: 'flex',
alignItems: 'center',
+ alignSelf: 'stretch',
gap: spacingVars['--spacing-2'],
flex: 1,
minWidth: 0,
@@ -167,16 +183,23 @@ const styles = stylex.create({
textAlign: 'start',
cursor: 'pointer',
},
- // Popover surface for collapsed items with children
+ // No border and no background: `usePopover` paints the panel this renders
+ // into. Drawing a second surface here put square corners inside its rounded
+ // ones. The radius matches so a theme retargeting `--radius-container`
+ // keeps the two in step.
popoverSurface: {
- borderWidth: borderVars['--border-width'],
- borderStyle: 'solid',
- borderColor: colorVars['--color-border'],
+ borderRadius: radiusVars['--radius-container'],
paddingBlock: spacingVars['--spacing-1'],
paddingInline: spacingVars['--spacing-1'],
- marginInlineStart: spacingVars['--spacing-1'],
minWidth: 180,
},
+ // The gap from the rail belongs on the positioned layer, where
+ // `DropdownMenu` keeps it. On the content div it insets the content instead,
+ // leaving the panel flush against the rail.
+ popoverGap: {
+ marginInlineStart: spacingVars['--spacing-1'],
+ marginInlineEnd: spacingVars['--spacing-1'],
+ },
popoverHeader: {
paddingInline: spacingVars['--spacing-2'],
paddingBlock: spacingVars['--spacing-1'],
@@ -361,6 +384,7 @@ export function SideNavItem({
'data-testid': testId,
ref,
xstyle,
+ ...rest
}: SideNavItemProps) {
const t = useTranslator();
const {isCollapsed} = useSideNavCollapse();
@@ -376,7 +400,7 @@ export function SideNavItem({
hasLightDismiss: true,
hasAutoFocus: true,
hasCloseButton: false,
- dialogLabel: `${label} submenu`,
+ dialogLabel: t('@astryx.sideNavItem.submenuLabel', {label}),
});
// Collapse state for items with children
@@ -434,42 +458,17 @@ export function SideNavItem({
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);
-
- const clearPopoverTimeouts = useCallback(() => {
- if (showTimeoutRef.current) {
- clearTimeout(showTimeoutRef.current);
- showTimeoutRef.current = null;
- }
- if (hideTimeoutRef.current) {
- clearTimeout(hideTimeoutRef.current);
- hideTimeoutRef.current = null;
- }
- }, []);
-
- const schedulePopoverShow = useCallback(() => {
- clearPopoverTimeouts();
- showTimeoutRef.current = setTimeout(() => {
- popover.show({skipAutoFocus: true});
- }, 150);
- }, [clearPopoverTimeouts, popover]);
-
- const schedulePopoverHide = useCallback(() => {
- clearPopoverTimeouts();
- hideTimeoutRef.current = setTimeout(() => {
- popover.hide();
- }, 200);
- }, [clearPopoverTimeouts, popover]);
-
- const handlePopoverMouseEnter = useCallback(() => {
- schedulePopoverShow();
- }, [schedulePopoverShow]);
-
- const handlePopoverMouseLeave = useCallback(() => {
- schedulePopoverHide();
- }, [schedulePopoverHide]);
+ // Pointer half only. The hook's `onKeyDown`/`menuRef` drive a `useListFocus`
+ // over `[role="menuitem"]`, and this flyout is a focus-trapped dialog of
+ // links — wiring them would swallow arrow keys rather than navigate with
+ // them. Keyboard stays with `usePopover`'s trap, as in DropdownMenuSubMenu.
+ const {triggerProps: hoverTriggerProps, contentProps: hoverContentProps} =
+ useMenuHover({
+ show: popover.show,
+ hide: popover.hide,
+ isOpen: popover.isOpen,
+ isEnabled: isCollapsed && hasChildren,
+ });
// In collapsed mode: hide items without icons
if (isCollapsed && !icon) {
@@ -484,16 +483,21 @@ export function SideNavItem({
displayIcon &&
renderIconSlot(displayIcon, {
size: 'sm',
- color: isSelected ? 'primary' : isDisabled ? 'disabled' : 'secondary',
+ // `inherit` so a selected row's icon follows the row to HighlightText
+ // under forced colors. Identical to `primary` otherwise: both token
+ // families are emitted from one expression.
+ color: isSelected ? 'inherit' : isDisabled ? 'disabled' : 'secondary',
});
- // Shared collapsed item styles — used by trigger, link, and button
+ // Shared collapsed item styles — used by trigger, link, and button.
+ // All three render a focusable element, so each draws the shared ring.
const collapsedItemStyles = mergeProps(
themeProps('side-nav-item', {
size,
selected: isSelected ? 'selected' : null,
+ disabled: isDisabled ? 'disabled' : null,
}),
- stylex.props(
+ focusOutlineProps.focusVisible(
navItemStyles.item,
navItemStyles[size],
styles.itemCollapsed,
@@ -511,9 +515,8 @@ export function SideNavItem({
<button
ref={mergeRefs(ref, popover.triggerRef)}
type="button"
- onClick={popover.toggle}
- onMouseEnter={handlePopoverMouseEnter}
- onMouseLeave={handlePopoverMouseLeave}
+ {...rest}
+ {...hoverTriggerProps}
aria-label={label}
data-testid={testId}
{...popover.triggerProps}
@@ -523,15 +526,15 @@ export function SideNavItem({
{popover.render(
<div
{...stylex.props(styles.popoverSurface)}
- onMouseEnter={handlePopoverMouseEnter}
- onMouseLeave={handlePopoverMouseLeave}
+ onMouseEnter={hoverContentProps.onMouseEnter}
+ onMouseLeave={hoverContentProps.onMouseLeave}
onClick={() => popover.hide()}>
<div {...stylex.props(styles.popoverHeader)}>{label}</div>
<SideNavCollapseContext value={EXPANDED_COLLAPSE_STATE}>
{children}
</SideNavCollapseContext>
</div>,
- {placement: 'end', alignment: 'start'},
+ {placement: 'end', alignment: 'start', xstyle: styles.popoverGap},
)}
</div>
);
@@ -552,6 +555,7 @@ export function SideNavItem({
as={as}
isDisabled={isDisabled}
onClick={handleClick}
+ {...rest}
{...collapsedAriaProps}
{...collapsedItemStyles}>
{collapsedIcon}
@@ -571,7 +575,8 @@ export function SideNavItem({
{displayIcon &&
renderIconSlot(displayIcon, {
size: 'sm',
- color: isSelected ? 'primary' : isDisabled ? 'disabled' : 'secondary',
+ // `inherit` — see the collapsed path above.
+ color: isSelected ? 'inherit' : isDisabled ? 'disabled' : 'secondary',
})}
{!isCollapsed && <span {...stylex.props(styles.label)}>{label}</span>}
{!isCollapsed && endContent && (
@@ -591,45 +596,47 @@ export function SideNavItem({
</>
);
- const navItemStyleProps = mergeProps(
- themeProps('side-nav-item', {
- size,
- selected: isSelected ? 'selected' : null,
- }),
- stylex.props(
- navItemStyles.item,
- navItemStyles[size],
- isSelected && navItemStyles.selected,
- isDisabled && navItemStyles.disabled,
- ),
- );
-
- // ── 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.
+ const itemThemeProps = themeProps('side-nav-item', {
+ size,
+ selected: isSelected ? 'selected' : null,
+ disabled: isDisabled ? 'disabled' : null,
+ });
- // ── 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>).
+ const itemStyleArgs = [
+ navItemStyles.item,
+ navItemStyles[size],
+ isSelected && navItemStyles.selected,
+ 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.
+ const rowProps = mergeProps(itemThemeProps, stylex.props(...itemStyleArgs));
+ const focusableRowProps = mergeProps(
+ itemThemeProps,
+ focusOutlineProps.focusVisible(...itemStyleArgs),
+ );
+ // 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) {
itemElement = (
- <div data-testid={testId} {...navItemStyleProps}>
+ <div data-testid={testId} {...rowProps}>
<NavItemElement
ref={ref}
href={href}
as={as}
isDisabled={isDisabled}
onClick={handleClick}
+ {...rest}
aria-current={isSelected ? ('page' as const) : undefined}
- {...stylex.props(styles.splitAction)}>
+ {...focusOutlineProps.focusVisible(styles.splitAction)}>
{itemContent}
</NavItemElement>
<button
@@ -642,7 +649,7 @@ export function SideNavItem({
}
aria-expanded={!isItemCollapsed}
aria-controls={`${id}-children`}
- {...stylex.props(styles.expandToggle)}>
+ {...focusOutlineProps.focusVisible(styles.expandToggle)}>
<Icon
icon="chevronDown"
size="lg"
@@ -671,8 +678,9 @@ export function SideNavItem({
as={as}
isDisabled={isDisabled}
onClick={handleClick}
+ {...rest}
{...ariaProps}
- {...navItemStyleProps}>
+ {...focusableRowProps}>
{itemContent}
</NavItemElement>
);
diff --git a/packages/core/src/SideNav/SideNavSection.tsx b/packages/core/src/SideNav/SideNavSection.tsx
index dbc9170c3c..24fc330e3e 100644
--- a/packages/core/src/SideNav/SideNavSection.tsx
+++ b/packages/core/src/SideNav/SideNavSection.tsx
@@ -29,6 +29,7 @@ import {
import {mergeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {useSideNavCollapse} from './SideNavCollapseContext';
+import {VisuallyHidden} from '../VisuallyHidden';
import {themeProps} from '../utils/themeProps';
// =============================================================================
// Styles
@@ -167,20 +168,6 @@ export function SideNavSection({
const shouldHideHeader = isHeaderHidden || isCollapsed;
- const visuallyHiddenStyle: React.CSSProperties = shouldHideHeader
- ? {
- position: 'absolute',
- width: 1,
- height: 1,
- padding: 0,
- margin: -1,
- overflow: 'hidden',
- clip: 'rect(0, 0, 0, 0)',
- whiteSpace: 'nowrap',
- borderWidth: 0,
- }
- : {};
-
return (
<div
ref={ref}
@@ -194,12 +181,11 @@ export function SideNavSection({
role="group"
aria-labelledby={titleId}
data-testid={testId}>
- <div
- {...mergeProps(stylex.props(styles.header), {
- style: shouldHideHeader ? visuallyHiddenStyle : undefined,
- })}>
- {headerContent}
- </div>
+ {shouldHideHeader ? (
+ <VisuallyHidden as="div">{headerContent}</VisuallyHidden>
+ ) : (
+ <div {...stylex.props(styles.header)}>{headerContent}</div>
+ )}
<div {...stylex.props(styles.items)}>{children}</div>
</div>
);
diff --git a/packages/core/src/SideNav/index.ts b/packages/core/src/SideNav/index.ts
index a5e6f5f357..ab0f736c7a 100644
--- a/packages/core/src/SideNav/index.ts
+++ b/packages/core/src/SideNav/index.ts
@@ -29,6 +29,8 @@ export type {SideNavCollapseButtonProps} from './SideNavCollapseButton';
export {useSideNavCollapse} from './SideNavCollapseContext';
export type {
SideNavCollapseState,
+ SideNavCollapsibleConfig,
+ SideNavControlledCollapsible,
SideNavImperativeCollapseHandle,
} from './SideNavCollapseContext';
diff --git a/packages/core/src/TopNav/TopNavMegaMenu.test.tsx b/packages/core/src/TopNav/TopNavMegaMenu.test.tsx
index 7939e999c3..09500f4e58 100644
--- a/packages/core/src/TopNav/TopNavMegaMenu.test.tsx
+++ b/packages/core/src/TopNav/TopNavMegaMenu.test.tsx
@@ -9,6 +9,8 @@
* SYNC: When TopNavMegaMenu changes, update tests to match new behavior
*/
+import * as stylex from '@stylexjs/stylex';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {describe, it, expect, vi, beforeAll, afterAll, afterEach} from 'vitest';
import {render, screen, act, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -817,3 +819,44 @@ describe('TopNavMegaMenuItem', () => {
expect(screen.getByRole('link', {name: /Analytics/})).toBeInTheDocument();
});
});
+
+// =============================================================================
+// The shared focus ring (#4654) — see the note in SideNav.test.tsx: jsdom will
+// not derive `:focus-visible` here, so what is pinned is that the focusable
+// element composes the shared utility's classes rather than falling back to
+// the browser's own outline.
+// =============================================================================
+
+const sharedFocusRingClasses = stylex
+ .props(focusOutlineStyles.focusVisible)
+ .className!.split(' ');
+
+function expectSharedFocusRing(el: Element) {
+ const classes = el.className.split(' ');
+ for (const c of sharedFocusRingClasses) {
+ expect(classes).toContain(c);
+ }
+}
+
+describe('TopNavMegaMenu — drawer focus ring', () => {
+ it('draws the shared ring on the drawer section header', () => {
+ render(
+ <TopNavRenderContext value="drawer">
+ <TopNavMegaMenu
+ label="Products"
+ items={<TopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />
+ </TopNavRenderContext>,
+ );
+ expectSharedFocusRing(screen.getByRole('button', {name: 'Products'}));
+ });
+
+ it('draws the shared ring on a drawer item', () => {
+ render(
+ <TopNavRenderContext value="drawer">
+ <TopNavMegaMenuItem title="Analytics" href="/analytics" />
+ </TopNavRenderContext>,
+ );
+ expectSharedFocusRing(screen.getByRole('link', {name: /Analytics/}));
+ });
+});
diff --git a/packages/core/src/TopNav/TopNavMegaMenu.tsx b/packages/core/src/TopNav/TopNavMegaMenu.tsx
index f202e705fa..5df2688b94 100644
--- a/packages/core/src/TopNav/TopNavMegaMenu.tsx
+++ b/packages/core/src/TopNav/TopNavMegaMenu.tsx
@@ -602,7 +602,10 @@ function DrawerMegaMenu({
aria-controls={`${menuId}-items`}
{...mergeProps(
themeProps('top-nav-mega-menu', {mode: 'drawer'}),
- stylex.props(navItemStyles.item, styles.drawerHeader),
+ focusOutlineProps.focusVisible(
+ navItemStyles.item,
+ styles.drawerHeader,
+ ),
)}>
{label}
<Icon
diff --git a/packages/core/src/TopNav/TopNavMegaMenuItem.tsx b/packages/core/src/TopNav/TopNavMegaMenuItem.tsx
index 7be934dac7..d12dac6fcf 100644
--- a/packages/core/src/TopNav/TopNavMegaMenuItem.tsx
+++ b/packages/core/src/TopNav/TopNavMegaMenuItem.tsx
@@ -215,7 +215,7 @@ export function TopNavMegaMenuItem({
{...elementProps}
{...mergeProps(
themeProps('top-nav-mega-menu-item', {mode: 'drawer'}),
- stylex.props(navItemStyles.item, styles.drawerItem),
+ focusOutlineProps.focusVisible(navItemStyles.item, styles.drawerItem),
)}>
{icon && <div {...stylex.props(styles.drawerItemIcon)}>{icon}</div>}
<div {...stylex.props(styles.drawerItemContent)}>
diff --git a/packages/core/src/TopNav/TopNavMenu.test.tsx b/packages/core/src/TopNav/TopNavMenu.test.tsx
index 895e15c7f5..4c1f541a0c 100644
--- a/packages/core/src/TopNav/TopNavMenu.test.tsx
+++ b/packages/core/src/TopNav/TopNavMenu.test.tsx
@@ -12,6 +12,9 @@
import {describe, it, expect, vi} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import * as stylex from '@stylexjs/stylex';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {TopNavRenderContext} from './TopNavRenderContext';
import {TopNavMenu} from './TopNavMenu';
const mockItems = [
@@ -171,3 +174,41 @@ describe('keyboard navigation (APG menu pattern)', () => {
expect(trigger).toHaveAttribute('aria-expanded', 'false');
});
});
+
+// =============================================================================
+// The shared focus ring (#4654) — see the note in SideNav.test.tsx: jsdom will
+// not derive `:focus-visible` here, so what is pinned is that the focusable
+// element composes the shared utility's classes rather than falling back to
+// the browser's own outline.
+// =============================================================================
+
+const sharedFocusRingClasses = stylex
+ .props(focusOutlineStyles.focusVisible)
+ .className!.split(' ');
+
+function expectSharedFocusRing(el: Element) {
+ const classes = el.className.split(' ');
+ for (const c of sharedFocusRingClasses) {
+ expect(classes).toContain(c);
+ }
+}
+
+describe('TopNavMenu — drawer focus ring', () => {
+ it('draws the shared ring on the drawer section header', () => {
+ render(
+ <TopNavRenderContext value="drawer">
+ <TopNavMenu label="Products" items={mockItems} />
+ </TopNavRenderContext>,
+ );
+ expectSharedFocusRing(screen.getByRole('button', {name: /Products/}));
+ });
+
+ it('draws the shared ring on a drawer item', () => {
+ render(
+ <TopNavRenderContext value="drawer">
+ <TopNavMenu label="Products" items={mockItems} />
+ </TopNavRenderContext>,
+ );
+ expectSharedFocusRing(screen.getByRole('link', {name: /Analytics/}));
+ });
+});
diff --git a/packages/core/src/TopNav/TopNavMenu.tsx b/packages/core/src/TopNav/TopNavMenu.tsx
index 3aeef4ae4a..064901c501 100644
--- a/packages/core/src/TopNav/TopNavMenu.tsx
+++ b/packages/core/src/TopNav/TopNavMenu.tsx
@@ -432,7 +432,10 @@ export function TopNavMenu({
onClick={() => setDrawerExpanded(v => !v)}
aria-expanded={drawerExpanded}
aria-controls={`${menuId}-items`}
- {...stylex.props(navItemStyles.item, drawerStyles.header)}>
+ {...focusOutlineProps.focusVisible(
+ navItemStyles.item,
+ drawerStyles.header,
+ )}>
{label}
<Icon
icon="chevronDown"
@@ -459,7 +462,10 @@ export function TopNavMenu({
item.onClick?.();
closeMobileNav();
}}
- {...stylex.props(navItemStyles.item, drawerStyles.item)}>
+ {...focusOutlineProps.focusVisible(
+ navItemStyles.item,
+ drawerStyles.item,
+ )}>
{item.icon && (
<span {...stylex.props(drawerStyles.itemIcon)}>
{item.icon}