Skip to content

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

TypeScript

refactor(MegaMenu): composed children API + mobile drawer drill-down (#659)

Cindy Zhang60e1457b4ac9
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 2851d84e0e..47d07111f0 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx
@@ -18,6 +18,8 @@ import {
XDSTopNavItem,
XDSTopNavMenu,
XDSTopNavMegaMenu,
+ XDSTopNavMegaMenuItem,
+ XDSTopNavMegaMenuFeaturedCard,
} from '@xds/core/TopNav';
import {XDSMobileNav, XDSMobileNavToggle} from '@xds/core/MobileNav';
import {XDSVStack, XDSHStack} from '@xds/core/Layout';
@@ -618,31 +620,38 @@ function SampleTopNav({
<XDSTopNavItem label="Home" href="#" isSelected />
<XDSTopNavMegaMenu
label="Products"
- items={[
- {
- title: 'Analytics',
- description: 'View metrics and dashboards',
- href: '#',
- },
- {
- title: 'Reports',
- description: 'Generate and export reports',
- href: '#',
- },
- {
- title: 'Pipelines',
- description: 'Data processing workflows',
- href: '#',
- },
- {title: 'Integrations', description: 'Connect your tools', href: '#'},
- ]}
- featured={{
- title: 'New: AI Features',
- description:
- 'Explore our latest AI-powered analytics tools for faster insights.',
- linkText: 'Learn more →',
- linkHref: '#',
- }}
+ items={
+ <>
+ <XDSTopNavMegaMenuItem
+ title="Analytics"
+ description="View metrics and dashboards"
+ href="#"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Reports"
+ description="Generate and export reports"
+ href="#"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Pipelines"
+ description="Data processing workflows"
+ href="#"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Integrations"
+ description="Connect your tools"
+ href="#"
+ />
+ </>
+ }
+ featured={
+ <XDSTopNavMegaMenuFeaturedCard
+ title="New: AI Features"
+ description="Explore our latest AI-powered analytics tools for faster insights."
+ linkLabel="Learn more"
+ linkHref="#"
+ />
+ }
/>
<XDSTopNavItem label="Team" href="#" />
</>
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 54c543cad0..9bd58290a5 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/mega-menu/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/mega-menu/page.tsx
@@ -11,6 +11,8 @@ import {
XDSTopNavHeading,
XDSTopNavItem,
XDSTopNavMegaMenu,
+ XDSTopNavMegaMenuItem,
+ XDSTopNavMegaMenuFeaturedCard,
} from '@xds/core/TopNav';
import {XDSNavIcon} from '@xds/core/NavIcon';
@@ -28,16 +30,39 @@ const styles = stylex.create({
transitionDuration: '0.2s',
transitionTimingFunction: 'ease-out',
},
- // When the mega menu opens, the wrapper becomes the top half of the
- // unified card: drop the bottom radius so it flows seamlessly into the
- // panel, and remove the wrapper shadow (the panel provides its own
- // shadow that visually wraps the dropdown area).
navWrapperMenuOpen: {
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
boxShadow:
'0 -1px 3px rgba(0, 0, 0, 0.06), -1px 0 3px rgba(0, 0, 0, 0.04), 1px 0 3px rgba(0, 0, 0, 0.04)',
},
+ featuredBody: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 8,
+ padding: 16,
+ },
+ featuredTitle: {
+ fontSize: 16,
+ fontWeight: 600,
+ color: 'var(--color-text-primary)',
+ },
+ featuredDescription: {
+ fontSize: 14,
+ color: 'var(--color-text-secondary)',
+ },
+ featuredLink: {
+ fontSize: 14,
+ fontWeight: 600,
+ color: 'var(--color-accent-text)',
+ textDecoration: 'none',
+ },
+ featuredImage: {
+ width: '100%',
+ height: 140,
+ objectFit: 'cover',
+ display: 'block',
+ },
});
// =============================================================================
@@ -156,84 +181,15 @@ const GlobeIcon = () => (
</svg>
);
-// =============================================================================
-// Demo Data
-// =============================================================================
-
-const productItems = [
- {
- title: 'Analytics',
- description: 'Track and analyze user behavior across your applications',
- icon: <ChartIcon />,
- href: '#analytics',
- },
- {
- title: 'Platform',
- description: 'End-to-end infrastructure for building at scale',
- icon: <LayersIcon />,
- href: '#platform',
- },
- {
- title: 'Security',
- description: 'Enterprise-grade protection for your data and users',
- icon: <ShieldIcon />,
- href: '#security',
- },
- {
- title: 'Automation',
- description: 'Streamline workflows with intelligent automation tools',
- icon: <ZapIcon />,
- href: '#automation',
- },
- {
- title: 'Developer Tools',
- description: 'APIs, SDKs, and CLI tools for seamless integration',
- icon: <CodeIcon />,
- href: '#dev-tools',
- },
- {
- title: 'Global Network',
- description: 'Low-latency edge infrastructure in 40+ regions',
- icon: <GlobeIcon />,
- href: '#network',
- },
-];
-
-const solutionItems = [
- {
- title: 'Enterprise',
- description: 'Solutions for large-scale organizations',
- icon: <LayersIcon />,
- href: '#enterprise',
- },
- {
- title: 'Startups',
- description: 'Get started fast with startup-friendly pricing',
- icon: <ZapIcon />,
- href: '#startups',
- },
- {
- title: 'Developers',
- description: 'Build with powerful APIs and documentation',
- icon: <CodeIcon />,
- href: '#developers',
- },
-];
-
// =============================================================================
// Page
// =============================================================================
-/**
- * Demo page for XDSTopNavMegaMenu — a nav item with a full-width mega menu.
- */
export default function MegaMenuPage() {
const [menuOpen1, setMenuOpen1] = useState(false);
const [menuOpen2, setMenuOpen2] = useState(false);
const [menuOpen3, setMenuOpen3] = useState(false);
- const isAnyOpen1 = menuOpen1 || menuOpen2;
-
return (
<div {...stylex.props(styles.container)}>
<XDSVStack gap={6}>
@@ -241,8 +197,7 @@ export default function MegaMenuPage() {
<XDSHeading level={1}>Mega Menu</XDSHeading>
<XDSText type="body" color="secondary">
A top nav variation with a full-width mega menu that appears on
- hover. The nav bar and dropdown panel appear as one unified card.
- Hover over &quot;Products&quot; or &quot;Solutions&quot; to see it.
+ hover. Uses the slots API with XDSTopNavMegaMenuItem components.
</XDSText>
</XDSVStack>
@@ -263,30 +218,91 @@ export default function MegaMenuPage() {
<>
<XDSTopNavMegaMenu
label="Products"
- items={productItems}
onOpenChange={setMenuOpen1}
- featured={{
- image:
- 'https://images.unsplash.com/photo-1551434678-e076c223a692?w=560&h=280&fit=crop',
- imageAlt: 'Team collaboration',
- title: 'What\u2019s new in v4.0',
- description:
- 'Explore the latest features including AI-powered analytics and real-time collaboration.',
- linkText: 'Read the announcement \u2192',
- linkHref: '#announcement',
- }}
+ items={
+ <>
+ <XDSTopNavMegaMenuItem
+ title="Analytics"
+ description="Track and analyze user behavior across your applications"
+ icon={<ChartIcon />}
+ href="#analytics"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Platform"
+ description="End-to-end infrastructure for building at scale"
+ icon={<LayersIcon />}
+ href="#platform"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Security"
+ description="Enterprise-grade protection for your data and users"
+ icon={<ShieldIcon />}
+ href="#security"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Automation"
+ description="Streamline workflows with intelligent automation tools"
+ icon={<ZapIcon />}
+ href="#automation"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Developer Tools"
+ description="APIs, SDKs, and CLI tools for seamless integration"
+ icon={<CodeIcon />}
+ href="#dev-tools"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Global Network"
+ description="Low-latency edge infrastructure in 40+ regions"
+ icon={<GlobeIcon />}
+ href="#network"
+ />
+ </>
+ }
+ featured={
+ <XDSTopNavMegaMenuFeaturedCard
+ title="What's new in v4.0"
+ description="Explore the latest features including AI-powered analytics and real-time collaboration."
+ image="https://images.unsplash.com/photo-1551434678-e076c223a692?w=560&h=280&fit=crop"
+ imageAlt="Team collaboration"
+ linkLabel="Read the announcement"
+ linkHref="#announcement"
+ />
+ }
/>
<XDSTopNavMegaMenu
label="Solutions"
- items={solutionItems}
onOpenChange={setMenuOpen2}
- featured={{
- title: 'Customer Stories',
- description:
- 'See how leading companies are building with our platform.',
- linkText: 'View case studies \u2192',
- linkHref: '#case-studies',
- }}
+ items={
+ <>
+ <XDSTopNavMegaMenuItem
+ title="Enterprise"
+ description="Solutions for large-scale organizations"
+ icon={<LayersIcon />}
+ href="#enterprise"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Startups"
+ description="Get started fast with startup-friendly pricing"
+ icon={<ZapIcon />}
+ href="#startups"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Developers"
+ description="Build with powerful APIs and documentation"
+ icon={<CodeIcon />}
+ href="#developers"
+ />
+ </>
+ }
+ featured={
+ <XDSTopNavMegaMenuFeaturedCard
+ title="Customer Stories"
+ description="See how leading companies are building with our platform."
+ linkLabel="View case studies"
+ linkHref="#case-studies"
+ />
+ }
/>
<XDSTopNavItem label="Learn" href="#" />
</>
@@ -313,27 +329,29 @@ export default function MegaMenuPage() {
<XDSTopNavItem label="Home" href="#" isSelected />
<XDSTopNavMegaMenu
label="Features"
- items={[
- {
- title: 'Dashboard',
- description: 'Overview of your key metrics',
- icon: <ChartIcon />,
- href: '#dashboard',
- },
- {
- title: 'Integrations',
- description: 'Connect with your favorite tools',
- icon: <CodeIcon />,
- href: '#integrations',
- },
- {
- title: 'API Access',
- description: 'Programmatic access to all features',
- icon: <GlobeIcon />,
- href: '#api',
- },
- ]}
onOpenChange={setMenuOpen3}
+ items={
+ <>
+ <XDSTopNavMegaMenuItem
+ title="Dashboard"
+ description="Overview of your key metrics"
+ icon={<ChartIcon />}
+ href="#dashboard"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Integrations"
+ description="Connect with your favorite tools"
+ icon={<CodeIcon />}
+ href="#integrations"
+ />
+ <XDSTopNavMegaMenuItem
+ title="API Access"
+ description="Programmatic access to all features"
+ icon={<GlobeIcon />}
+ href="#api"
+ />
+ </>
+ }
/>
<XDSTopNavItem label="Pricing" href="#" />
</>
diff --git a/apps/storybook/stories/TopNavMenu.stories.tsx b/apps/storybook/stories/TopNavMenu.stories.tsx
index e15b029a51..1fe1ae5479 100644
--- a/apps/storybook/stories/TopNavMenu.stories.tsx
+++ b/apps/storybook/stories/TopNavMenu.stories.tsx
@@ -6,6 +6,8 @@ import {
XDSTopNavItem,
XDSTopNavMenu,
XDSTopNavMegaMenu,
+ XDSTopNavMegaMenuItem,
+ XDSTopNavMegaMenuFeaturedCard,
} from '@xds/core/TopNav';
import {XDSNavIcon} from '@xds/core/NavIcon';
import {XDSButton} from '@xds/core/Button';
@@ -143,13 +145,11 @@ export const MultipleMenus: Story = {
};
// =============================================================================
-// TopNavMegaMenu Stories
+// TopNavMegaMenu Stories — Composed Children API
// =============================================================================
/**
- * Full-width mega menu with items grid and featured content area.
- * Wrap XDSTopNav in a container with `position: relative` for
- * correct full-width panel positioning.
+ * Full-width mega menu with composed children API.
*/
export const MegaMenu: Story = {
name: 'Mega Menu',
@@ -176,49 +176,50 @@ export const MegaMenu: Story = {
<XDSTopNavMegaMenu
label="Products"
onOpenChange={setMenuOpen}
- items={[
- {
- title: 'Analytics',
- description:
- 'Track and analyze user behavior across your apps',
- icon: <ChartBarIcon style={{width: 20, height: 20}} />,
- href: '#analytics',
- },
- {
- title: 'Security',
- description: 'Enterprise-grade protection for your data',
- icon: <ShieldCheckIcon style={{width: 20, height: 20}} />,
- href: '#security',
- },
- {
- title: 'Automation',
- description: 'Streamline workflows with intelligent tools',
- icon: <BoltIcon style={{width: 20, height: 20}} />,
- href: '#automation',
- },
- {
- title: 'Developer Tools',
- description: 'APIs, SDKs, and CLI for integration',
- icon: <CodeBracketIcon style={{width: 20, height: 20}} />,
- href: '#dev-tools',
- },
- {
- title: 'Global Network',
- description: 'Low-latency edge infra in 40+ regions',
- icon: <GlobeAltIcon style={{width: 20, height: 20}} />,
- href: '#network',
- },
- ]}
- featured={{
- image:
- 'https://images.unsplash.com/photo-1551434678-e076c223a692?w=560&h=280&fit=crop',
- imageAlt: 'Team collaboration',
- title: 'What\u2019s new in v4.0',
- description:
- 'AI-powered analytics and real-time collaboration.',
- linkText: 'Read the announcement \u2192',
- linkHref: '#announcement',
- }}
+ items={
+ <>
+ <XDSTopNavMegaMenuItem
+ title="Analytics"
+ description="Track and analyze user behavior across your apps"
+ icon={<ChartBarIcon style={{width: 20, height: 20}} />}
+ href="#analytics"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Security"
+ description="Enterprise-grade protection for your data"
+ icon={<ShieldCheckIcon style={{width: 20, height: 20}} />}
+ href="#security"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Automation"
+ description="Streamline workflows with intelligent tools"
+ icon={<BoltIcon style={{width: 20, height: 20}} />}
+ href="#automation"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Developer Tools"
+ description="APIs, SDKs, and CLI for integration"
+ icon={<CodeBracketIcon style={{width: 20, height: 20}} />}
+ href="#dev-tools"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Global Network"
+ description="Low-latency edge infra in 40+ regions"
+ icon={<GlobeAltIcon style={{width: 20, height: 20}} />}
+ href="#network"
+ />
+ </>
+ }
+ featured={
+ <XDSTopNavMegaMenuFeaturedCard
+ title="What's new in v4.0"
+ description="AI-powered analytics and real-time collaboration."
+ image="https://images.unsplash.com/photo-1551434678-e076c223a692?w=560&h=280&fit=crop"
+ imageAlt="Team collaboration"
+ linkLabel="Read the announcement"
+ linkHref="#announcement"
+ />
+ }
/>
<XDSTopNavItem label="Pricing" href="#" />
<XDSTopNavItem label="Docs" href="#" />
@@ -238,7 +239,6 @@ export const MegaMenu: Story = {
/**
* Mega menu without the featured content area — just the items grid.
- * Uses single-column layout for fewer items.
*/
export const MegaMenuSimple: Story = {
name: 'Mega Menu (Simple)',
@@ -252,27 +252,28 @@ export const MegaMenuSimple: Story = {
<XDSTopNavItem label="Home" href="#" isSelected />
<XDSTopNavMegaMenu
label="Features"
- isSingleColumn
- items={[
- {
- title: 'Dashboard',
- description: 'Overview of your key metrics',
- icon: <ChartBarIcon style={{width: 20, height: 20}} />,
- href: '#',
- },
- {
- title: 'Integrations',
- description: 'Connect with your favorite tools',
- icon: <CodeBracketIcon style={{width: 20, height: 20}} />,
- href: '#',
- },
- {
- title: 'API Access',
- description: 'Programmatic access to all features',
- icon: <GlobeAltIcon style={{width: 20, height: 20}} />,
- href: '#',
- },
- ]}
+ items={
+ <>
+ <XDSTopNavMegaMenuItem
+ title="Dashboard"
+ description="Overview of your key metrics"
+ icon={<ChartBarIcon style={{width: 20, height: 20}} />}
+ href="#"
+ />
+ <XDSTopNavMegaMenuItem
+ title="Integrations"
+ description="Connect with your favorite tools"
+ icon={<CodeBracketIcon style={{width: 20, height: 20}} />}
+ href="#"
+ />
+ <XDSTopNavMegaMenuItem
+ title="API Access"
+ description="Programmatic access to all features"
+ icon={<GlobeAltIcon style={{width: 20, height: 20}} />}
+ href="#"
+ />
+ </>
+ }
/>
</>
}
diff --git a/packages/core/src/TopNav/TopNav.doc.mjs b/packages/core/src/TopNav/TopNav.doc.mjs
index 5b808b235e..481bad4d45 100644
--- a/packages/core/src/TopNav/TopNav.doc.mjs
+++ b/packages/core/src/TopNav/TopNav.doc.mjs
@@ -74,16 +74,20 @@ export const docs = {
/>
<XDSTopNavMegaMenu
label="Solutions"
- items={[
- {title: 'Enterprise', description: 'For large teams', icon: <BuildingIcon />, href: '/enterprise'},
- {title: 'Startups', description: 'Move fast', icon: <RocketIcon />, href: '/startups'},
- ]}
- featured={{
- title: 'New: AI Features',
- description: 'Explore our latest AI-powered tools.',
- linkText: 'Learn more \u2192',
- linkHref: '/ai',
- }}
+ items={
+ <>
+ <XDSTopNavMegaMenuItem title="Enterprise" description="For large teams" icon={<BuildingIcon />} href="/enterprise" />
+ <XDSTopNavMegaMenuItem title="Startups" description="Move fast" icon={<RocketIcon />} href="/startups" />
+ </>
+ }
+ featured={
+ <XDSTopNavMegaMenuFeaturedCard
+ title="New: AI Features"
+ description="Explore our latest AI-powered tools."
+ linkLabel="Learn more"
+ linkHref="/ai"
+ />
+ }
/>
</>
}
@@ -396,7 +400,7 @@ export const docs = {
{
name: 'XDSTopNavMegaMenu',
description:
- 'Navigation item that displays a full-width mega menu panel on hover, with items in a two-column grid and an optional featured content area.',
+ 'Navigation item that displays a full-width mega menu panel on hover. Uses a slots API with items and featured props. XDSTopNavMegaMenuItem renders itself in both desktop and mobile drawer modes. Supports inline collapsible drawer via render mode context.',
props: [
{
name: 'label',
@@ -406,15 +410,13 @@ export const docs = {
},
{
name: 'items',
- type: 'XDSTopNavMegaMenuItemData[]',
- description: 'Menu items to display in the mega menu panel.',
- required: true,
+ type: 'ReactNode',
+ description: 'Menu items slot — typically XDSTopNavMegaMenuItem components, but accepts any ReactNode.',
},
{
name: 'featured',
- type: 'XDSTopNavMegaMenuFeatured',
- description:
- 'Optional featured content displayed on the right side of the mega menu panel.',
+ type: 'ReactNode',
+ description: 'Featured content slot — rendered in the right panel on desktop, below items in the mobile drawer.',
},
{
name: 'delay',
@@ -430,13 +432,6 @@ export const docs = {
'Delay in milliseconds before hiding the menu after the mouse leaves.',
default: '250',
},
- {
- name: 'isSingleColumn',
- type: 'boolean',
- description:
- 'Whether to use a single-column layout for menu items instead of two columns.',
- default: 'false',
- },
{
name: 'onOpenChange',
type: '(isOpen: boolean) => void',
@@ -447,36 +442,34 @@ export const docs = {
examples: [
{
label: 'With featured content',
- code: `<div style={{position: 'relative'}}>
- <XDSTopNav
- startContent={
- <XDSTopNavMegaMenu
- label="Solutions"
- items={[
- {title: 'Enterprise', description: 'For large teams', icon: <BuildingIcon />, href: '/enterprise'},
- {title: 'Startups', description: 'Move fast', icon: <RocketIcon />, href: '/startups'},
- ]}
- featured={{
- title: 'New: AI Features',
- description: 'Explore our latest AI-powered tools.',
- linkText: 'Learn more \u2192',
- linkHref: '/ai',
- }}
- />
- }
- />
-</div>`,
+ code: `<XDSTopNavMegaMenu
+ label="Solutions"
+ items={
+ <>
+ <XDSTopNavMegaMenuItem title="Enterprise" description="For large teams" icon={<BuildingIcon />} href="/enterprise" />
+ <XDSTopNavMegaMenuItem title="Startups" description="Move fast" icon={<RocketIcon />} href="/startups" />
+ </>
+ }
+ featured={
+ <XDSTopNavMegaMenuFeaturedCard
+ title="New: AI Features"
+ description="Explore our latest AI-powered tools."
+ linkLabel="Learn more"
+ linkHref="/ai"
+ />
+ }
+/>`,
},
{
- label: 'Single column layout',
+ label: 'Without featured content',
code: `<XDSTopNavMegaMenu
label="Products"
- isSingleColumn
- items={[
- {title: 'Analytics', description: 'Track behavior', icon: <ChartIcon />, href: '/analytics'},
- {title: 'Messaging', description: 'Real-time comms', icon: <ChatIcon />, href: '/messaging'},
- {title: 'Storage', description: 'Manage your data', icon: <DatabaseIcon />, href: '/storage'},
- ]}
+ items={
+ <>
+ <XDSTopNavMegaMenuItem title="Analytics" description="Track behavior" icon={<ChartIcon />} href="/analytics" />
+ <XDSTopNavMegaMenuItem title="Messaging" description="Real-time comms" icon={<ChatIcon />} href="/messaging" />
+ </>
+ }
/>`,
},
],
@@ -559,16 +552,20 @@ export const docsZh = {
/>
<XDSTopNavMegaMenu
label="Solutions"
- items={[
- {title: 'Enterprise', description: 'For large teams', icon: <BuildingIcon />, href: '/enterprise'},
- {title: 'Startups', description: 'Move fast', icon: <RocketIcon />, href: '/startups'},
- ]}
- featured={{
- title: 'New: AI Features',
- description: 'Explore our latest AI-powered tools.',
- linkText: 'Learn more \u2192',
- linkHref: '/ai',
- }}
+ items={
+ <>
+ <XDSTopNavMegaMenuItem title="Enterprise" description="大型团队解决方案" icon={<BuildingIcon />} href="/enterprise" />
+ <XDSTopNavMegaMenuItem title="Startups" description="快速启动" icon={<RocketIcon />} href="/startups" />
+ </>
+ }
+ featured={
+ <XDSTopNavMegaMenuFeaturedCard
+ title="新功能:AI 特性"
+ description="探索我们最新的 AI 驱动工具。"
+ linkLabel="了解更多"
+ linkHref="/ai"
+ />
+ }
/>
</>
}
@@ -881,7 +878,7 @@ export const docsZh = {
{
name: 'XDSTopNavMegaMenu',
description:
- '导航项,在悬停时显示全宽超级菜单面板,包含双列网格布局的项目和可选的特色内容区域。',
+ '导航项,在悬停时显示全宽超级菜单面板。使用插槽 API(items 和 featured)。XDSTopNavMegaMenuItem 在桌面和移动抽屉模式中自行渲染。',
props: [
{
name: 'label',
@@ -891,15 +888,13 @@ export const docsZh = {
},
{
name: 'items',
- type: 'XDSTopNavMegaMenuItemData[]',
- description: '在超级菜单面板中显示的菜单项。',
- required: true,
+ type: 'ReactNode',
+ description: '菜单项插槽 — 通常为 XDSTopNavMegaMenuItem 组件,但接受任何 ReactNode。',
},
{
name: 'featured',
- type: 'XDSTopNavMegaMenuFeatured',
- description:
- '在超级菜单面板右侧显示的可选特色内容。',
+ type: 'ReactNode',
+ description: '特色内容插槽 — 桌面端显示在右侧面板,移动抽屉中显示在项目下方。',
},
{
name: 'delay',
@@ -915,13 +910,6 @@ export const docsZh = {
'鼠标离开后隐藏菜单的延迟(毫秒)。',
default: '250',
},
- {
- name: 'isSingleColumn',
- type: 'boolean',
- description:
- '是否对菜单项使用单列布局而非双列。',
- default: 'false',
- },
{
name: 'onOpenChange',
type: '(isOpen: boolean) => void',
@@ -932,36 +920,34 @@ export const docsZh = {
examples: [
{
label: '带特色内容',
- code: `<div style={{position: 'relative'}}>
- <XDSTopNav
- startContent={
- <XDSTopNavMegaMenu
- label="Solutions"
- items={[
- {title: 'Enterprise', description: 'For large teams', icon: <BuildingIcon />, href: '/enterprise'},
- {title: 'Startups', description: 'Move fast', icon: <RocketIcon />, href: '/startups'},
- ]}
- featured={{
- title: 'New: AI Features',
- description: 'Explore our latest AI-powered tools.',
- linkText: 'Learn more \u2192',
- linkHref: '/ai',
- }}
- />
- }
- />
-</div>`,
+ code: `<XDSTopNavMegaMenu
+ label="Solutions"
+ items={
+ <>
+ <XDSTopNavMegaMenuItem title="Enterprise" description="大型团队" icon={<BuildingIcon />} href="/enterprise" />
+ <XDSTopNavMegaMenuItem title="Startups" description="快速启动" icon={<RocketIcon />} href="/startups" />
+ </>
+ }
+ featured={
+ <XDSTopNavMegaMenuFeaturedCard
+ title="新功能:AI 特性"
+ description="探索我们最新的 AI 驱动工具。"
+ linkLabel="了解更多"
+ linkHref="/ai"
+ />
+ }
+/>`,
},
{
- label: '单列布局',
+ label: '无特色内容',
code: `<XDSTopNavMegaMenu
label="Products"
- isSingleColumn
- items={[
- {title: 'Analytics', description: 'Track behavior', icon: <ChartIcon />, href: '/analytics'},
- {title: 'Messaging', description: 'Real-time comms', icon: <ChatIcon />, href: '/messaging'},
- {title: 'Storage', description: 'Manage your data', icon: <DatabaseIcon />, href: '/storage'},
- ]}
+ items={
+ <>
+ <XDSTopNavMegaMenuItem title="Analytics" description="Track behavior" icon={<ChartIcon />} href="/analytics" />
+ <XDSTopNavMegaMenuItem title="Messaging" description="Real-time comms" icon={<ChatIcon />} href="/messaging" />
+ </>
+ }
/>`,
},
],
@@ -1046,14 +1032,13 @@ export const docsDense = {
},
{
name: 'XDSTopNavMegaMenu',
- description: 'Nav item w/ full-width mega menu panel on hover; 2-column grid+optional featured area.',
+ description: 'Nav item w/ full-width mega menu panel on hover. Slots API w/ items+featured ReactNode props. Mobile drawer inline collapsible.',
propDescriptions: {
label: 'Trigger button visible label.',
- items: 'Menu items in mega panel.',
- featured: 'Optional featured content on right side of mega panel.',
+ items: 'Menu items slot — typically XDSTopNavMegaMenuItem, accepts any ReactNode.',
+ featured: 'Featured content slot — right panel desktop, below items in drawer.',
delay: 'Show delay ms on hover.',
hideDelay: 'Hide delay ms after mouse leaves.',
- isSingleColumn: 'Single-column layout instead of two columns.',
onOpenChange: 'Fired on open/close. For coordinating wrapper styles.',
},
},
diff --git a/packages/core/src/TopNav/XDSTopNavMegaMenu.test.tsx b/packages/core/src/TopNav/XDSTopNavMegaMenu.test.tsx
new file mode 100644
index 0000000000..4326b0ad83
--- /dev/null
+++ b/packages/core/src/TopNav/XDSTopNavMegaMenu.test.tsx
@@ -0,0 +1,269 @@
+/**
+ * @file XDSTopNavMegaMenu.test.tsx
+ * @input Uses vitest, @testing-library/react, XDSTopNavMegaMenu and sub-components
+ * @output Unit tests for XDSTopNavMegaMenu slots API and mobile modes
+ * @position Testing; validates XDSTopNavMegaMenu behavior
+ *
+ * SYNC: When XDSTopNavMegaMenu changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {XDSTopNavMegaMenu} from './XDSTopNavMegaMenu';
+import {XDSTopNavMegaMenuItem} from './XDSTopNavMegaMenuItem';
+import {XDSTopNavRenderContext} from './XDSTopNavRenderContext';
+
+// =============================================================================
+// Default (desktop) mode
+// =============================================================================
+
+describe('XDSTopNavMegaMenu — default mode', () => {
+ it('renders the trigger button with label', () => {
+ render(
+ <XDSTopNavMegaMenu
+ label="Products"
+ items={<XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />,
+ );
+ expect(screen.getByRole('button', {name: 'Products'})).toBeInTheDocument();
+ });
+
+ it('trigger has aria-haspopup and aria-expanded attributes', () => {
+ render(
+ <XDSTopNavMegaMenu
+ label="Products"
+ items={<XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />,
+ );
+ const trigger = screen.getByRole('button', {name: 'Products'});
+ expect(trigger).toHaveAttribute('aria-haspopup', 'true');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('renders with multiple menu items', () => {
+ render(
+ <XDSTopNavMegaMenu
+ label="Products"
+ items={
+ <>
+ <XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />
+ <XDSTopNavMegaMenuItem title="Reports" href="/reports" />
+ </>
+ }
+ />,
+ );
+ expect(screen.getByRole('button', {name: 'Products'})).toBeInTheDocument();
+ });
+
+ it('renders with featured content', () => {
+ render(
+ <XDSTopNavMegaMenu
+ label="Products"
+ items={<XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ featured={<span data-testid="featured">Featured content</span>}
+ />,
+ );
+ expect(screen.getByRole('button', {name: 'Products'})).toBeInTheDocument();
+ });
+
+ it('renders without items or featured', () => {
+ render(<XDSTopNavMegaMenu label="Empty" />);
+ expect(screen.getByRole('button', {name: 'Empty'})).toBeInTheDocument();
+ });
+});
+
+// =============================================================================
+// Mobile-bar mode — should be hidden
+// =============================================================================
+
+describe('XDSTopNavMegaMenu — mobile-bar mode', () => {
+ it('returns null in mobile-bar mode', () => {
+ const {container} = render(
+ <XDSTopNavRenderContext.Provider value="mobile-bar">
+ <XDSTopNavMegaMenu
+ label="Products"
+ items={<XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />
+ </XDSTopNavRenderContext.Provider>,
+ );
+ expect(container.innerHTML).toBe('');
+ });
+});
+
+// =============================================================================
+// Drawer mode — inline collapsible
+// =============================================================================
+
+describe('XDSTopNavMegaMenu — drawer mode', () => {
+ it('renders a collapsible trigger with label', () => {
+ render(
+ <XDSTopNavRenderContext.Provider value="drawer">
+ <XDSTopNavMegaMenu
+ label="Products"
+ items={<XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />
+ </XDSTopNavRenderContext.Provider>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Products'});
+ expect(trigger).toBeInTheDocument();
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('expands to show items when tapped', async () => {
+ const user = userEvent.setup();
+
+ render(
+ <XDSTopNavRenderContext.Provider value="drawer">
+ <XDSTopNavMegaMenu
+ label="Products"
+ items={
+ <>
+ <XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />
+ <XDSTopNavMegaMenuItem title="Reports" href="/reports" />
+ </>
+ }
+ />
+ </XDSTopNavRenderContext.Provider>,
+ );
+
+ const trigger = screen.getByRole('button', {name: 'Products'});
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ await user.click(trigger);
+
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(screen.getByText('Analytics')).toBeInTheDocument();
+ expect(screen.getByText('Reports')).toBeInTheDocument();
+ });
+
+ it('collapses when trigger is clicked again', async () => {
+ const user = userEvent.setup();
+
+ render(
+ <XDSTopNavRenderContext.Provider value="drawer">
+ <XDSTopNavMegaMenu
+ label="Products"
+ items={<XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />
+ </XDSTopNavRenderContext.Provider>,
+ );
+
+ const trigger = screen.getByRole('button', {name: 'Products'});
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ await user.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('shows item descriptions when provided', async () => {
+ const user = userEvent.setup();
+
+ render(
+ <XDSTopNavRenderContext.Provider value="drawer">
+ <XDSTopNavMegaMenu
+ label="Products"
+ items={
+ <XDSTopNavMegaMenuItem
+ title="Analytics"
+ description="Track behavior"
+ href="/analytics"
+ />
+ }
+ />
+ </XDSTopNavRenderContext.Provider>,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Products'}));
+
+ expect(screen.getByText('Analytics')).toBeInTheDocument();
+ expect(screen.getByText('Track behavior')).toBeInTheDocument();
+ });
+
+ it('renders items as links when href is provided', async () => {
+ const user = userEvent.setup();
+
+ render(
+ <XDSTopNavRenderContext.Provider value="drawer">
+ <XDSTopNavMegaMenu
+ label="Products"
+ items={<XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ />
+ </XDSTopNavRenderContext.Provider>,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Products'}));
+
+ const link = screen.getByRole('link', {name: 'Analytics'});
+ expect(link).toHaveAttribute('href', '/analytics');
+ });
+
+ it('renders items as buttons when onClick is provided without href', async () => {
+ const user = userEvent.setup();
+ const handleClick = vi.fn();
+
+ render(
+ <XDSTopNavRenderContext.Provider value="drawer">
+ <XDSTopNavMegaMenu
+ label="Tools"
+ items={<XDSTopNavMegaMenuItem title="Export" onClick={handleClick} />}
+ />
+ </XDSTopNavRenderContext.Provider>,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Tools'}));
+ await user.click(screen.getByRole('button', {name: 'Export'}));
+
+ expect(handleClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('renders featured content when expanded', async () => {
+ const user = userEvent.setup();
+
+ render(
+ <XDSTopNavRenderContext.Provider value="drawer">
+ <XDSTopNavMegaMenu
+ label="Products"
+ items={<XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />}
+ featured={<span>Featured: New AI Tools</span>}
+ />
+ </XDSTopNavRenderContext.Provider>,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Products'}));
+
+ expect(screen.getByText('Featured: New AI Tools')).toBeInTheDocument();
+ });
+});
+
+// =============================================================================
+// XDSTopNavMegaMenuItem — standalone rendering
+// =============================================================================
+
+describe('XDSTopNavMegaMenuItem', () => {
+ it('renders as a desktop item by default', () => {
+ render(<XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />);
+ expect(screen.getByRole('link', {name: /Analytics/})).toBeInTheDocument();
+ });
+
+ it('renders description in desktop mode', () => {
+ render(
+ <XDSTopNavMegaMenuItem
+ title="Analytics"
+ description="Track behavior"
+ href="/analytics"
+ />,
+ );
+ expect(screen.getByText('Analytics')).toBeInTheDocument();
+ expect(screen.getByText('Track behavior')).toBeInTheDocument();
+ });
+
+ it('renders as a drawer item in drawer context', () => {
+ render(
+ <XDSTopNavRenderContext.Provider value="drawer">
+ <XDSTopNavMegaMenuItem title="Analytics" href="/analytics" />
+ </XDSTopNavRenderContext.Provider>,
+ );
+ expect(screen.getByRole('link', {name: /Analytics/})).toBeInTheDocument();
+ });
+});
diff --git a/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx b/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
index b2e5ce3314..069934961c 100644
--- a/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
+++ b/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
@@ -1,13 +1,18 @@
/**
* @file XDSTopNavMegaMenu.tsx
- * @input Uses React, StyleX, useXDSLayer (Popover API + CSS anchor positioning)
+ * @input Uses React, StyleX, useXDSPopover (Popover API + CSS anchor positioning)
* @output Exports XDSTopNavMegaMenu component and related types
* @position Navigation item with hover-triggered full-width mega menu for XDSTopNav
*
- * Uses useXDSLayer to promote the panel to the top layer via the Popover API,
+ * Uses useXDSPopover to promote the panel to the top layer via the Popover API,
* eliminating z-index stacking. CSS anchor positioning places the panel below
* the nav wrapper.
*
+ * Supports three render modes via XDSTopNavRenderContext:
+ * - 'default': desktop popover mega menu (hover/click triggered)
+ * - 'mobile-bar': returns null (hidden in compact mobile bar)
+ * - 'drawer': drill-down navigation with back button
+ *
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/TopNav/TopNav.doc.mjs
* - /packages/core/src/TopNav/index.ts
@@ -15,7 +20,7 @@
'use client';
-import {useCallback, useEffect, useRef, type ReactNode} from 'react';
+import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -31,7 +36,9 @@ import {useXDSPopover} from '../Popover/useXDSPopover';
import {XDSGrid} from '../Grid/XDSGrid';
import {getIcon} from '../Icon/globalIconRegistry';
import {xdsClassName, mergeProps} from '../utils';
+import {navItemStyles} from '../NavItem/navItemStyles.stylex';
import {useTopNavSlot} from './TopNavContext';
+import {useXDSTopNavRenderMode} from './XDSTopNavRenderContext';
// =============================================================================
// Styles
@@ -84,7 +91,6 @@ const styles = stylex.create({
transform: 'rotate(180deg)',
},
// Animation styles applied to the layer's popover element.
- // Uses :popover-open for enter and @starting-style for initial state.
panelAnimation: {
backgroundColor: 'transparent',
opacity: {
@@ -129,63 +135,7 @@ const styles = stylex.create({
flexBasis: 300,
minWidth: 0,
},
- menuItem: {
- display: 'flex',
- alignItems: 'flex-start',
- gap: spacingVars['--spacing-3'],
- paddingBlock: spacingVars['--spacing-3'],
- paddingInline: spacingVars['--spacing-3'],
- borderRadius: radiusVars['--radius-element'],
- textDecoration: 'none',
- cursor: 'pointer',
- transitionProperty: 'background-color',
- transitionDuration: transitionVars['--transition-fast'],
- backgroundColor: {
- default: 'transparent',
- ':hover': {
- '@media (hover: hover)': colorVars['--color-hover-overlay'],
- },
- },
- border: 'none',
- outline: {
- default: null,
- ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,
- },
- outlineOffset: {
- default: '0',
- ':focus-visible': '2px',
- },
- color: 'inherit',
- },
- menuItemIcon: {
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- width: 40,
- height: 40,
- borderRadius: radiusVars['--radius-element'],
- backgroundColor: colorVars['--color-deemphasized'],
- flexShrink: 0,
- color: colorVars['--color-icon-secondary'],
- },
- menuItemContent: {
- display: 'flex',
- flexDirection: 'column',
- gap: spacingVars['--spacing-1'],
- minWidth: 0,
- },
- menuItemTitle: {
- fontSize: textSizeVars['--text-base'],
- lineHeight: lineHeightVars['--leading-base'],
- fontWeight: fontWeightVars['--font-weight-semibold'],
- color: colorVars['--color-text-primary'],
- },
- menuItemDescription: {
- fontSize: textSizeVars['--text-sm'],
- lineHeight: lineHeightVars['--leading-snug'],
- fontWeight: fontWeightVars['--font-weight-normal'],
- color: colorVars['--color-text-secondary'],
- },
+
featured: {
flexGrow: 1,
flexShrink: 1,
@@ -196,38 +146,49 @@ const styles = stylex.create({
display: 'flex',
flexDirection: 'column',
},
- featuredImage: {
- width: '100%',
- height: 140,
- objectFit: 'cover',
- display: 'block',
- },
- featuredBody: {
+ // =========================================================================
+ // Drawer mode styles (composes navItemStyles.item as base)
+ // =========================================================================
+ drawerSection: {
display: 'flex',
flexDirection: 'column',
- gap: spacingVars['--spacing-2'],
- paddingBlock: spacingVars['--spacing-4'],
- paddingInline: spacingVars['--spacing-4'],
},
- featuredTitle: {
- fontSize: textSizeVars['--text-base'],
- lineHeight: lineHeightVars['--leading-base'],
- fontWeight: fontWeightVars['--font-weight-semibold'],
- color: colorVars['--color-text-primary'],
+ // Header button override — justifyContent and button resets only,
+ // base layout/colors come from navItemStyles.item
+ drawerHeader: {
+ justifyContent: 'space-between',
+ border: 'none',
+ background: 'none',
},
- featuredDescription: {
- fontSize: textSizeVars['--text-sm'],
- lineHeight: lineHeightVars['--leading-snug'],
- color: colorVars['--color-text-secondary'],
+ drawerChevron: {
+ display: 'inline-flex',
+ transitionProperty: 'transform',
+ transitionDuration: transitionVars['--transition-fast'],
},
- featuredLink: {
- fontSize: textSizeVars['--text-sm'],
- lineHeight: lineHeightVars['--leading-snug'],
- fontWeight: fontWeightVars['--font-weight-semibold'],
- color: colorVars['--color-accent-text'],
- textDecoration: 'none',
- cursor: 'pointer',
- marginBlockStart: spacingVars['--spacing-1'],
+ drawerChevronExpanded: {
+ transform: 'rotate(180deg)',
+ },
+ drawerItems: {
+ display: 'grid',
+ gridTemplateRows: '0fr',
+ transitionProperty: 'grid-template-rows',
+ transitionDuration: transitionVars['--transition-normal'],
+ },
+ drawerItemsExpanded: {
+ gridTemplateRows: '1fr',
+ },
+ drawerItemsInner: {
+ overflow: 'hidden',
+ minHeight: 0,
+ },
+
+ // Featured card in drawer — compact version
+ drawerFeatured: {
+ marginBlockStart: spacingVars['--spacing-2'],
+ marginInlineStart: spacingVars['--spacing-6'],
+ borderRadius: radiusVars['--radius-container'],
+ backgroundColor: colorVars['--color-deemphasized'],
+ overflow: 'hidden',
},
});
@@ -235,56 +196,23 @@ const styles = stylex.create({
// Types
// =============================================================================
-/**
- * An item in the mega menu.
- */
-export interface XDSTopNavMegaMenuItemData {
- /** Display title for the menu item. */
- title: string;
- /** Optional description text displayed below the title. */
- description?: string;
- /** Optional icon element displayed to the left. */
- icon?: ReactNode;
- /** URL to navigate to when clicked. */
- href?: string;
- /** Callback when item is clicked. */
- onClick?: () => void;
-}
-
-/**
- * Featured content for the right side of the mega menu.
- */
-export interface XDSTopNavMegaMenuFeatured {
- /** Image URL for the featured area. */
- image?: string;
- /** Alt text for the featured image. */
- imageAlt?: string;
- /** Featured content title. */
- title: string;
- /** Featured content description. */
- description?: string;
- /** Call-to-action link text. */
- linkText?: string;
- /** Call-to-action link URL. */
- linkHref?: string;
- /** Callback when CTA is clicked. */
- onLinkClick?: () => void;
- /** Custom content to render instead of the default layout. */
- children?: ReactNode;
-}
-
export interface XDSTopNavMegaMenuProps {
/** The visible label for the nav item trigger. */
label: string;
- /** Menu items to display in the mega menu panel. */
- items: XDSTopNavMegaMenuItemData[];
- /** Optional featured content on the right side. */
- featured?: XDSTopNavMegaMenuFeatured;
+ /**
+ * Menu items slot — typically one or more XDSTopNavMegaMenuItem components,
+ * but accepts any ReactNode for custom layouts.
+ */
+ items?: ReactNode;
+ /**
+ * Featured content slot — rendered in the right panel on desktop,
+ * and below the items in the mobile drawer.
+ */
+ featured?: ReactNode;
/** Delay before showing the menu on hover (ms). @default 150 */
delay?: number;
/** Delay before hiding the menu after mouse leaves (ms). @default 250 */
hideDelay?: number;
- /** Whether to use single-column layout for items. @default false */
/**
* Callback fired when the mega menu opens or closes.
* Useful for coordinating wrapper styles (e.g. hiding other shadows).
@@ -292,7 +220,6 @@ export interface XDSTopNavMegaMenuProps {
onOpenChange?: (isOpen: boolean) => void;
}
-// =============================================================================
// =============================================================================
// XDSTopNavMegaMenu
// =============================================================================
@@ -300,13 +227,14 @@ export interface XDSTopNavMegaMenuProps {
/**
* A navigation item that displays a full-width mega menu on hover.
*
- * Renders as a nav item trigger in XDSTopNav's startContent slot. On hover,
- * shows a full-width panel below the nav bar with menu items organized in
- * columns and an optional featured content area on the right.
+ * Uses a composed children API with sub-components:
+ * - `items` — ReactNode slot, typically XDSTopNavMegaMenuItem components
+ * - `featured` — ReactNode slot for the right-panel / drawer featured card
*
- * The panel is promoted to the top layer via the Popover API (through
- * useXDSLayer) and positioned via CSS anchor positioning relative to the
- * parent `<nav>` element (the XDSTopNav).
+ * Supports three render modes via XDSTopNavRenderContext:
+ * - `'default'`: desktop popover with hover/click trigger
+ * - `'mobile-bar'`: hidden (returns null)
+ * - `'drawer'`: inline collapsible matching TopNavMenu pattern
*
* @example
* ```
@@ -314,16 +242,28 @@ export interface XDSTopNavMegaMenuProps {
* 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',
- * }}
+ * items={
+ * <>
+ * <XDSTopNavMegaMenuItem
+ * title="Analytics"
+ * description="Track behavior"
+ * icon={<ChartIcon />}
+ * href="/analytics"
+ * />
+ * <XDSTopNavMegaMenuItem
+ * title="Messaging"
+ * description="Real-time comms"
+ * icon={<ChatIcon />}
+ * href="/messaging"
+ * />
+ * </>
+ * }
+ * featured={
+ * <>
+ * <strong>New: AI Features</strong>
+ * <p>Explore our latest AI-powered tools.</p>
+ * </>
+ * }
* />
* }
* />
@@ -336,6 +276,51 @@ export function XDSTopNavMegaMenu({
delay = 150,
hideDelay = 250,
onOpenChange,
+}: XDSTopNavMegaMenuProps) {
+ const renderMode = useXDSTopNavRenderMode();
+
+ // =========================================================================
+ // Mobile-bar mode — hidden
+ // =========================================================================
+ if (renderMode === 'mobile-bar') {
+ return null;
+ }
+
+ // =========================================================================
+ // Drawer mode — inline collapsible
+ // =========================================================================
+ if (renderMode === 'drawer') {
+ return <DrawerMegaMenu label={label} items={items} featured={featured} />;
+ }
+
+ // =========================================================================
+ // Default mode — desktop popover
+ // =========================================================================
+ return (
+ <DefaultMegaMenu
+ label={label}
+ items={items}
+ featured={featured}
+ delay={delay}
+ hideDelay={hideDelay}
+ onOpenChange={onOpenChange}
+ />
+ );
+}
+
+XDSTopNavMegaMenu.displayName = 'XDSTopNavMegaMenu';
+
+// =============================================================================
+// DefaultMegaMenu — desktop popover mode
+// =============================================================================
+
+function DefaultMegaMenu({
+ label,
+ items,
+ featured,
+ delay = 150,
+ hideDelay = 250,
+ onOpenChange,
}: XDSTopNavMegaMenuProps) {
const slot = useTopNavSlot();
const showTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -444,75 +429,17 @@ export function XDSTopNavMegaMenu({
{...stylex.props(styles.panelContainer)}>
<div {...stylex.props(styles.panelContent)}>
{/* Menu items section */}
- <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 {...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>
+ {items != null && (
+ <div {...stylex.props(styles.menuWrapper)}>
+ <XDSGrid columns={2} minChildWidth={200} gap={2}>
+ {items}
+ </XDSGrid>
+ </div>
+ )}
{/* Featured section */}
- {featured && (
- <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.linkText && (
- <a
- href={featured.linkHref}
- onClick={featured.onLinkClick}
- tabIndex={popover.isOpen ? 0 : -1}
- {...stylex.props(styles.featuredLink)}>
- {featured.linkText}
- </a>
- )}
- </div>
- </>
- )}
- </div>
+ {featured != null && (
+ <div {...stylex.props(styles.featured)}>{featured}</div>
)}
</div>
</div>,
@@ -526,4 +453,57 @@ export function XDSTopNavMegaMenu({
);
}
-XDSTopNavMegaMenu.displayName = 'XDSTopNavMegaMenu';
+// =============================================================================
+// DrawerMegaMenu — mobile drawer inline collapsible mode
+// =============================================================================
+
+function DrawerMegaMenu({
+ label,
+ items,
+ featured,
+}: Pick<XDSTopNavMegaMenuProps, 'label' | 'items' | 'featured'>) {
+ const [isExpanded, setIsExpanded] = useState(false);
+ const menuId = `mega-menu-${label.toLowerCase().replace(/\s+/g, '-')}`;
+
+ return (
+ <div {...stylex.props(styles.drawerSection)}>
+ {/* Header toggle — same pattern as TopNavMenu drawer */}
+ <button
+ type="button"
+ onClick={() => setIsExpanded(v => !v)}
+ aria-expanded={isExpanded}
+ aria-controls={`${menuId}-items`}
+ {...mergeProps(
+ xdsClassName('top-nav-mega-menu', {mode: 'drawer'}),
+ stylex.props(navItemStyles.item, styles.drawerHeader),
+ )}>
+ {label}
+ <span
+ {...stylex.props(
+ styles.drawerChevron,
+ isExpanded && styles.drawerChevronExpanded,
+ )}>
+ {getIcon('chevronDown')}
+ </span>
+ </button>
+
+ {/* Animated expand/collapse container */}
+ <div
+ id={`${menuId}-items`}
+ {...stylex.props(
+ styles.drawerItems,
+ isExpanded && styles.drawerItemsExpanded,
+ )}>
+ <div {...stylex.props(styles.drawerItemsInner)}>
+ {/* Items render themselves in drawer mode via XDSTopNavRenderContext */}
+ {items}
+
+ {/* Featured card */}
+ {featured != null && (
+ <div {...stylex.props(styles.drawerFeatured)}>{featured}</div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/core/src/TopNav/XDSTopNavMegaMenuFeaturedCard.tsx b/packages/core/src/TopNav/XDSTopNavMegaMenuFeaturedCard.tsx
new file mode 100644
index 0000000000..d16af1ba29
--- /dev/null
+++ b/packages/core/src/TopNav/XDSTopNavMegaMenuFeaturedCard.tsx
@@ -0,0 +1,149 @@
+/**
+ * @file XDSTopNavMegaMenuFeaturedCard.tsx
+ * @input Uses React, StyleX, theme tokens
+ * @output Exports XDSTopNavMegaMenuFeaturedCard component
+ * @position Standard featured card for the XDSTopNavMegaMenu featured slot.
+ *
+ * Provides a consistent appearance for promotional/featured content in mega menus.
+ * The `featured` slot on XDSTopNavMegaMenu is still open ReactNode — this component
+ * is the standard card, but consumers can pass anything.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/TopNav/TopNav.doc.mjs
+ * - /packages/core/src/TopNav/index.ts
+ */
+
+'use client';
+
+import {type ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ textSizeVars,
+ fontWeightVars,
+ lineHeightVars,
+} from '../theme/tokens.stylex';
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const styles = stylex.create({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ },
+ image: {
+ width: '100%',
+ height: 140,
+ objectFit: 'cover' as const,
+ display: 'block',
+ },
+ body: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-2'],
+ padding: spacingVars['--spacing-4'],
+ },
+ title: {
+ fontSize: textSizeVars['--text-base'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ lineHeight: lineHeightVars['--leading-base'],
+ color: colorVars['--color-text-primary'],
+ },
+ description: {
+ fontSize: textSizeVars['--text-sm'],
+ lineHeight: lineHeightVars['--leading-snug'],
+ color: colorVars['--color-text-secondary'],
+ },
+ link: {
+ fontSize: textSizeVars['--text-sm'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ lineHeight: lineHeightVars['--leading-snug'],
+ color: colorVars['--color-accent-text'],
+ textDecoration: 'none',
+ },
+});
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface XDSTopNavMegaMenuFeaturedCardProps {
+ /** Card title. */
+ title: string;
+ /** Description text below the title. */
+ description?: string;
+ /** Optional image URL displayed above the body. */
+ image?: string;
+ /** Alt text for the image. */
+ imageAlt?: string;
+ /** CTA link text. */
+ linkLabel?: string;
+ /** CTA link URL. */
+ linkHref?: string;
+ /** Custom content rendered below the standard body. */
+ children?: ReactNode;
+}
+
+// =============================================================================
+// Component
+// =============================================================================
+
+/**
+ * Standard featured card for the XDSTopNavMegaMenu `featured` slot.
+ *
+ * Provides a consistent card with optional image, title, description,
+ * and CTA link. For fully custom content, pass any ReactNode directly
+ * to the `featured` slot instead.
+ *
+ * @example
+ * ```
+ * <XDSTopNavMegaMenu
+ * label="Products"
+ * items={...}
+ * featured={
+ * <XDSTopNavMegaMenuFeaturedCard
+ * title="What's new in v4.0"
+ * description="AI-powered analytics and real-time collaboration."
+ * image="https://example.com/promo.jpg"
+ * imageAlt="Team collaboration"
+ * linkLabel="Read the announcement"
+ * linkHref="/blog/v4"
+ * />
+ * }
+ * />
+ * ```
+ */
+export function XDSTopNavMegaMenuFeaturedCard({
+ title,
+ description,
+ image,
+ imageAlt,
+ linkLabel,
+ linkHref,
+ children,
+}: XDSTopNavMegaMenuFeaturedCardProps) {
+ return (
+ <div {...stylex.props(styles.root)}>
+ {image && (
+ <img src={image} alt={imageAlt ?? ''} {...stylex.props(styles.image)} />
+ )}
+ <div {...stylex.props(styles.body)}>
+ <span {...stylex.props(styles.title)}>{title}</span>
+ {description && (
+ <span {...stylex.props(styles.description)}>{description}</span>
+ )}
+ {linkLabel && linkHref && (
+ <a href={linkHref} {...stylex.props(styles.link)}>
+ {linkLabel} →
+ </a>
+ )}
+ {children}
+ </div>
+ </div>
+ );
+}
+
+XDSTopNavMegaMenuFeaturedCard.displayName = 'XDSTopNavMegaMenuFeaturedCard';
diff --git a/packages/core/src/TopNav/XDSTopNavMegaMenuItem.tsx b/packages/core/src/TopNav/XDSTopNavMegaMenuItem.tsx
new file mode 100644
index 0000000000..3e728e1590
--- /dev/null
+++ b/packages/core/src/TopNav/XDSTopNavMegaMenuItem.tsx
@@ -0,0 +1,246 @@
+/**
+ * @file XDSTopNavMegaMenuItem.tsx
+ * @input Uses React, StyleX, theme tokens, navItemStyles, XDSTopNavRenderContext
+ * @output Exports XDSTopNavMegaMenuItem component and props
+ * @position Individual item inside an XDSTopNavMegaMenu — renders itself in both
+ * desktop (popover) and mobile drawer modes.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/TopNav/TopNav.doc.mjs
+ * - /packages/core/src/TopNav/index.ts
+ */
+
+'use client';
+
+import {type ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ transitionVars,
+ textSizeVars,
+ fontWeightVars,
+ lineHeightVars,
+} from '../theme/tokens.stylex';
+import {navItemStyles} from '../NavItem/navItemStyles.stylex';
+import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
+import type {XDSLinkComponentType} from '../Link/types';
+import {useXDSTopNavRenderMode} from './XDSTopNavRenderContext';
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const styles = stylex.create({
+ // Desktop popover item
+ desktop: {
+ display: 'flex',
+ alignItems: 'flex-start',
+ gap: spacingVars['--spacing-3'],
+ paddingBlock: spacingVars['--spacing-3'],
+ paddingInline: spacingVars['--spacing-3'],
+ borderRadius: radiusVars['--radius-element'],
+ textDecoration: 'none',
+ cursor: 'pointer',
+ transitionProperty: 'background-color',
+ transitionDuration: transitionVars['--transition-fast'],
+ backgroundColor: {
+ default: 'transparent',
+ ':hover': {
+ '@media (hover: hover)': colorVars['--color-hover-overlay'],
+ },
+ ':active': colorVars['--color-pressed-overlay'],
+ },
+ border: 'none',
+ outline: {
+ default: null,
+ ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,
+ },
+ outlineOffset: {
+ default: '0',
+ ':focus-visible': '2px',
+ },
+ color: 'inherit',
+ fontFamily: 'inherit',
+ textAlign: 'start',
+ boxSizing: 'border-box',
+ width: '100%',
+ },
+ desktopIcon: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 40,
+ height: 40,
+ borderRadius: radiusVars['--radius-element'],
+ backgroundColor: colorVars['--color-deemphasized'],
+ flexShrink: 0,
+ color: colorVars['--color-icon-secondary'],
+ },
+ desktopContent: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-1'],
+ minWidth: 0,
+ },
+ desktopTitle: {
+ fontSize: textSizeVars['--text-base'],
+ lineHeight: lineHeightVars['--leading-base'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ color: colorVars['--color-text-primary'],
+ },
+ desktopDescription: {
+ fontSize: textSizeVars['--text-sm'],
+ lineHeight: lineHeightVars['--leading-snug'],
+ fontWeight: fontWeightVars['--font-weight-normal'],
+ color: colorVars['--color-text-secondary'],
+ },
+ // Drawer item overrides (base from navItemStyles.item)
+ drawerItem: {
+ paddingInlineStart: spacingVars['--spacing-6'],
+ alignItems: 'flex-start',
+ textDecoration: 'none',
+ },
+ drawerItemIcon: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 32,
+ height: 32,
+ borderRadius: radiusVars['--radius-element'],
+ backgroundColor: colorVars['--color-deemphasized'],
+ flexShrink: 0,
+ color: colorVars['--color-icon-secondary'],
+ marginBlockStart: spacingVars['--spacing-0-5'],
+ },
+ drawerItemContent: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-0-5'],
+ minWidth: 0,
+ },
+ drawerItemDescription: {
+ fontSize: textSizeVars['--text-sm'],
+ lineHeight: lineHeightVars['--leading-snug'],
+ color: colorVars['--color-text-secondary'],
+ fontWeight: fontWeightVars['--font-weight-normal'],
+ },
+});
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface XDSTopNavMegaMenuItemProps {
+ /** Display title for the menu item. */
+ title: string;
+ /** Optional description text displayed below the title. */
+ description?: string;
+ /** Optional icon element displayed to the left. */
+ icon?: ReactNode;
+ /** URL to navigate to when clicked. */
+ href?: string;
+ /** Callback when item is clicked. */
+ onClick?: () => void;
+ /**
+ * Custom component to render instead of `<a>` for link items.
+ * Overrides the provider-level default set by XDSLinkProvider.
+ */
+ as?: XDSLinkComponentType;
+ /**
+ * tabIndex — set by parent when inside a closed popover.
+ * @internal
+ */
+ tabIndex?: number;
+}
+
+// =============================================================================
+// Component
+// =============================================================================
+
+/**
+ * An individual item inside an XDSTopNavMegaMenu.
+ *
+ * Renders itself in both desktop (popover grid) and mobile drawer modes
+ * using XDSTopNavRenderContext to switch appearance.
+ *
+ * @example
+ * ```
+ * <XDSTopNavMegaMenu
+ * label="Products"
+ * items={
+ * <>
+ * <XDSTopNavMegaMenuItem
+ * title="Analytics"
+ * description="Track and analyze user behavior"
+ * icon={<ChartIcon />}
+ * href="/analytics"
+ * />
+ * <XDSTopNavMegaMenuItem title="Reports" href="/reports" />
+ * </>
+ * }
+ * />
+ * ```
+ */
+export function XDSTopNavMegaMenuItem({
+ title,
+ description,
+ icon,
+ href,
+ onClick,
+ as,
+ tabIndex,
+}: XDSTopNavMegaMenuItemProps) {
+ const renderMode = useXDSTopNavRenderMode();
+ const LinkComponent = useXDSLinkComponent(as);
+
+ // =========================================================================
+ // Drawer mode — matches SideNavItem / TopNavMenu drawer appearance
+ // =========================================================================
+ if (renderMode === 'drawer') {
+ const Element = href ? LinkComponent : 'button';
+ const elementProps = Element === 'button' ? {type: 'button' as const} : {};
+ return (
+ <Element
+ href={href}
+ onClick={onClick}
+ {...elementProps}
+ {...stylex.props(navItemStyles.item, styles.drawerItem)}>
+ {icon && <div {...stylex.props(styles.drawerItemIcon)}>{icon}</div>}
+ <div {...stylex.props(styles.drawerItemContent)}>
+ {title}
+ {description && (
+ <span {...stylex.props(styles.drawerItemDescription)}>
+ {description}
+ </span>
+ )}
+ </div>
+ </Element>
+ );
+ }
+
+ // =========================================================================
+ // Default mode — desktop popover item with large icon + description
+ // =========================================================================
+ const Element = href ? LinkComponent : 'div';
+ return (
+ <Element
+ href={href}
+ onClick={onClick}
+ tabIndex={tabIndex}
+ {...stylex.props(styles.desktop)}>
+ {icon && <div {...stylex.props(styles.desktopIcon)}>{icon}</div>}
+ <div {...stylex.props(styles.desktopContent)}>
+ <span {...stylex.props(styles.desktopTitle)}>{title}</span>
+ {description && (
+ <span {...stylex.props(styles.desktopDescription)}>
+ {description}
+ </span>
+ )}
+ </div>
+ </Element>
+ );
+}
+
+XDSTopNavMegaMenuItem.displayName = 'XDSTopNavMegaMenuItem';
diff --git a/packages/core/src/TopNav/index.ts b/packages/core/src/TopNav/index.ts
index 6ef476f07c..9279d48101 100644
--- a/packages/core/src/TopNav/index.ts
+++ b/packages/core/src/TopNav/index.ts
@@ -20,11 +20,13 @@ export {XDSTopNavMenu} from './XDSTopNavMenu';
export type {XDSTopNavMenuProps, XDSTopNavMenuItemData} from './XDSTopNavMenu';
export {XDSTopNavMegaMenu} from './XDSTopNavMegaMenu';
-export type {
- XDSTopNavMegaMenuProps,
- XDSTopNavMegaMenuItemData,
- XDSTopNavMegaMenuFeatured,
-} from './XDSTopNavMegaMenu';
+export type {XDSTopNavMegaMenuProps} from './XDSTopNavMegaMenu';
+
+export {XDSTopNavMegaMenuItem} from './XDSTopNavMegaMenuItem';
+export type {XDSTopNavMegaMenuItemProps} from './XDSTopNavMegaMenuItem';
+
+export {XDSTopNavMegaMenuFeaturedCard} from './XDSTopNavMegaMenuFeaturedCard';
+export type {XDSTopNavMegaMenuFeaturedCardProps} from './XDSTopNavMegaMenuFeaturedCard';
export {
XDSTopNavRenderContext,