An open source design system that's fully customizable and agent ready
TypeScript
feat(SideNav): heading truncation tooltip + headerEndContent (#1095)
Cindy Zhang14bbfc2d260d
diff --git a/apps/storybook/stories/SideNav.stories.tsx b/apps/storybook/stories/SideNav.stories.tsxindex 76a939c31b..48346d160f 100644--- a/apps/storybook/stories/SideNav.stories.tsx+++ b/apps/storybook/stories/SideNav.stories.tsx@@ -394,3 +394,102 @@ export const HiddenSectionHeader: Story = {</XDSSideNav>),};++// =============================================================================+// Long Heading with Tooltip+// =============================================================================++export const LongHeadingText: Story = {+ name: 'Long Heading with Tooltip',+ render: () => (+ <XDSSideNav+ header={+ <XDSSideNavHeading+ icon={+ <XDSNavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />+ }+ heading="Enterprise Resource Planning Dashboard"+ superheading="Acme Corporation International"+ subheading="[email protected]"+ headingHref="/"+ />+ }>+ <XDSSideNavSection title="Main">+ <XDSSideNavItem+ label="Dashboard"+ icon={HomeIcon}+ selectedIcon={HomeIconSolid}+ isSelected+ />+ <XDSSideNavItem label="Projects" icon={FolderIcon} />+ </XDSSideNavSection>+ </XDSSideNav>+ ),+};++// =============================================================================+// Header End Content+// =============================================================================++export const HeaderEndContent: Story = {+ name: 'Header End Content',+ render: () => (+ <XDSSideNav+ header={+ <XDSSideNavHeading+ icon={+ <XDSNavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />+ }+ heading="My App"+ headingHref="/"+ headerEndContent={<XDSBadge label="3" variant="error" />}+ />+ }>+ <XDSSideNavSection title="Main">+ <XDSSideNavItem+ label="Dashboard"+ icon={HomeIcon}+ selectedIcon={HomeIconSolid}+ isSelected+ />+ <XDSSideNavItem label="Projects" icon={FolderIcon} />+ </XDSSideNavSection>+ </XDSSideNav>+ ),+};++// =============================================================================+// Header End Content + Menu+// =============================================================================++export const HeaderEndContentWithMenu: Story = {+ name: 'Header End Content + Menu',+ render: () => (+ <XDSSideNav+ header={+ <XDSSideNavHeading+ icon={+ <XDSNavIcon icon={<CubeIcon style={{width: 16, height: 16}} />} />+ }+ heading="Product Name"+ subheading="Business Account"+ headerEndContent={<XDSBadge label="New" variant="info" />}+ menu={+ <XDSList density="compact">+ <XDSListItem label="Switch Account" href="#" />+ <XDSListItem label="Sign Out" href="#" />+ </XDSList>+ }+ />+ }>+ <XDSSideNavSection title="Main">+ <XDSSideNavItem+ label="Dashboard"+ icon={HomeIcon}+ selectedIcon={HomeIconSolid}+ isSelected+ />+ </XDSSideNavSection>+ </XDSSideNav>+ ),+};diff --git a/packages/core/src/SideNav/SideNav.doc.mjs b/packages/core/src/SideNav/SideNav.doc.mjsindex 64d6117b01..46b043b6e0 100644--- a/packages/core/src/SideNav/SideNav.doc.mjs+++ b/packages/core/src/SideNav/SideNav.doc.mjs@@ -15,6 +15,8 @@ export const docs = {'Accessible — nav landmark, aria-current="page", role="group" with aria-labelledby on sections','Keyboard navigable — Tab through items, Enter/Space to activate','Resizable sidebar via resizable prop — drag handle at inline-end edge, pointer-based resize with min/max constraints',+ 'Heading text overflow detection with tooltip — shows full text on hover when heading, superheading, or subheading is truncated by ellipsis',+ 'Header end content slot — headerEndContent prop on XDSSideNavHeading for badges, status indicators, or action buttons at the trailing edge of the heading row',],accessibility: ['<nav aria-label="Side navigation"> wraps the entire component',@@ -220,6 +222,11 @@ export const docs = {type: 'ReactNode',description: 'Menu content rendered inside a popover.',},+ {+ name: 'headerEndContent',+ type: 'ReactNode',+ description: 'Content rendered at the trailing edge of the heading row, between text and chevron. Useful for badges, status indicators, or compact action buttons. Hidden when collapsed.',+ },],examples: [{@@ -244,6 +251,15 @@ export const docs = {heading="My App"headingHref="/"menu={<WorkspaceSwitcher />}+/>`,+ },+ {+ label: 'With header end content',+ code: `<XDSSideNavHeading+ icon={<AppIcon />}+ heading="My App"+ headingHref="/"+ headerEndContent={<XDSBadge label="3" variant="error" />}/>`,},],@@ -661,6 +677,11 @@ export const docsZh = {type: 'ReactNode',description: '在弹出框内渲染的菜单内容。',},+ {+ name: 'headerEndContent',+ type: 'ReactNode',+ description: '在标题行尾部渲染的内容,位于文本和箭头之间。适用于徽章、状态指示器或紧凑操作按钮。折叠时隐藏。',+ },],examples: [{@@ -932,6 +953,7 @@ export const docsDense = {subheading: 'Text below heading.',subheadingHref: 'Link for subheading.',menu: 'Menu content rendered inside popover.',+ headerEndContent: 'Content at trailing edge of heading row. For badges, status indicators, action buttons. Hidden when collapsed.',},},{diff --git a/packages/core/src/SideNav/XDSSideNav.test.tsx b/packages/core/src/SideNav/XDSSideNav.test.tsxindex ba8503e175..ec7cbe4c65 100644--- a/packages/core/src/SideNav/XDSSideNav.test.tsx+++ b/packages/core/src/SideNav/XDSSideNav.test.tsx@@ -325,6 +325,113 @@ describe('XDSSideNavHeading collapsed', () => {});});+// =============================================================================+// XDSSideNavHeading — headerEndContent+// =============================================================================++describe('XDSSideNavHeading headerEndContent', () => {+ it('renders headerEndContent in the default static path', () => {+ render(+ <XDSSideNavHeading+ heading="My App"+ headerEndContent={<span data-testid="end-badge">3</span>}+ />,+ );+ expect(screen.getByTestId('end-badge')).toBeInTheDocument();+ });++ it('renders headerEndContent outside the link in isWholeHeadingLink path', () => {+ render(+ <XDSSideNavHeading+ heading="My App"+ headingHref="/home"+ headerEndContent={<span data-testid="end-badge">3</span>}+ />,+ );+ const badge = screen.getByTestId('end-badge');+ expect(badge).toBeInTheDocument();+ // Badge should NOT be inside the link+ expect(badge.closest('a')).toBeNull();+ });++ it('renders headerEndContent outside the button trigger in isWholeHeadingTrigger path', () => {+ render(+ <XDSSideNavHeading+ heading="My App"+ menu={<div>Menu</div>}+ headerEndContent={<span data-testid="end-badge">3</span>}+ />,+ );+ const badge = screen.getByTestId('end-badge');+ expect(badge).toBeInTheDocument();+ // Badge should NOT be inside the button+ expect(badge.closest('button')).toBeNull();+ });++ it('renders headerEndContent in mixed mode (menu + href)', () => {+ render(+ <XDSSideNavHeading+ heading="My App"+ headingHref="/home"+ menu={<div>Menu</div>}+ headerEndContent={<span data-testid="end-badge">3</span>}+ />,+ );+ expect(screen.getByTestId('end-badge')).toBeInTheDocument();+ });++ it('renders headerEndContent with independent links (no menu)', () => {+ render(+ <XDSSideNavHeading+ heading="Product"+ headingHref="/product"+ superheading="Suite"+ superheadingHref="/suite"+ headerEndContent={<span data-testid="end-badge">3</span>}+ />,+ );+ expect(screen.getByTestId('end-badge')).toBeInTheDocument();+ });++ it('hides headerEndContent when collapsed', () => {+ render(+ <CollapsedWrapper>+ <XDSSideNavHeading+ heading="My App"+ icon={<span>🏠</span>}+ headerEndContent={<span data-testid="end-badge">3</span>}+ />+ </CollapsedWrapper>,+ );+ expect(screen.queryByTestId('end-badge')).not.toBeInTheDocument();+ });+});++// =============================================================================+// XDSSideNavHeading — truncation tooltips+// =============================================================================++describe('XDSSideNavHeading truncation tooltips', () => {+ it('attaches truncation refs to heading text spans', () => {+ const {container} = render(+ <XDSSideNavHeading+ heading="My App"+ superheading="Acme Corp"+ subheading="[email protected]"+ />,+ );+ // All three text spans should be present+ expect(screen.getByText('My App')).toBeInTheDocument();+ expect(screen.getByText('Acme Corp')).toBeInTheDocument();+ expect(screen.getByText('[email protected]')).toBeInTheDocument();+ });++ it('does not crash with truncation hooks when only heading is provided', () => {+ render(<XDSSideNavHeading heading="My App" />);+ expect(screen.getByText('My App')).toBeInTheDocument();+ });+});+// =============================================================================// XDSSideNavItem// =============================================================================diff --git a/packages/core/src/SideNav/XDSSideNavHeading.tsx b/packages/core/src/SideNav/XDSSideNavHeading.tsxindex 54929bda34..b3b2cb5c68 100644--- a/packages/core/src/SideNav/XDSSideNavHeading.tsx+++ b/packages/core/src/SideNav/XDSSideNavHeading.tsx@@ -2,12 +2,13 @@/*** @file XDSSideNavHeading.tsx- * @input Uses React, useRef, useCallback, ReactNode, StyleX, useXDSPopover+ * @input Uses React, useRef, useCallback, ReactNode, StyleX, useXDSPopover, useTruncation* @output Exports XDSSideNavHeading component and XDSSideNavHeadingProps* @position Core implementation; used inside XDSSideNav header slot** Product/suite/account heading with smart interaction boundary logic.* Composes useXDSPopover internally when menu prop is provided.+ * Detects text truncation and shows tooltip on hover for overflowing text.** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/SideNav/SideNav.doc.mjs@@ -16,7 +17,7 @@* - /apps/storybook/stories/SideNav.stories.tsx*/-import {useCallback, useRef, type ReactNode} from 'react';+import {lazy, Suspense, useCallback, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {@@ -33,10 +34,15 @@ import {useXDSPopover} from '../Popover/useXDSPopover';import {XDSLink} from '../Link';import {getIcon} from '../Icon/globalIconRegistry';import {XDSTooltip} from '../Tooltip';+import {useTruncation} from '../Text/useTruncation';import {navItemStyles} from '../NavItem/navItemStyles.stylex';import {useXDSSideNavCollapse} from './XDSSideNavCollapseContext';import {xdsClassName, mergeProps} from '../utils';+const LazyXDSTooltip = lazy(() =>+ import('../Tooltip/XDSTooltip').then(mod => ({default: mod.XDSTooltip})),+);+// =============================================================================// Styles// =============================================================================@@ -129,6 +135,22 @@ const styles = stylex.create({minHeight: spacingVars['--spacing-7'],color: colorVars['--color-icon-secondary'],},+ headerEndContent: {+ flexShrink: 0,+ display: 'flex',+ alignItems: 'center',+ },+ // Inner interactive element (link/button) when headerEndContent splits+ // the interactive boundary — stretches to fill remaining space so+ // headerEndContent hugs the trailing edge of the nav.+ interactiveInner: {+ display: 'flex',+ alignItems: 'center',+ flex: 1,+ minWidth: 0,+ padding: 0,+ gap: 'inherit',+ },popoverContent: {padding: spacingVars['--spacing-1'],overflow: 'hidden',@@ -182,6 +204,13 @@ export interface XDSSideNavHeadingProps {* - With hrefs → links are independent, chevron/remaining area is the trigger*/menu?: ReactNode;+ /**+ * Content rendered at the trailing edge of the heading row.+ * Useful for badges, status indicators, or compact action buttons.+ * Not part of the popover trigger or heading link — purely decorative/interactive.+ * Hidden when the sidebar is collapsed.+ */+ headerEndContent?: ReactNode;/*** StyleX styles created via `stylex.create()`. Merged with the component's* base styles inside a single `stylex.props()` call for optimal deduplication.@@ -254,6 +283,7 @@ export function XDSSideNavHeading({subheading,subheadingHref,menu,+ headerEndContent,xstyle,className,style,@@ -265,6 +295,45 @@ export function XDSSideNavHeading({const rootRef = useRef<HTMLDivElement>(null);const collapsedItemRef = useRef<HTMLElement>(null);+ // Truncation detection for heading text elements+ const headingTruncation = useTruncation({maxLines: 1});+ const superheadingTruncation = useTruncation({maxLines: 1});+ const subheadingTruncation = useTruncation({maxLines: 1});++ // Refs for tooltip anchors+ const headingSpanRef = useRef<HTMLSpanElement>(null);+ const superheadingSpanRef = useRef<HTMLSpanElement>(null);+ const subheadingSpanRef = useRef<HTMLSpanElement>(null);++ // Merged ref callbacks for truncation + tooltip anchor+ const mergedHeadingRef = useCallback(+ (el: HTMLSpanElement | null) => {+ headingTruncation.ref(el);+ (+ headingSpanRef as React.MutableRefObject<HTMLSpanElement | null>+ ).current = el;+ },+ [headingTruncation.ref],+ );+ const mergedSuperheadingRef = useCallback(+ (el: HTMLSpanElement | null) => {+ superheadingTruncation.ref(el);+ (+ superheadingSpanRef as React.MutableRefObject<HTMLSpanElement | null>+ ).current = el;+ },+ [superheadingTruncation.ref],+ );+ const mergedSubheadingRef = useCallback(+ (el: HTMLSpanElement | null) => {+ subheadingTruncation.ref(el);+ (+ subheadingSpanRef as React.MutableRefObject<HTMLSpanElement | null>+ ).current = el;+ },+ [subheadingTruncation.ref],+ );+const popover = useXDSPopover({dialogLabel: 'Navigation menu',});@@ -362,6 +431,30 @@ export function XDSSideNavHeading({const isWholeHeadingLink =!!headingHref && !menu && !superheadingHref && !subheadingHref;+ // Render truncation tooltips for text spans (only in expanded mode)+ const renderTruncationTooltips = () => (+ <>+ {superheadingTruncation.isTruncated && (+ <Suspense fallback={null}>+ <LazyXDSTooltip+ content={superheading!}+ anchorRef={superheadingSpanRef}+ />+ </Suspense>+ )}+ {headingTruncation.isTruncated && (+ <Suspense fallback={null}>+ <LazyXDSTooltip content={heading} anchorRef={headingSpanRef} />+ </Suspense>+ )}+ {subheadingTruncation.isTruncated && (+ <Suspense fallback={null}>+ <LazyXDSTooltip content={subheading!} anchorRef={subheadingSpanRef} />+ </Suspense>+ )}+ </>+ );+// Render text contentconst renderTextContent = () => (<span {...stylex.props(styles.textContainer)}>@@ -375,7 +468,11 @@ export function XDSSideNavHeading({{superheading}</XDSLink>) : (- <span {...stylex.props(styles.superheading)}>{superheading}</span>+ <span+ ref={mergedSuperheadingRef}+ {...stylex.props(styles.superheading)}>+ {superheading}+ </span>))}{hasAnyHref && headingHref && menu ? (<XDSLink@@ -387,6 +484,7 @@ export function XDSSideNavHeading({</XDSLink>) : (<span+ ref={mergedHeadingRef}{...stylex.props(styles.heading,hasCompactHeading && styles.headingCompact,@@ -404,7 +502,9 @@ export function XDSSideNavHeading({{subheading}</XDSLink>) : (- <span {...stylex.props(styles.subheading)}>{subheading}</span>+ <span ref={mergedSubheadingRef} {...stylex.props(styles.subheading)}>+ {subheading}+ </span>))}</span>);@@ -413,29 +513,103 @@ export function XDSSideNavHeading({<span {...stylex.props(styles.chevron)}>{getIcon('chevronDown')}</span>);+ const headerEndContentElement = headerEndContent && (+ <span {...stylex.props(styles.headerEndContent)}>{headerEndContent}</span>+ );+// Whole heading is a link (no menu, single headingHref)if (isWholeHeadingLink) {+ // When headerEndContent is provided, render it outside the link+ if (headerEndContent) {+ return (+ <>+ <div+ ref={ref}+ data-testid={testId}+ {...mergeProps(+ xdsClassName('side-nav-heading'),+ stylex.props(styles.root, xstyle),+ className,+ style,+ )}>+ <a+ href={headingHref}+ {...stylex.props(+ styles.root,+ styles.interactive,+ styles.interactiveInner,+ )}+ {...(props as React.AnchorHTMLAttributes<HTMLAnchorElement>)}>+ {icon && <span {...stylex.props(styles.icon)}>{icon}</span>}+ {renderTextContent()}+ </a>+ {headerEndContentElement}+ {chevronElement}+ </div>+ {renderTruncationTooltips()}+ </>+ );+ }return (- <a- ref={ref as React.Ref<HTMLAnchorElement>}- href={headingHref}- data-testid={testId}- {...mergeProps(- xdsClassName('side-nav-heading'),- stylex.props(styles.root, styles.interactive, xstyle),- className,- style,- )}- {...(props as React.AnchorHTMLAttributes<HTMLAnchorElement>)}>- {icon && <span {...stylex.props(styles.icon)}>{icon}</span>}- {renderTextContent()}- {chevronElement}- </a>+ <>+ <a+ ref={ref as React.Ref<HTMLAnchorElement>}+ href={headingHref}+ data-testid={testId}+ {...mergeProps(+ xdsClassName('side-nav-heading'),+ stylex.props(styles.root, styles.interactive, xstyle),+ className,+ style,+ )}+ {...(props as React.AnchorHTMLAttributes<HTMLAnchorElement>)}>+ {icon && <span {...stylex.props(styles.icon)}>{icon}</span>}+ {renderTextContent()}+ {chevronElement}+ </a>+ {renderTruncationTooltips()}+ </>);}// Whole header is the popover trigger (menu, no hrefs)if (isWholeHeadingTrigger) {+ // When headerEndContent is provided, render it outside the button trigger+ if (headerEndContent) {+ return (+ <>+ <div+ data-testid={testId}+ {...mergeProps(+ xdsClassName('side-nav-heading'),+ stylex.props(styles.root, xstyle),+ className,+ style,+ )}>+ <button+ ref={setRef as React.Ref<HTMLButtonElement>}+ type="button"+ onClick={handleToggle}+ {...popover.triggerProps}+ {...stylex.props(+ styles.root,+ styles.interactive,+ styles.interactiveInner,+ )}>+ {icon && <span {...stylex.props(styles.icon)}>{icon}</span>}+ {renderTextContent()}+ {chevronElement}+ </button>+ {headerEndContentElement}+ </div>+ {renderTruncationTooltips()}+ {popover.render(+ <div {...stylex.props(styles.popoverContent)}>{menu}</div>,+ {placement: 'below', alignment: 'start', xstyle: styles.popover},+ )}+ </>+ );+ }return (<><button@@ -454,6 +628,7 @@ export function XDSSideNavHeading({{renderTextContent()}{chevronElement}</button>+ {renderTruncationTooltips()}{popover.render(<div {...stylex.props(styles.popoverContent)}>{menu}</div>,{placement: 'below', alignment: 'start', xstyle: styles.popover},@@ -486,6 +661,7 @@ export function XDSSideNavHeading({<span {...stylex.props(styles.icon)}>{icon}</span>))}{renderTextContent()}+ {headerEndContentElement}{showChevron && (<buttontype="button"@@ -497,6 +673,7 @@ export function XDSSideNavHeading({</button>)}</div>+ {renderTruncationTooltips()}{popover.render(<div {...stylex.props(styles.popoverContent)}>{menu}</div>,{placement: 'below', alignment: 'start', xstyle: styles.popover},@@ -508,6 +685,88 @@ export function XDSSideNavHeading({// Static heading with independent links (no menu)if (hasAnyHref && !isWholeHeadingLink) {return (+ <>+ <div+ ref={ref}+ data-testid={testId}+ {...mergeProps(+ xdsClassName('side-nav-heading'),+ stylex.props(styles.root, xstyle),+ className,+ style,+ )}+ {...props}>+ {icon &&+ (headingHref ? (+ <a href={headingHref} {...stylex.props(styles.icon)}>+ {icon}+ </a>+ ) : (+ <span {...stylex.props(styles.icon)}>{icon}</span>+ ))}+ <span {...stylex.props(styles.textContainer)}>+ {superheading &&+ (superheadingHref ? (+ <XDSLink+ label={superheading}+ href={superheadingHref}+ color="secondary"+ size="xsm">+ {superheading}+ </XDSLink>+ ) : (+ <span+ ref={mergedSuperheadingRef}+ {...stylex.props(styles.superheading)}>+ {superheading}+ </span>+ ))}+ {headingHref ? (+ <XDSLink+ label={heading}+ href={headingHref}+ color="primary"+ weight="semibold">+ {heading}+ </XDSLink>+ ) : (+ <span+ ref={mergedHeadingRef}+ {...stylex.props(+ styles.heading,+ hasCompactHeading && styles.headingCompact,+ )}>+ {heading}+ </span>+ )}+ {subheading &&+ (subheadingHref ? (+ <XDSLink+ label={subheading}+ href={subheadingHref}+ color="secondary"+ size="xsm">+ {subheading}+ </XDSLink>+ ) : (+ <span+ ref={mergedSubheadingRef}+ {...stylex.props(styles.subheading)}>+ {subheading}+ </span>+ ))}+ </span>+ {headerEndContentElement}+ {chevronElement}+ </div>+ {renderTruncationTooltips()}+ </>+ );+ }++ // Default: static heading, no links, no menu+ return (+ <><divref={ref}data-testid={testId}@@ -518,78 +777,13 @@ export function XDSSideNavHeading({style,)}{...props}>- {icon &&- (headingHref ? (- <a href={headingHref} {...stylex.props(styles.icon)}>- {icon}- </a>- ) : (- <span {...stylex.props(styles.icon)}>{icon}</span>- ))}- <span {...stylex.props(styles.textContainer)}>- {superheading &&- (superheadingHref ? (- <XDSLink- label={superheading}- href={superheadingHref}- color="secondary"- size="xsm">- {superheading}- </XDSLink>- ) : (- <span {...stylex.props(styles.superheading)}>{superheading}</span>- ))}- {headingHref ? (- <XDSLink- label={heading}- href={headingHref}- color="primary"- weight="semibold">- {heading}- </XDSLink>- ) : (- <span- {...stylex.props(- styles.heading,- hasCompactHeading && styles.headingCompact,- )}>- {heading}- </span>- )}- {subheading &&- (subheadingHref ? (- <XDSLink- label={subheading}- href={subheadingHref}- color="secondary"- size="xsm">- {subheading}- </XDSLink>- ) : (- <span {...stylex.props(styles.subheading)}>{subheading}</span>- ))}- </span>+ {icon && <span {...stylex.props(styles.icon)}>{icon}</span>}+ {renderTextContent()}+ {headerEndContentElement}{chevronElement}</div>- );- }-- // Default: static heading, no links, no menu- return (- <div- ref={ref}- data-testid={testId}- {...mergeProps(- xdsClassName('side-nav-heading'),- stylex.props(styles.root, xstyle),- className,- style,- )}- {...props}>- {icon && <span {...stylex.props(styles.icon)}>{icon}</span>}- {renderTextContent()}- {chevronElement}- </div>+ {renderTruncationTooltips()}+ </>);}