Skip to content

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

TypeScript

fix(TopNav): mega menu and menu positioning, keyboard, alignment, and focus trapping (#622)

Cindy Zhangc9f6af5719f7
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx
index 6549d3795f..2489f0c703 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx
@@ -45,6 +45,8 @@ interface ShellConfig {
showFooterIcons: boolean;
showTopContent: boolean;
sideNavHeadingStyle: 'none' | 'simple' | 'link' | 'menu' | 'full';
+ showSuperheading: boolean;
+ showSubheading: boolean;
showNestedItems: boolean;
defaultCollapsed: boolean;
controlledCollapse: boolean;
@@ -68,6 +70,8 @@ const DEFAULT_CONFIG: ShellConfig = {
showFooterIcons: true,
showTopContent: true,
sideNavHeadingStyle: 'link',
+ showSuperheading: false,
+ showSubheading: false,
showNestedItems: true,
defaultCollapsed: false,
controlledCollapse: false,
@@ -172,6 +176,16 @@ function ConfigPanel({
{value: 'full', label: 'Full'},
]}
/>
+ <ToggleRow
+ label="Superheading"
+ value={config.showSuperheading}
+ onChange={v => onChange({showSuperheading: v})}
+ />
+ <ToggleRow
+ label="Subheading"
+ value={config.showSubheading}
+ onChange={v => onChange({showSubheading: v})}
+ />
<ToggleRow
label="Banner"
value={config.showBanner}
@@ -382,15 +396,9 @@ function SampleSideNav({config}: {config: ShellConfig}) {
? '#'
: undefined
}
- superheading={
- config.sideNavHeadingStyle === 'full' ? 'Acme Suite' : undefined
- }
- superheadingHref={
- config.sideNavHeadingStyle === 'full' ? '#' : undefined
- }
- subheading={
- config.sideNavHeadingStyle === 'full' ? 'Business Account' : undefined
- }
+ superheading={config.showSuperheading ? 'Acme Suite' : undefined}
+ superheadingHref={config.showSuperheading ? '#' : undefined}
+ subheading={config.showSubheading ? 'Business Account' : undefined}
menu={
config.sideNavHeadingStyle === 'menu' ||
config.sideNavHeadingStyle === 'full'
diff --git a/apps/sandbox/src/app/(sandbox)/pages/mega-menu/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/mega-menu/page.tsx
index b1003e245d..54c543cad0 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/mega-menu/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/mega-menu/page.tsx
@@ -333,7 +333,6 @@ export default function MegaMenuPage() {
href: '#api',
},
]}
- isSingleColumn
onOpenChange={setMenuOpen3}
/>
<XDSTopNavItem label="Pricing" href="#" />
diff --git a/packages/core/src/HoverCard/useXDSHoverCard.tsx b/packages/core/src/HoverCard/useXDSHoverCard.tsx
index 3e3787cfe6..32f48ed027 100644
--- a/packages/core/src/HoverCard/useXDSHoverCard.tsx
+++ b/packages/core/src/HoverCard/useXDSHoverCard.tsx
@@ -178,6 +178,16 @@ export interface XDSHoverCardReturn {
children: ReactNode,
props?: ContextRenderProps,
) => ReactNode;
+
+ /**
+ * Imperatively show the hover card (bypassing hover delay).
+ */
+ show: () => void;
+
+ /**
+ * Imperatively hide the hover card.
+ */
+ hide: () => void;
}
/**
@@ -471,5 +481,7 @@ export function useXDSHoverCard(
anchorId: layer.anchorId,
describedBy: layer.id,
renderHoverCard,
+ show: layer.show,
+ hide: layer.hide,
};
}
diff --git a/packages/core/src/TopNav/TopNavContext.ts b/packages/core/src/TopNav/TopNavContext.ts
new file mode 100644
index 0000000000..eee5414987
--- /dev/null
+++ b/packages/core/src/TopNav/TopNavContext.ts
@@ -0,0 +1,9 @@
+import {createContext, useContext} from 'react';
+
+export type TopNavSlot = 'start' | 'center' | 'end';
+
+export const TopNavSlotContext = createContext<TopNavSlot>('start');
+
+export function useTopNavSlot(): TopNavSlot {
+ return useContext(TopNavSlotContext);
+}
diff --git a/packages/core/src/TopNav/XDSTopNav.tsx b/packages/core/src/TopNav/XDSTopNav.tsx
index ad05707b06..4880a72b71 100644
--- a/packages/core/src/TopNav/XDSTopNav.tsx
+++ b/packages/core/src/TopNav/XDSTopNav.tsx
@@ -19,6 +19,7 @@ import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
import {edgeSignals} from '../Layout/edgeCompensation.stylex';
import {xdsClassName, mergeProps} from '../utils';
+import {TopNavSlotContext} from './TopNavContext';
/**
* Base TopNav styles
@@ -164,20 +165,24 @@ export function XDSTopNav({
<div {...stylex.props(styles.leftSection, edgeSignals.start)}>
{heading && <div {...stylex.props(styles.heading)}>{heading}</div>}
{startContent && (
- <div {...stylex.props(styles.startContent)}>{startContent}</div>
+ <TopNavSlotContext value="start">
+ <div {...stylex.props(styles.startContent)}>{startContent}</div>
+ </TopNavSlotContext>
)}
</div>
{hasCenterContent && (
- <div {...stylex.props(styles.centerContent)}>{centerContent}</div>
+ <TopNavSlotContext value="center">
+ <div {...stylex.props(styles.centerContent)}>{centerContent}</div>
+ </TopNavSlotContext>
)}
{hasCenterContent ? (
<div {...stylex.props(styles.rightSection, edgeSignals.end)}>
- {endContent}
+ <TopNavSlotContext value="end">{endContent}</TopNavSlotContext>
</div>
) : (
endContent && (
<div {...stylex.props(styles.endContent, edgeSignals.end)}>
- {endContent}
+ <TopNavSlotContext value="end">{endContent}</TopNavSlotContext>
</div>
)
)}
diff --git a/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx b/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
index 681ef1ef4f..b2e5ce3314 100644
--- a/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
+++ b/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
@@ -15,7 +15,7 @@
'use client';
-import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react';
+import {useCallback, useEffect, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -27,17 +27,17 @@ import {
lineHeightVars,
elevationVars,
} from '../theme/tokens.stylex';
-import {useXDSLayer} from '../Layer';
+import {useXDSPopover} from '../Popover/useXDSPopover';
+import {XDSGrid} from '../Grid/XDSGrid';
+import {getIcon} from '../Icon/globalIconRegistry';
import {xdsClassName, mergeProps} from '../utils';
+import {useTopNavSlot} from './TopNavContext';
// =============================================================================
// Styles
// =============================================================================
const styles = stylex.create({
- wrapper: {
- position: 'static',
- },
trigger: {
display: 'inline-flex',
alignItems: 'center',
@@ -86,6 +86,7 @@ const styles = stylex.create({
// Animation styles applied to the layer's popover element.
// Uses :popover-open for enter and @starting-style for initial state.
panelAnimation: {
+ backgroundColor: 'transparent',
opacity: {
default: 0,
':popover-open': 1,
@@ -116,20 +117,17 @@ const styles = stylex.create({
},
panelContent: {
display: 'flex',
+ flexWrap: 'wrap',
gap: spacingVars['--spacing-6'],
paddingBlock: spacingVars['--spacing-6'],
paddingInline: spacingVars['--spacing-6'],
maxWidth: 960,
- marginInline: 'auto',
- },
- menuSection: {
- display: 'grid',
- gridTemplateColumns: '1fr 1fr',
- gap: spacingVars['--spacing-2'],
- flex: 1,
},
- menuSectionSingle: {
- gridTemplateColumns: '1fr',
+ menuWrapper: {
+ flexGrow: 2,
+ flexShrink: 1,
+ flexBasis: 300,
+ minWidth: 0,
},
menuItem: {
display: 'flex',
@@ -189,8 +187,9 @@ const styles = stylex.create({
color: colorVars['--color-text-secondary'],
},
featured: {
- width: 280,
- flexShrink: 0,
+ flexGrow: 1,
+ flexShrink: 1,
+ flexBasis: 200,
borderRadius: radiusVars['--radius-container'],
backgroundColor: colorVars['--color-deemphasized'],
overflow: 'hidden',
@@ -230,16 +229,6 @@ const styles = stylex.create({
cursor: 'pointer',
marginBlockStart: spacingVars['--spacing-1'],
},
- divider: {
- width: 1,
- backgroundColor: colorVars['--color-divider'],
- flexShrink: 0,
- },
- // Anchor positioning: stretch panel to match the anchor width.
- anchorStretch: {
- left: 'anchor(left)' as unknown as string,
- right: 'anchor(right)' as unknown as string,
- },
});
// =============================================================================
@@ -296,7 +285,6 @@ export interface XDSTopNavMegaMenuProps {
/** Delay before hiding the menu after mouse leaves (ms). @default 250 */
hideDelay?: number;
/** Whether to use single-column layout for items. @default false */
- isSingleColumn?: boolean;
/**
* Callback fired when the mega menu opens or closes.
* Useful for coordinating wrapper styles (e.g. hiding other shadows).
@@ -305,25 +293,6 @@ export interface XDSTopNavMegaMenuProps {
}
// =============================================================================
-// Chevron Icon
-// =============================================================================
-
-function ChevronDown() {
- return (
- <svg
- width="12"
- height="12"
- viewBox="0 0 12 12"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round">
- <path d="M3 4.5L6 7.5L9 4.5" />
- </svg>
- );
-}
-
// =============================================================================
// XDSTopNavMegaMenu
// =============================================================================
@@ -337,32 +306,27 @@ function ChevronDown() {
*
* The panel is promoted to the top layer via the Popover API (through
* useXDSLayer) and positioned via CSS anchor positioning relative to the
- * nearest positioned ancestor (typically the nav bar wrapper).
- *
- * For correct full-width behavior, wrap the XDSTopNav in a container with
- * `position: relative`.
+ * parent `<nav>` element (the XDSTopNav).
*
* @example
* ```
- * <div style={{ position: 'relative' }}>
- * <XDSTopNav
- * startContent={
- * <XDSTopNavMegaMenu
- * label="Products"
- * items={[
- * { title: 'Analytics', description: 'Track behavior', icon: <ChartIcon /> },
- * { title: 'Messaging', description: 'Real-time comms', icon: <ChatIcon /> },
- * ]}
- * featured={{
- * title: 'New: AI Features',
- * description: 'Explore our latest AI-powered tools.',
- * linkText: 'Learn more \u2192',
- * linkHref: '/ai',
- * }}
- * />
- * }
- * />
- * </div>
+ * <XDSTopNav
+ * startContent={
+ * <XDSTopNavMegaMenu
+ * label="Products"
+ * items={[
+ * { title: 'Analytics', description: 'Track behavior', icon: <ChartIcon /> },
+ * { title: 'Messaging', description: 'Real-time comms', icon: <ChatIcon /> },
+ * ]}
+ * featured={{
+ * title: 'New: AI Features',
+ * description: 'Explore our latest AI-powered tools.',
+ * linkText: 'Learn more \u2192',
+ * linkHref: '/ai',
+ * }}
+ * />
+ * }
+ * />
* ```
*/
export function XDSTopNavMegaMenu({
@@ -371,59 +335,31 @@ export function XDSTopNavMegaMenu({
featured,
delay = 150,
hideDelay = 250,
- isSingleColumn = false,
onOpenChange,
}: XDSTopNavMegaMenuProps) {
- const [isOpen, setIsOpen] = useState(false);
+ const slot = useTopNavSlot();
const showTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const wrapperRef = useRef<HTMLDivElement | null>(null);
+ const triggerButtonRef = useRef<HTMLButtonElement | null>(null);
+ const clickLockedRef = useRef(false);
- // useXDSLayer handles: Popover API (top layer), CSS anchor positioning,
- // toggle event sync, and popover element rendering.
- const layer = useXDSLayer({
- mode: 'context',
- lightDismiss: false, // Hover-driven, not click-to-dismiss
+ const popover = useXDSPopover({
+ dialogLabel: label,
+ xstyle: styles.panelAnimation,
onShow: () => onOpenChange?.(true),
onHide: () => onOpenChange?.(false),
});
- // Set the CSS anchor to the nearest positioned ancestor (the nav wrapper).
- // The panel spans this element's full width.
+ // Set the CSS anchor to the parent <nav> element (the XDSTopNav).
useEffect(() => {
- const wrapper = wrapperRef.current;
- if (!wrapper) return;
-
- let el: HTMLElement | null = wrapper.parentElement;
- while (el) {
- const position = getComputedStyle(el).position;
- if (
- position === 'relative' ||
- position === 'absolute' ||
- position === 'fixed'
- ) {
- layer.ref(el);
- break;
- }
- el = el.parentElement;
+ const nav = triggerButtonRef.current?.closest('nav');
+ if (nav) {
+ popover.triggerRef(nav as HTMLElement);
}
-
return () => {
- layer.ref(null);
+ popover.triggerRef(null);
};
- }, [layer]);
-
- const setOpen = useCallback(
- (open: boolean) => {
- setIsOpen(open);
- if (open) {
- layer.show();
- } else {
- layer.hide();
- }
- },
- [layer],
- );
+ }, [popover]);
const clearTimeouts = useCallback(() => {
if (showTimeoutRef.current) {
@@ -439,35 +375,36 @@ export function XDSTopNavMegaMenu({
const scheduleShow = useCallback(() => {
clearTimeouts();
showTimeoutRef.current = setTimeout(() => {
- setOpen(true);
+ popover.show({skipAutoFocus: true});
}, delay);
- }, [clearTimeouts, setOpen, delay]);
+ }, [clearTimeouts, popover, delay]);
const scheduleHide = useCallback(() => {
clearTimeouts();
hideTimeoutRef.current = setTimeout(() => {
- setOpen(false);
+ popover.hide();
}, hideDelay);
- }, [clearTimeouts, setOpen, hideDelay]);
+ }, [clearTimeouts, popover, hideDelay]);
const handleMouseEnter = useCallback(() => {
- scheduleShow();
+ if (!clickLockedRef.current) scheduleShow();
}, [scheduleShow]);
const handleMouseLeave = useCallback(() => {
- scheduleHide();
+ if (!clickLockedRef.current) scheduleHide();
}, [scheduleHide]);
- const handleKeyDown = useCallback(
- (e: React.KeyboardEvent) => {
- if (e.key === 'Escape') {
- e.stopPropagation();
- clearTimeouts();
- setOpen(false);
- }
- },
- [clearTimeouts, setOpen],
- );
+ const handleClick = useCallback(() => {
+ clearTimeouts();
+ if (popover.isOpen) {
+ clickLockedRef.current = false;
+ popover.hide();
+ triggerButtonRef.current?.focus();
+ } else {
+ clickLockedRef.current = true;
+ popover.show();
+ }
+ }, [popover, clearTimeouts]);
useEffect(() => {
return () => {
@@ -476,26 +413,29 @@ export function XDSTopNavMegaMenu({
}, [clearTimeouts]);
return (
- <div
- ref={wrapperRef}
- onMouseEnter={handleMouseEnter}
- onMouseLeave={handleMouseLeave}
- onKeyDown={handleKeyDown}
- {...mergeProps(
- xdsClassName('top-nav-mega-menu'),
- stylex.props(styles.wrapper),
- )}>
+ <>
<button
+ ref={triggerButtonRef}
type="button"
aria-haspopup="true"
- aria-expanded={isOpen}
- {...stylex.props(styles.trigger, isOpen && styles.triggerOpen)}>
+ aria-expanded={popover.isOpen}
+ onClick={handleClick}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ {...mergeProps(
+ xdsClassName('top-nav-mega-menu'),
+ stylex.props(styles.trigger, popover.isOpen && styles.triggerOpen),
+ )}>
{label}
- <span {...stylex.props(styles.chevron, isOpen && styles.chevronOpen)}>
- <ChevronDown />
+ <span
+ {...stylex.props(
+ styles.chevron,
+ popover.isOpen && styles.chevronOpen,
+ )}>
+ {getIcon('chevronDown')}
</span>
</button>
- {layer.render(
+ {popover.render(
<div
role="menu"
aria-label={label}
@@ -504,90 +444,85 @@ export function XDSTopNavMegaMenu({
{...stylex.props(styles.panelContainer)}>
<div {...stylex.props(styles.panelContent)}>
{/* Menu items section */}
- <div
- {...stylex.props(
- styles.menuSection,
- isSingleColumn && styles.menuSectionSingle,
- )}>
- {items.map((item, index) => {
- const Element = item.href ? 'a' : 'div';
- return (
- <Element
- key={index}
- role="menuitem"
- tabIndex={isOpen ? 0 : -1}
- href={item.href}
- onClick={item.onClick}
- {...stylex.props(styles.menuItem)}>
- {item.icon && (
- <div {...stylex.props(styles.menuItemIcon)}>
- {item.icon}
- </div>
- )}
- <div {...stylex.props(styles.menuItemContent)}>
- <span {...stylex.props(styles.menuItemTitle)}>
- {item.title}
- </span>
- {item.description && (
- <span {...stylex.props(styles.menuItemDescription)}>
- {item.description}
- </span>
+ <div {...stylex.props(styles.menuWrapper)}>
+ <XDSGrid columns={2} minChildWidth={200} gap={2}>
+ {items.map((item, index) => {
+ const Element = item.href ? 'a' : 'div';
+ return (
+ <Element
+ key={index}
+ role="menuitem"
+ tabIndex={popover.isOpen ? 0 : -1}
+ href={item.href}
+ onClick={item.onClick}
+ {...stylex.props(styles.menuItem)}>
+ {item.icon && (
+ <div {...stylex.props(styles.menuItemIcon)}>
+ {item.icon}
+ </div>
)}
- </div>
- </Element>
- );
- })}
+ <div {...stylex.props(styles.menuItemContent)}>
+ <span {...stylex.props(styles.menuItemTitle)}>
+ {item.title}
+ </span>
+ {item.description && (
+ <span {...stylex.props(styles.menuItemDescription)}>
+ {item.description}
+ </span>
+ )}
+ </div>
+ </Element>
+ );
+ })}
+ </XDSGrid>
</div>
{/* Featured section */}
{featured && (
- <>
- <div {...stylex.props(styles.divider)} />
- <div {...stylex.props(styles.featured)}>
- {featured.children ? (
- featured.children
- ) : (
- <>
- {featured.image && (
- <img
- src={featured.image}
- alt={featured.imageAlt ?? ''}
- {...stylex.props(styles.featuredImage)}
- />
- )}
- <div {...stylex.props(styles.featuredBody)}>
- <span {...stylex.props(styles.featuredTitle)}>
- {featured.title}
+ <div {...stylex.props(styles.featured)}>
+ {featured.children ? (
+ featured.children
+ ) : (
+ <>
+ {featured.image && (
+ <img
+ src={featured.image}
+ alt={featured.imageAlt ?? ''}
+ {...stylex.props(styles.featuredImage)}
+ />
+ )}
+ <div {...stylex.props(styles.featuredBody)}>
+ <span {...stylex.props(styles.featuredTitle)}>
+ {featured.title}
+ </span>
+ {featured.description && (
+ <span {...stylex.props(styles.featuredDescription)}>
+ {featured.description}
</span>
- {featured.description && (
- <span {...stylex.props(styles.featuredDescription)}>
- {featured.description}
- </span>
- )}
- {featured.linkText && (
- <a
- href={featured.linkHref}
- onClick={featured.onLinkClick}
- tabIndex={isOpen ? 0 : -1}
- {...stylex.props(styles.featuredLink)}>
- {featured.linkText}
- </a>
- )}
- </div>
- </>
- )}
- </div>
- </>
+ )}
+ {featured.linkText && (
+ <a
+ href={featured.linkHref}
+ onClick={featured.onLinkClick}
+ tabIndex={popover.isOpen ? 0 : -1}
+ {...stylex.props(styles.featuredLink)}>
+ {featured.linkText}
+ </a>
+ )}
+ </div>
+ </>
+ )}
+ </div>
)}
</div>
</div>,
{
placement: 'below',
- alignment: 'center',
- xstyle: [styles.panelAnimation, styles.anchorStretch],
+ alignment: slot,
+ xstyle: styles.panelAnimation,
},
)}
- </div>
+ </>
);
}
diff --git a/packages/core/src/TopNav/XDSTopNavMenu.test.tsx b/packages/core/src/TopNav/XDSTopNavMenu.test.tsx
index ba3886e375..502ec7352a 100644
--- a/packages/core/src/TopNav/XDSTopNavMenu.test.tsx
+++ b/packages/core/src/TopNav/XDSTopNavMenu.test.tsx
@@ -33,7 +33,7 @@ describe('XDSTopNavMenu', () => {
it('trigger has aria-haspopup attribute', () => {
render(<XDSTopNavMenu label="Products" items={mockItems} />);
const trigger = screen.getByRole('button', {name: 'Products'});
- expect(trigger).toHaveAttribute('aria-haspopup', 'true');
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
});
it('renders with custom items', () => {
diff --git a/packages/core/src/TopNav/XDSTopNavMenu.tsx b/packages/core/src/TopNav/XDSTopNavMenu.tsx
index aa149b4afe..b40e6e9bb0 100644
--- a/packages/core/src/TopNav/XDSTopNavMenu.tsx
+++ b/packages/core/src/TopNav/XDSTopNavMenu.tsx
@@ -10,9 +10,13 @@
* - /packages/core/src/TopNav/index.ts
*/
-import {type ReactNode} from 'react';
+import {useCallback, useEffect, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {useXDSHoverCard} from '../HoverCard/useXDSHoverCard';
+import {useXDSPopover} from '../Popover/useXDSPopover';
+import {useListFocus} from '../hooks/useListFocus';
+import {getIcon} from '../Icon/globalIconRegistry';
+import {xdsClassName, mergeProps} from '../utils';
+import {useTopNavSlot} from './TopNavContext';
import {
colorVars,
spacingVars,
@@ -21,6 +25,7 @@ import {
textSizeVars,
fontWeightVars,
lineHeightVars,
+ elevationVars,
} from '../theme/tokens.stylex';
// =============================================================================
@@ -60,11 +65,32 @@ const styles = stylex.create({
border: 'none',
fontFamily: 'inherit',
},
+ triggerOpen: {
+ color: colorVars['--color-text-primary'],
+ backgroundColor: colorVars['--color-hover-overlay'],
+ },
+ chevron: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ transitionProperty: 'transform',
+ transitionDuration: transitionVars['--transition-fast'],
+ },
+ chevronOpen: {
+ transform: 'rotate(180deg)',
+ },
menuContainer: {
display: 'flex',
flexDirection: 'column',
- gap: spacingVars['--spacing-2'],
+ gap: spacingVars['--spacing-1'],
minWidth: 280,
+ padding: spacingVars['--spacing-1'],
+ backgroundColor: colorVars['--color-popover'],
+ borderRadius: radiusVars['--radius-container'],
+ boxShadow: elevationVars['--elevation-menu'],
+ },
+ menuOffset: {
+ marginBlockStart: spacingVars['--spacing-1'],
+ backgroundColor: 'transparent',
},
menuItem: {
display: 'flex',
@@ -220,34 +246,128 @@ export interface XDSTopNavMenuProps {
* />
* ```
*/
+
export function XDSTopNavMenu({
label,
items,
delay = 150,
hideDelay = 200,
}: XDSTopNavMenuProps) {
- const hoverCard = useXDSHoverCard({
- placement: 'below',
- alignment: 'start',
- delay,
- hideDelay,
- focusTrigger: 'always',
+ const slot = useTopNavSlot();
+ const showTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const triggerButtonRef = useRef<HTMLButtonElement | null>(null);
+ const clickLockedRef = useRef(false);
+
+ const popover = useXDSPopover({
+ dialogLabel: label,
+ xstyle: styles.menuOffset,
});
+ const {
+ listRef: menuRef,
+ handleKeyDown: handleListKeyDown,
+ focusFirst,
+ } = useListFocus({
+ onEscape: () => {
+ clearTimeouts();
+ clickLockedRef.current = false;
+ popover.hide();
+ triggerButtonRef.current?.focus();
+ },
+ });
+
+ const clearTimeouts = useCallback(() => {
+ if (showTimeoutRef.current) {
+ clearTimeout(showTimeoutRef.current);
+ showTimeoutRef.current = null;
+ }
+ if (hideTimeoutRef.current) {
+ clearTimeout(hideTimeoutRef.current);
+ hideTimeoutRef.current = null;
+ }
+ }, []);
+
+ const scheduleShow = useCallback(() => {
+ clearTimeouts();
+ showTimeoutRef.current = setTimeout(() => {
+ popover.show({skipAutoFocus: true});
+ }, delay);
+ }, [clearTimeouts, popover, delay]);
+
+ const scheduleHide = useCallback(() => {
+ clearTimeouts();
+ hideTimeoutRef.current = setTimeout(() => {
+ popover.hide();
+ }, hideDelay);
+ }, [clearTimeouts, popover, hideDelay]);
+
+ const handleMouseEnter = useCallback(() => {
+ if (!clickLockedRef.current) scheduleShow();
+ }, [scheduleShow]);
+
+ const handleMouseLeave = useCallback(() => {
+ if (!clickLockedRef.current) scheduleHide();
+ }, [scheduleHide]);
+
+ const handleClick = useCallback(() => {
+ clearTimeouts();
+ if (popover.isOpen) {
+ clickLockedRef.current = false;
+ popover.hide();
+ triggerButtonRef.current?.focus();
+ } else {
+ clickLockedRef.current = true;
+ popover.show();
+ requestAnimationFrame(() => focusFirst());
+ }
+ }, [popover, clearTimeouts, focusFirst]);
+
+ // Combine refs — popover.triggerRef for anchor, triggerButtonRef for focus
+ const setTriggerRef = useCallback(
+ (el: HTMLButtonElement | null) => {
+ (
+ triggerButtonRef as React.MutableRefObject<HTMLButtonElement | null>
+ ).current = el;
+ popover.triggerRef(el);
+ },
+ [popover],
+ );
+
+ useEffect(() => {
+ return () => clearTimeouts();
+ }, [clearTimeouts]);
+
return (
<>
<button
- ref={hoverCard.ref}
+ ref={setTriggerRef}
type="button"
- aria-haspopup="true"
- aria-describedby={hoverCard.describedBy}
- {...stylex.props(styles.trigger)}>
+ {...popover.triggerProps}
+ onClick={handleClick}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ {...mergeProps(
+ xdsClassName('top-nav-menu'),
+ stylex.props(styles.trigger, popover.isOpen && styles.triggerOpen),
+ )}>
{label}
+ <span
+ {...stylex.props(
+ styles.chevron,
+ popover.isOpen && styles.chevronOpen,
+ )}>
+ {getIcon('chevronDown')}
+ </span>
</button>
- {hoverCard.renderHoverCard(
+ {popover.render(
<div
+ ref={menuRef as React.RefObject<HTMLDivElement>}
role="menu"
aria-label={label}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ onKeyDown={handleListKeyDown}
{...stylex.props(styles.menuContainer)}>
{items.map((item, index) => {
const Element = item.href ? 'a' : 'div';
@@ -255,7 +375,7 @@ export function XDSTopNavMenu({
<Element
key={index}
role="menuitem"
- tabIndex={0}
+ tabIndex={popover.isOpen ? 0 : -1}
href={item.href}
onClick={item.onClick}
{...stylex.props(styles.menuItem)}>
@@ -274,6 +394,11 @@ export function XDSTopNavMenu({
);
})}
</div>,
+ {
+ placement: 'below',
+ alignment: slot,
+ xstyle: styles.menuOffset,
+ },
)}
</>
);