An open source design system that's fully customizable and agent ready
TypeScript
fix(SideNavItem): the collapsed rail tooltip describes the item's control, not its row (#7502)
Ernest12e7190f6d44
diff --git a/.changeset/side-nav-initial-collapsed-tooltip.md b/.changeset/side-nav-initial-collapsed-tooltip.mdnew file mode 100644index 0000000000..30f1648807--- /dev/null+++ b/.changeset/side-nav-initial-collapsed-tooltip.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] SideNav: a collapsed rail item's tooltip now binds to the link or button itself rather than the row around it, so the focusable control is the WAI-ARIA tooltip pattern's trigger and is described by the tooltip (`aria-describedby`) from its first render. Keyboard focus on it now shows the label. As with other link and button tooltips, a touch tap activates the control without opening the tooltip. A disabled item still shows its label on hover.++@ernestt @thewebartisan7diff --git a/packages/core/src/SideNav/SideNav.test.tsx b/packages/core/src/SideNav/SideNav.test.tsxindex 163999bdbb..0ba8d3c258 100644--- a/packages/core/src/SideNav/SideNav.test.tsx+++ b/packages/core/src/SideNav/SideNav.test.tsx@@ -3759,33 +3759,235 @@ describe('SideNav collapse conflict warning', () => {// SideNavItem — collapsed-from-mount rail tooltip// =============================================================================+// Two interchangeable link components: switching between them remounts the+// rendered link element.+function RailLinkA({ref, ...props}: React.ComponentPropsWithRef<'a'>) {+ return <a ref={ref} {...props} />;+}++function RailLinkB({ref, ...props}: React.ComponentPropsWithRef<'a'>) {+ return <a ref={ref} {...props} />;+}+describe('SideNavItem collapsed-from-mount rail tooltip', () => {- // #7692: a childless item that mounts inside an already-collapsed SideNav- // renders its Tooltip inside the very element anchorRef points at. React- // attaches that ref only after the tooltip's layout effect has run, so the- // tooltip never attached and a persisted collapsed rail lost all tooltips- // on page load.- it('anchors the rail tooltip when the nav is collapsed at mount', async () => {- render(+ // #7435 / #7692: a childless item that mounts inside an already-collapsed+ // SideNav (the persisted-collapse case) must attach its tooltip on the first+ // render, and the tooltip must describe the control that takes focus — the+ // link or button — not the row around it.+ function railTooltipFor(trigger: HTMLElement) {+ const id = trigger.getAttribute('aria-describedby');+ return id == null ? null : document.getElementById(id);+ }++ function renderRail(item: ReactNode) {+ return render(<SideNavaria-label="Main"collapsible={{isCollapsed: true, hasButton: false}}>- <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ {item}</SideNav>,);- const link = screen.getByRole('link', {name: 'Dashboard'});- const anchor = link.parentElement as HTMLElement;+ }- // The tooltip attaches despite mounting inside its own anchor: the item- // row is described by the tooltip layer.- await waitFor(() => {- expect(anchor.getAttribute('aria-describedby')).not.toBe('');- });- const layer = document.getElementById(- anchor.getAttribute('aria-describedby') as string,+ let showPopover: ReturnType<typeof vi.spyOn> | undefined;++ afterEach(() => {+ showPopover?.mockRestore();+ showPopover = undefined;+ vi.useRealTimers();+ });++ it('describes the rail link by its tooltip when the nav is collapsed at mount', () => {+ renderRail(+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />,);+ const link = screen.getByRole('link', {name: 'Dashboard'});++ const layer = railTooltipFor(link);expect(layer).not.toBeNull();expect(layer).toHaveAttribute('role', 'tooltip');expect(layer).toHaveTextContent('Dashboard');});++ it('shows a disabled item its label when the pointer rests on its row', async () => {+ // The disabled control is `pointer-events: none`, so in a browser the+ // pointer lands on the row; the tooltip has to listen there.+ vi.useFakeTimers();+ const spy = vi.spyOn(HTMLElement.prototype, 'showPopover');+ showPopover = spy;+ renderRail(+ <SideNavItem+ label="Analytics (Coming Soon)"+ icon={StubIcon}+ href="/analytics"+ isDisabled+ />,+ );+ // Let the row's tooltip attach after the commit.+ await act(async () => {});+ const button = screen.getByRole('button', {+ name: 'Analytics (Coming Soon)',+ });+ const row = button.parentElement as HTMLElement;+ const layer = screen.getByRole('tooltip', {hidden: true});+ expect(layer).toHaveTextContent('Analytics (Coming Soon)');++ fireEvent.mouseEnter(row);+ act(() => {+ vi.advanceTimersByTime(200);+ });+ expect(spy.mock.contexts).toContain(layer);+ });++ it('describes the link once a disabled item is enabled in the rail', () => {+ const item = (isDisabled: boolean) => (+ <SideNavItem+ label="Dashboard"+ icon={StubIcon}+ href="/dashboard"+ isDisabled={isDisabled}+ />+ );+ const {rerender} = renderRail(item(true));+ rerender(+ <SideNav+ aria-label="Main"+ collapsible={{isCollapsed: true, hasButton: false}}>+ {item(false)}+ </SideNav>,+ );++ const link = screen.getByRole('link', {name: 'Dashboard'});+ expect(railTooltipFor(link)).toHaveTextContent('Dashboard');+ });++ it('describes the new control when a rail item gains an href', () => {+ const item = (href?: string) => (+ <SideNavItem+ label="Dashboard"+ icon={StubIcon}+ href={href}+ onClick={() => {}}+ />+ );+ const {rerender} = renderRail(item());+ const button = screen.getByRole('button', {name: 'Dashboard'});+ expect(railTooltipFor(button)).toHaveTextContent('Dashboard');++ rerender(+ <SideNav+ aria-label="Main"+ collapsible={{isCollapsed: true, hasButton: false}}>+ {item('/dashboard')}+ </SideNav>,+ );+ const link = screen.getByRole('link', {name: 'Dashboard'});+ expect(railTooltipFor(link)).toHaveTextContent('Dashboard');+ });++ it('binds the replacement when a rail link element is replaced', () => {+ // Switching the link component remounts the element; the tooltip must+ // follow the new element.+ vi.useFakeTimers();+ const spy = vi.spyOn(HTMLElement.prototype, 'showPopover');+ showPopover = spy;+ const item = (as: typeof RailLinkA) => (+ <SideNavItem+ label="Dashboard"+ icon={StubIcon}+ href="/dashboard"+ as={as}+ />+ );+ const {rerender} = renderRail(item(RailLinkA));+ const first = screen.getByRole('link', {name: 'Dashboard'});+ rerender(+ <SideNav+ aria-label="Main"+ collapsible={{isCollapsed: true, hasButton: false}}>+ {item(RailLinkB)}+ </SideNav>,+ );++ const link = screen.getByRole('link', {name: 'Dashboard'});+ expect(link).not.toBe(first);+ const layer = railTooltipFor(link);+ expect(layer).toHaveTextContent('Dashboard');+ fireEvent.mouseEnter(link);+ act(() => {+ vi.advanceTimersByTime(200);+ });+ expect(spy.mock.contexts).toContain(layer);+ });++ it("keeps the tooltip beside a caller's changing aria-describedby", () => {+ const item = (hint: string) => (+ <SideNavItem+ label="Dashboard"+ icon={StubIcon}+ href="/dashboard"+ aria-describedby={hint}+ />+ );+ const {rerender} = renderRail(item('hint-a'));+ rerender(+ <SideNav+ aria-label="Main"+ collapsible={{isCollapsed: true, hasButton: false}}>+ {item('hint-b')}+ </SideNav>,+ );++ const link = screen.getByRole('link', {name: 'Dashboard'});+ const tooltip = screen.getByRole('tooltip', {hidden: true});+ const ids = (link.getAttribute('aria-describedby') ?? '').split(' ');+ expect(ids).toContain('hint-b');+ expect(ids).toContain(tooltip.id);+ expect(ids).not.toContain('hint-a');+ });++ it('shows the label when keyboard focus reaches a rail link', () => {+ const spy = vi.spyOn(HTMLElement.prototype, 'showPopover');+ showPopover = spy;+ renderRail(+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />,+ );+ const link = screen.getByRole('link', {name: 'Dashboard'});+ const layer = railTooltipFor(link);+ // jsdom does not model `:focus-visible`; stand in for a keyboard focus.+ const realMatches = link.matches.bind(link);+ vi.spyOn(link, 'matches').mockImplementation((selector: string) =>+ selector === ':focus-visible' ? true : realMatches(selector),+ );++ fireEvent.focusIn(link);+ expect(spy.mock.contexts).toContain(layer);+ });++ it('keeps a tooltip that was open when the rail expanded shut on the next collapse', () => {+ vi.useFakeTimers();+ const spy = vi.spyOn(HTMLElement.prototype, 'showPopover');+ showPopover = spy;+ const rail = (isCollapsed: boolean) => (+ <SideNav aria-label="Main" collapsible={{isCollapsed, hasButton: false}}>+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ </SideNav>+ );+ const {rerender} = render(rail(true));+ const link = screen.getByRole('link', {name: 'Dashboard'});+ fireEvent.mouseEnter(link);+ act(() => {+ vi.advanceTimersByTime(200);+ });+ expect(spy.mock.contexts).toContain(railTooltipFor(link));++ // Expanding (from a shortcut, say) removes the trigger without a leave.+ rerender(rail(false));+ spy.mockClear();+ rerender(rail(true));+ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(spy).not.toHaveBeenCalled();+ });});diff --git a/packages/core/src/SideNav/SideNavItem.tsx b/packages/core/src/SideNav/SideNavItem.tsxindex 0beb29afd2..02ee513331 100644--- a/packages/core/src/SideNav/SideNavItem.tsx+++ b/packages/core/src/SideNav/SideNavItem.tsx@@ -10,7 +10,11 @@** Navigation item with icon, selected state, row-level actions, and nesting.* Collapsed icon-only controls use a meaningful consumer `aria-label` when- * provided and fall back to `label` when it is missing or blank.+ * provided and fall back to `label` when it is missing or blank. Their label+ * tooltip binds to the interactive control through a callback ref, so hover,+ * keyboard focus, and `aria-describedby` follow the control from the first+ * collapsed render. A disabled control takes neither pointer nor focus, so its+ * row is the tooltip's trigger instead.** Collapsed items with children open their submenu flyout through* `useMenuHover`, the shared hover-intent hook (same one `SideNavHeading` and@@ -36,7 +40,6 @@ import {useCallback,useId,useMemo,- useRef,useState,type ReactNode,} from 'react';@@ -58,7 +61,7 @@ import {usePopover} from '../Popover/usePopover';import {useMenuHover} from '../hooks/useMenuHover';import {mergeProps} from '../utils';import type {BaseProps} from '../BaseProps';-import {Tooltip} from '../Tooltip';+import {useTooltip} from '../Tooltip';import {navItemStyles, type NavItemSize} from '../NavItem/navItemStyles.stylex';import {SizeProvider} from '../SizeContext/SizeContext';import {focusOutlineProps} from '../utils/focusOutline.stylex';@@ -355,6 +358,12 @@ function NavItemElement({);}+/** Joins the non-empty ids into one `aria-describedby` value. */+function joinIds(...ids: (string | null | undefined)[]): string | undefined {+ const joined = ids.filter(Boolean).join(' ');+ return joined === '' ? undefined : joined;+}+// =============================================================================// Types// =============================================================================@@ -511,7 +520,6 @@ export function SideNavItem({const isInDrawer = renderMode === 'drawer' || renderMode === 'drawer-content';const id = useId();const hasChildren = !!children;- const itemRef = useRef<HTMLDivElement>(null);const depth = use(SideNavItemDepthContext);// Popover for collapsed items with children@@ -523,6 +531,19 @@ export function SideNavItem({});const mergedTriggerRef = useMergedRefs(ref, popover.triggerRef);+ // Label tooltip for a collapsed leaf. It binds through a callback ref and+ // its id renders as an `aria-describedby` prop, so both follow the element+ // they describe across re-renders. The hook outlives the collapsed branch,+ // so it is held shut whenever the item is not a collapsed leaf: a tooltip+ // open when the rail expands must not come back on the next collapse.+ const isRailLeaf = isCollapsed && !hasChildren;+ const railTooltip = useTooltip({+ placement: 'end',+ isEnabled: isRailLeaf,+ isOpen: isRailLeaf ? undefined : false,+ });+ const railLeafRef = useMergedRefs(ref, railTooltip.ref);+// Collapse state for items with childrenconst itemCollapsibleConfig = useMemo(() => (typeof itemCollapsible === 'object' ? itemCollapsible : {}),@@ -679,9 +700,16 @@ export function SideNavItem({);}- // Items without children: icon-only link/button with tooltip+ // Items without children: icon-only link or button, its label in a+ // tooltip. The control is the trigger, so the element that takes focus is+ // the one described. A disabled control takes neither pointer+ // (`navItemStyles.disabled`) nor focus, so its row is the trigger instead.+ const isRowTrigger = isDisabled;const collapsedAriaProps = {'aria-current': isSelected ? ('page' as const) : undefined,+ 'aria-describedby': isRowTrigger+ ? rest['aria-describedby']+ : joinIds(rest['aria-describedby'], railTooltip.describedBy),'aria-disabled': isDisabled || undefined,'aria-label': collapsedAccessibleLabel,'data-testid': testId,@@ -689,7 +717,7 @@ export function SideNavItem({const collapsedElement = (<NavItemElement- ref={ref}+ ref={isRowTrigger ? ref : railLeafRef}href={href}as={as}isDisabled={isDisabled}@@ -702,9 +730,12 @@ export function SideNavItem({);return (- <div ref={itemRef} {...stylex.props(styles.root, xstyle)}>+ <div+ ref={isRowTrigger ? railTooltip.ref : undefined}+ aria-describedby={isRowTrigger ? railTooltip.describedBy : undefined}+ {...stylex.props(styles.root, xstyle)}>{collapsedElement}- <Tooltip content={label} placement="end" anchorRef={itemRef} />+ {railTooltip.renderTooltip(label)}</div>);}@@ -894,7 +925,7 @@ export function SideNavItem({}const item = (- <div ref={itemRef} {...stylex.props(styles.root, xstyle)}>+ <div {...stylex.props(styles.root, xstyle)}>{itemElement}{hasChildren && !isCollapsed && (<div