An open source design system that's fully customizable and agent ready
TypeScript
feat(AppShell): responsive mobile nav API (#565) (#644)
Cindy Zhangaf1076e9a869
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsxindex 2478f62c3e..473b3e18ef 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx+++ b/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx@@ -18,7 +18,7 @@ import {XDSTopNavMenu,XDSTopNavMegaMenu,} from '@xds/core/TopNav';-import {XDSMobileNav} from '@xds/core/MobileNav';+import {XDSMobileNav, XDSMobileNavToggle} from '@xds/core/MobileNav';import {XDSVStack, XDSHStack} from '@xds/core/Layout';import {XDSText, XDSHeading} from '@xds/core/Text';import {XDSSwitch} from '@xds/core/Switch';@@ -115,7 +115,7 @@ interface ShellConfig {showNestedItems: boolean;isCollapsible: boolean;collapseToggleLocation: 'sidenav' | 'topnav';- mobileNavMode: 'auto' | 'custom' | 'none';+ mobileNavMode: 'auto' | 'customContent' | 'customToggle' | 'disabled';mobileNavSide: 'start' | 'end';topNavAlignment: 'start' | 'center' | 'end';topNavStyle: 'items' | 'menus' | 'mega';@@ -270,21 +270,6 @@ function ConfigPanel({]}/>)}- <SelectorRow- label="Breakpoint"- value={config.sideNavBreakpoint}- onChange={v =>- onChange({- sideNavBreakpoint: v as ShellConfig['sideNavBreakpoint'],- })- }- options={[- {value: 'sm', label: 'SM'},- {value: 'md', label: 'MD'},- {value: 'lg', label: 'LG'},- {value: 'none', label: 'None'},- ]}- /></XDSVStack><XDSDivider />@@ -345,11 +330,29 @@ function ConfigPanel({}options={[{value: 'auto', label: 'Auto'},- {value: 'custom', label: 'Custom'},- {value: 'none', label: 'None'},+ {value: 'customContent', label: 'Custom Content'},+ {value: 'customToggle', label: 'Custom Toggle'},+ {value: 'disabled', label: 'Disabled'},]}/>- {config.mobileNavMode === 'custom' && (+ {config.mobileNavMode !== 'disabled' && (+ <SelectorRow+ label="Breakpoint"+ value={config.sideNavBreakpoint}+ onChange={v =>+ onChange({+ sideNavBreakpoint: v as ShellConfig['sideNavBreakpoint'],+ })+ }+ options={[+ {value: 'sm', label: 'SM'},+ {value: 'md', label: 'MD'},+ {value: 'lg', label: 'LG'},+ {value: 'none', label: 'None'},+ ]}+ />+ )}+ {config.mobileNavMode === 'customContent' && (<SelectorRowlabel="Side"value={config.mobileNavSide}@@ -733,11 +736,14 @@ const styles = stylex.create({padding4: {padding: 16,},+ customSearchBar: {+ paddingInline: 8,+ paddingBlock: 4,+ },});export default function ShellLabPage() {const [config, setConfig] = useState<ShellConfig>(DEFAULT_CONFIG);- const [isMobileNavOpen, setIsMobileNavOpen] = useState(false);const [showConfig, setShowConfig] = useState(true);const [externalCollapsed, setExternalCollapsed] = useState(false);@@ -745,27 +751,61 @@ export default function ShellLabPage() {setConfig(prev => ({...prev, ...update}));}, []);- const mobileNav =- config.mobileNavMode === 'custom' ? (- <XDSMobileNav- isOpen={isMobileNavOpen}- onOpenChange={setIsMobileNavOpen}- title="Navigation"- side={config.mobileNavSide}>- <XDSSideNavSection title="Navigation">- <XDSSideNavItem- label="Dashboard"- isSelected- href="#"- icon={DashboardIcon}- />- <XDSSideNavItem label="Projects" href="#" icon={ProjectsIcon} />- <XDSSideNavItem label="Messages" href="#" icon={MessagesIcon} />- </XDSSideNavSection>- </XDSMobileNav>- ) : config.mobileNavMode === 'none' ? (- <></>- ) : undefined;+ // Build the mobileNav prop based on config+ const mobileNav:+ | false+ | {hasToggle?: boolean; content?: React.ReactNode}+ | React.ReactNode+ | undefined =+ config.mobileNavMode === 'disabled'+ ? false+ : config.mobileNavMode === 'customContent'+ ? {+ content: (+ <XDSMobileNav title="Custom Nav" side={config.mobileNavSide}>+ <XDSVStack gap={2} xstyle={styles.customSearchBar}>+ <input+ type="search"+ placeholder="Search navigation..."+ style={{+ width: '100%',+ padding: '8px 12px',+ borderRadius: 8,+ border: '1px solid var(--color-divider)',+ background: 'var(--color-wash)',+ fontSize: 14,+ outline: 'none',+ }}+ />+ </XDSVStack>+ <XDSSideNavSection title="Quick Links">+ <XDSSideNavItem label="Docs" href="#" />+ <XDSSideNavItem label="Help Center" href="#" />+ </XDSSideNavSection>+ <XDSSideNavSection title="Navigation">+ <XDSSideNavItem+ label="Dashboard"+ isSelected+ href="#"+ icon={DashboardIcon}+ />+ <XDSSideNavItem+ label="Projects"+ href="#"+ icon={ProjectsIcon}+ />+ <XDSSideNavItem+ label="Messages"+ href="#"+ icon={MessagesIcon}+ />+ </XDSSideNavSection>+ </XDSMobileNav>+ ),+ }+ : config.mobileNavMode === 'customToggle'+ ? {hasToggle: false} // auto drawer content, but no auto toggle+ : undefined; // auto with toggle — full default behaviorreturn (<>@@ -810,7 +850,12 @@ export default function ShellLabPage() {}><XDSVStack gap={6} xstyle={styles.content}><XDSVStack gap={2}>- <XDSHeading level={1}>Shell Lab</XDSHeading>+ <XDSHStack gap={3} vAlign="center">+ {config.mobileNavMode === 'customToggle' && (+ <XDSMobileNavToggle label="Open navigation" />+ )}+ <XDSHeading level={1}>Shell Lab</XDSHeading>+ </XDSHStack><XDSText type="body" color="secondary">Use the configuration panel to experiment with different shell andnavigation setups. Resize the browser to test responsive behaviordiff --git a/packages/core/src/AppShell/XDSAppShell.test.tsx b/packages/core/src/AppShell/XDSAppShell.test.tsxindex 59b92325ab..0dbc7047f9 100644--- a/packages/core/src/AppShell/XDSAppShell.test.tsx+++ b/packages/core/src/AppShell/XDSAppShell.test.tsx@@ -273,7 +273,7 @@ describe('XDSAppShell', () => {);// Should show default mobile nav (XDSMobileNav wrapping sideNav)- expect(screen.getByTestId('sidenav-mobile')).toBeInTheDocument();+ expect(screen.getByRole('dialog', {hidden: true})).toBeInTheDocument();// Should show nav content inside the mobile navexpect(screen.getByText('Nav')).toBeInTheDocument();});@@ -289,7 +289,7 @@ describe('XDSAppShell', () => {);// Default mobile nav should be rendered when below breakpoint- expect(screen.getByTestId('sidenav-mobile')).toBeInTheDocument();+ expect(screen.getByRole('dialog', {hidden: true})).toBeInTheDocument();});// ===========================================================================@@ -473,8 +473,10 @@ describe('XDSAppShell', () => {<div>Content</div></XDSAppShell>,);- // Default mobile nav should NOT appear- expect(screen.queryByTestId('sidenav-mobile')).not.toBeInTheDocument();+ // Default auto-generated mobile nav should NOT appear — only the explicit one+ // (The explicit mobileNav is rendered as a ReactNode, so only one dialog exists)+ const dialogs = screen.getAllByRole('dialog', {hidden: true});+ expect(dialogs).toHaveLength(1);// Explicit mobileNav slot should be renderedexpect(screen.getByTestId('appshell-mobile-nav')).toBeInTheDocument();});diff --git a/packages/core/src/AppShell/XDSAppShell.tsx b/packages/core/src/AppShell/XDSAppShell.tsxindex a9adca3e47..0612cbd1c5 100644--- a/packages/core/src/AppShell/XDSAppShell.tsx+++ b/packages/core/src/AppShell/XDSAppShell.tsx@@ -15,7 +15,15 @@'use client';-import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react';+import {+ isValidElement,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type ReactNode,+} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {@@ -29,6 +37,10 @@ import {XDSLayoutHeader} from '../Layout/XDSLayoutHeader';import {XDSLayoutPanel} from '../Layout/XDSLayoutPanel';import {XDSLayoutContent} from '../Layout/XDSLayoutContent';import {XDSMobileNav} from '../MobileNav/XDSMobileNav';+import {XDSMobileNavToggle} from '../MobileNav/XDSMobileNavToggle';+import {XDSSideNavRenderContext} from '../SideNav/XDSSideNavRenderContext';+import {XDSAppShellMobileContext} from './XDSAppShellMobileContext';+import type {XDSAppShellMobileContextValue} from './XDSAppShellMobileContext';import type {SpacingStep} from '../utils/types';import {xdsClassName, mergeProps} from '../utils';@@ -70,6 +82,37 @@ export type XDSAppShellBreakpoint = 'sm' | 'md' | 'lg' | 'none';*/export type XDSAppShellVariant = 'wash' | 'surface' | 'section' | 'elevated';+/**+ * Configuration object for mobile navigation behavior.+ * Used when you need to customize the auto mobile nav without replacing it entirely.+ */+export interface XDSMobileNavConfig {+ /**+ * Whether to auto-render the hamburger toggle.+ * When false, use `<XDSMobileNavToggle />` to place it yourself.+ * @default true+ */+ hasToggle?: boolean;++ /**+ * Controlled open state. When provided, AppShell doesn't manage+ * mobile nav state internally.+ */+ isOpen?: boolean;++ /**+ * Callback when the mobile nav drawer open state changes.+ */+ onOpenChange?: (isOpen: boolean) => void;++ /**+ * Custom drawer content. Replaces the auto-generated drawer.+ * Can be an `<XDSMobileNav>` for full drawer config (title, width, side)+ * or raw children.+ */+ content?: ReactNode;+}+export interface XDSAppShellProps {/** Ref forwarded to the root element */ref?: React.Ref<HTMLDivElement>;@@ -118,16 +161,37 @@ export interface XDSAppShellProps {height?: 'fill' | 'auto';/**- * Mobile navigation — typically an XDSMobileNav.+ * Mobile navigation configuration.+ *+ * Accepts three shapes:+ * - **`false`** — Disable mobile nav entirely.+ * - **`MobileNavConfig` object** — Configure auto behavior (toggle, controlled state, custom content).+ * - **`ReactNode`** — Full escape hatch: provide your own `<XDSMobileNav>` (you own everything).*- * When provided, replaces the default mobile drawer that AppShell renders- * for sideNav below the breakpoint. The consumer owns the XDSMobileNav- * element and its open/close state, just like topNav and sideNav.+ * When omitted, AppShell automatically generates a mobile drawer with+ * sideNav content (and TopNav items in the future) below the breakpoint.+ *+ * @example+ * ```+ * // Auto (default) — no prop needed+ * <XDSAppShell topNav={...} sideNav={...}>*- * When not provided, AppShell automatically wraps sideNav in an- * XDSMobileNav for the mobile breakpoint.+ * // Controlled state, auto content+ * <XDSAppShell mobileNav={{ isOpen, onOpenChange }}>+ *+ * // Custom toggle placement+ * <XDSAppShell mobileNav={{ hasToggle: false }}>+ * <XDSMobileNavToggle />+ * </XDSAppShell>+ *+ * // Full custom drawer+ * <XDSAppShell mobileNav={<XDSMobileNav title="Menu">...</XDSMobileNav>}>+ *+ * // Disable+ * <XDSAppShell mobileNav={false}>+ * ```*/- mobileNav?: ReactNode;+ mobileNav?: false | XDSMobileNavConfig | ReactNode;/*** Side navigation — typically an XDSSideNav.@@ -290,6 +354,12 @@ const styles = stylex.create({hidden: {display: 'none',},+ autoMobileTopBar: {+ display: 'flex',+ alignItems: 'center',+ height: 48,+ paddingInline: 8,+ },// Sticky header for auto height modeheaderSticky: {position: 'sticky',@@ -360,11 +430,47 @@ export function XDSAppShell({ref,}: XDSAppShellProps) {// =========================================================================- // SideNav collapse state (controlled + uncontrolled)+ // Parse mobileNav prop — normalize to config, custom element, or disabled+ // =========================================================================+ const mobileNavDisabled = mobileNav === false;+ const mobileNavConfig: XDSMobileNavConfig | null =+ mobileNav != null &&+ mobileNav !== false &&+ typeof mobileNav === 'object' &&+ !isValidElement(mobileNav)+ ? (mobileNav as XDSMobileNavConfig)+ : null;+ // ReactNode shorthand — user provides <XDSMobileNav> directly as the prop+ const mobileNavReactNode: ReactNode | null =+ mobileNav != null &&+ mobileNav !== false &&+ (isValidElement(mobileNav) || typeof mobileNav === 'string')+ ? mobileNav+ : null;+ // Custom content from config object+ const mobileNavConfigContent: ReactNode | null =+ mobileNavConfig?.content ?? null;+ const mobileNavHasToggle = mobileNavConfig?.hasToggle !== false;+ const mobileNavIsControlled = mobileNavConfig?.isOpen !== undefined;++ // =========================================================================+ // Mobile nav open state (controlled + uncontrolled)// =========================================================================- // Track whether we're below the breakpointconst [isBelowBreakpoint, setIsBelowBreakpoint] = useState(false);- const [isMobileNavOpen, setIsMobileNavOpen] = useState(false);+ const [uncontrolledMobileOpen, setUncontrolledMobileOpen] = useState(false);+ const isMobileNavOpen = mobileNavIsControlled+ ? mobileNavConfig!.isOpen!+ : uncontrolledMobileOpen;++ const setMobileNavOpen = useCallback(+ (open: boolean) => {+ if (!mobileNavIsControlled) {+ setUncontrolledMobileOpen(open);+ }+ mobileNavConfig?.onOpenChange?.(open);+ },+ [mobileNavIsControlled, mobileNavConfig],+ );const isFill = height === 'fill';const isAuto = height === 'auto';@@ -373,7 +479,8 @@ export function XDSAppShell({const hasBanner = banner != null;const hasTopNav = topNav != null;const hasSideNav = sideNav != null;- const hasMobileNav = mobileNav != null;+ const hasNavContent = hasSideNav || hasTopNav;+ const mobileNavEnabled = !mobileNavDisabled && hasNavContent;const navHasDividers = variant === 'section';const isElevated = variant === 'elevated';const navAreaStyle =@@ -462,10 +569,34 @@ export function XDSAppShell({// Determine if sideNav should show as overlay (mobile) or inline// =========================================================================const showSideNavInline = hasSideNav && !isBelowBreakpoint;- // Default mobile nav: when no explicit mobileNav is provided, AppShell- // internally renders an XDSMobileNav wrapping the sideNav content.- // This shares the same <dialog>-based behavior as explicit mobileNav.- const useDefaultMobileNav = hasSideNav && !hasMobileNav && isBelowBreakpoint;+ // Three mobile nav rendering modes:+ // 1. ReactNode shorthand — render the user's element as-is (they own the drawer)+ const shouldRenderMobileNavReactNode = mobileNavReactNode != null;+ // 2. Config with custom content — render inside AppShell-managed drawer+ const shouldRenderConfigContent =+ mobileNavEnabled && mobileNavConfigContent != null && isBelowBreakpoint;+ // 3. Auto — wrap sideNav content in a managed drawer+ const shouldRenderAutoMobileNav =+ mobileNavEnabled &&+ !mobileNavReactNode &&+ !mobileNavConfigContent &&+ isBelowBreakpoint &&+ hasSideNav;++ // =========================================================================+ // Mobile context — shared with XDSMobileNavToggle and future TopNav mobile+ // =========================================================================+ const mobileContextValue = useMemo<XDSAppShellMobileContextValue>(+ () => ({+ isMobile: isBelowBreakpoint,+ isMobileNavOpen,+ toggleMobileNav: () => setMobileNavOpen(!isMobileNavOpen),+ openMobileNav: () => setMobileNavOpen(true),+ closeMobileNav: () => setMobileNavOpen(false),+ isMobileNavEnabled: mobileNavEnabled,+ }),+ [isBelowBreakpoint, isMobileNavOpen, setMobileNavOpen, mobileNavEnabled],+ );// =========================================================================// Build header content (topNav + banner)@@ -557,55 +688,89 @@ export function XDSAppShell({// TODO: Include root providers (ThemeProvider, ProseProvider, LayerProvider)// at the app level once they're available for wrapping.// =========================================================================- return (- <div- ref={setShellRef}- data-testid={dataTestId}- {...mergeProps(- xdsClassName('app-shell', {height, variant}),- stylex.props(- styles.root,- variant === 'wash'- ? styles.variantWash- : variant === 'surface'- ? styles.variantSurface- : variant === 'section'- ? styles.variantSection- : styles.variantElevated,- isFill ? styles.rootFill : styles.rootAuto,- xstyle,- ),- className,- style,- )}>- {/* Skip-to-content link */}- <a- href={`#${MAIN_CONTENT_ID}`}- {...stylex.props(styles.skipLink)}- data-testid="skip-to-content">- Skip to content- </a>-- <XDSLayout- height={height}+ // =========================================================================+ // Build auto mobile nav hamburger for TopNav+ // Injected into the headerContent when mobileNav is enabled and hasToggle+ // =========================================================================+ const shouldShowAutoToggle =+ mobileNavEnabled && mobileNavHasToggle && isBelowBreakpoint;++ // For sidenav-only layouts with no TopNav, render the sideNav in topbar+ // mode — it shows heading + footer icons horizontally, with the hamburger+ const autoMobileTopBar =+ shouldShowAutoToggle && !hasTopNav && hasSideNav ? (+ <XDSLayoutHeaderpadding={0}- header={headerContent}- start={sideNavContent}- content={mainContent}- />-- {/* Mobile nav — either explicit mobileNav or default wrapping sideNav */}- {mobileNav}- {useDefaultMobileNav && (- <XDSMobileNav- isOpen={isMobileNavOpen}- onOpenChange={open => setIsMobileNavOpen(open)}- width={sideNavWidth}- data-testid="sidenav-mobile">- {sideNav}- </XDSMobileNav>- )}- </div>+ hasDivider={navHasDividers}+ xstyle={navAreaStyle}>+ <div+ {...stylex.props(styles.autoMobileTopBar)}+ role="navigation"+ aria-label="Mobile navigation">+ <XDSSideNavRenderContext value="topbar">+ {sideNav}+ </XDSSideNavRenderContext>+ <XDSMobileNavToggle />+ </div>+ </XDSLayoutHeader>+ ) : undefined;++ return (+ <XDSAppShellMobileContext.Provider value={mobileContextValue}>+ <div+ ref={setShellRef}+ data-testid={dataTestId}+ {...mergeProps(+ xdsClassName('app-shell', {height, variant}),+ stylex.props(+ styles.root,+ variant === 'wash'+ ? styles.variantWash+ : variant === 'surface'+ ? styles.variantSurface+ : variant === 'section'+ ? styles.variantSection+ : styles.variantElevated,+ isFill ? styles.rootFill : styles.rootAuto,+ xstyle,+ ),+ className,+ style,+ )}>+ {/* Skip-to-content link */}+ <a+ href={`#${MAIN_CONTENT_ID}`}+ {...stylex.props(styles.skipLink)}+ data-testid="skip-to-content">+ Skip to content+ </a>++ <XDSLayout+ height={height}+ padding={0}+ header={+ <>+ {headerContent}+ {autoMobileTopBar}+ </>+ }+ start={sideNavContent}+ content={mainContent}+ />++ {/* Mobile nav — three modes:+ 1. ReactNode shorthand: render user's element as-is+ 2. Config content: render inside AppShell-managed drawer+ 3. Auto: wrap sideNav in a managed drawer */}+ {shouldRenderMobileNavReactNode && mobileNavReactNode}+ {shouldRenderConfigContent && mobileNavConfigContent}+ {shouldRenderAutoMobileNav && (+ <XDSSideNavRenderContext value="drawer">+ {sideNav}+ </XDSSideNavRenderContext>+ )}+ </div>+ </XDSAppShellMobileContext.Provider>);}diff --git a/packages/core/src/AppShell/XDSAppShellMobileContext.tsx b/packages/core/src/AppShell/XDSAppShellMobileContext.tsxnew file mode 100644index 0000000000..96d2f3c23f--- /dev/null+++ b/packages/core/src/AppShell/XDSAppShellMobileContext.tsx@@ -0,0 +1,48 @@+/**+ * @file XDSAppShellMobileContext.tsx+ * @input Uses React createContext, useContext+ * @output Exports XDSAppShellMobileContext, useXDSAppShellMobile+ * @position Internal context for mobile nav state; consumed by XDSMobileNavToggle, XDSTopNav (future)+ *+ * Provides mobile navigation state to any component in the AppShell tree.+ * Used by XDSMobileNavToggle to open/close the drawer and by TopNav (future)+ * to adapt rendering based on mobile context.+ */++'use client';++import {createContext, useContext} from 'react';++export interface XDSAppShellMobileContextValue {+ /** Whether the viewport is below the mobile breakpoint */+ isMobile: boolean;+ /** Whether the mobile nav drawer is currently open */+ isMobileNavOpen: boolean;+ /** Toggle the mobile nav drawer open/closed */+ toggleMobileNav: () => void;+ /** Open the mobile nav drawer */+ openMobileNav: () => void;+ /** Close the mobile nav drawer */+ closeMobileNav: () => void;+ /** Whether mobile nav is enabled at all */+ isMobileNavEnabled: boolean;+}++const defaultValue: XDSAppShellMobileContextValue = {+ isMobile: false,+ isMobileNavOpen: false,+ toggleMobileNav: () => {},+ openMobileNav: () => {},+ closeMobileNav: () => {},+ isMobileNavEnabled: false,+};++export const XDSAppShellMobileContext =+ createContext<XDSAppShellMobileContextValue>(defaultValue);++/**+ * Hook to access mobile nav state from anywhere in the AppShell tree.+ */+export function useXDSAppShellMobile(): XDSAppShellMobileContextValue {+ return useContext(XDSAppShellMobileContext);+}diff --git a/packages/core/src/AppShell/index.ts b/packages/core/src/AppShell/index.tsindex c43da02c7d..0fa79e2205 100644--- a/packages/core/src/AppShell/index.ts+++ b/packages/core/src/AppShell/index.ts@@ -12,4 +12,10 @@ export type {XDSAppShellProps,XDSAppShellBreakpoint,XDSAppShellVariant,+ XDSMobileNavConfig,} from './XDSAppShell';+export {+ useXDSAppShellMobile,+ XDSAppShellMobileContext,+} from './XDSAppShellMobileContext';+export type {XDSAppShellMobileContextValue} from './XDSAppShellMobileContext';diff --git a/packages/core/src/MobileNav/XDSMobileNav.tsx b/packages/core/src/MobileNav/XDSMobileNav.tsxindex 2b9a4110e4..052dd21d1e 100644--- a/packages/core/src/MobileNav/XDSMobileNav.tsx+++ b/packages/core/src/MobileNav/XDSMobileNav.tsx@@ -29,6 +29,7 @@ import {colorVars, spacingVars} from '../theme/tokens.stylex';import {XDSButton} from '../Button';import {XDSIcon} from '../Icon';import {XDSHeading} from '../Text/XDSHeading';+import {useXDSAppShellMobile} from '../AppShell/XDSAppShellMobileContext';import {xdsClassName, mergeProps} from '../utils';import {XDSBaseProps} from '../XDSBaseProps';@@ -126,8 +127,8 @@ const styles = stylex.create({display: 'flex',alignItems: 'center',justifyContent: 'space-between',+ height: 48,paddingInline: spacingVars['--spacing-2'],- paddingBlock: spacingVars['--spacing-2'],flexShrink: 0,borderBlockEndWidth: 1,borderBlockEndStyle: 'solid',@@ -140,6 +141,7 @@ const styles = stylex.create({flex: 1,overflowY: 'auto',overflowX: 'hidden',+ overscrollBehavior: 'contain',paddingInline: spacingVars['--spacing-2'],paddingBlock: spacingVars['--spacing-1'],},@@ -147,8 +149,8 @@ const styles = stylex.create({const dynamicStyles = stylex.create({width: (w: number) => ({- width: `${w}px`,- maxWidth: '85vw',+ width: '100vw',+ maxWidth: `${w}px`,}),});@@ -161,15 +163,19 @@ export interface XDSMobileNavProps extends Omit<XDSBaseProps, 'title'> {ref?: React.Ref<HTMLDialogElement>;/*** Whether the drawer is open.+ * Inside XDSAppShell, this is managed automatically via context.+ * Outside XDSAppShell, provide this prop to control the drawer yourself.*/- isOpen: boolean;+ isOpen?: boolean;/*** Callback fired when the drawer visibility changes.* Called with `false` when the drawer should close* (backdrop click, escape, close button).+ * Inside XDSAppShell, this is managed automatically via context.+ * Outside XDSAppShell, provide this prop to control the drawer yourself.*/- onOpenChange: (isOpen: boolean) => void;+ onOpenChange?: (isOpen: boolean) => void;/*** Drawer content — typically XDSSideNavSection/XDSSideNavItem, or any ReactNode.@@ -178,21 +184,33 @@ export interface XDSMobileNavProps extends Omit<XDSBaseProps, 'title'> {/*** Optional title shown at the top of the drawer.+ * For simple text headers. Use `header` for custom content.*/title?: string;+ /**+ * Custom header content rendered in the header area next to the close button.+ * Replaces `title` when provided. Use for logos, SideNavHeading, search bars, etc.+ */+ header?: ReactNode;+/*** Width of the drawer in pixels.- * @default 280+ * @default 320*/width?: number;/*** Which side the drawer slides from.- * @default 'start'+ * @default 'end'*/side?: 'start' | 'end';+ /**+ * Accessible label for the drawer. Falls back to title, then 'Navigation'.+ */+ label?: string;+/*** Test ID for the root element.*/@@ -214,33 +232,54 @@ export interface XDSMobileNavProps extends Omit<XDSBaseProps, 'title'> {* which provides built-in focus trapping, body scroll lock, and `::backdrop`.* No manual z-index needed — the browser's top layer handles stacking.*+ * When used inside XDSAppShell, `isOpen` and `onOpenChange` are managed+ * automatically via context. When used standalone, provide them as props.+ ** @example* ```- * <XDSMobileNav- * isOpen={isOpen}- * onOpenChange={(open) => setIsOpen(open)}- * title="Navigation">- * <XDSSideNavSection title="Main">- * <XDSSideNavItem label="Home" icon={HomeIcon} isSelected href="/" />- * <XDSSideNavItem label="Settings" icon={SettingsIcon} href="/settings" />- * </XDSSideNavSection>+ * // Inside AppShell — state managed by AppShell+ * <XDSAppShell mobileNav={+ * <XDSMobileNav title="Navigation">+ * <XDSSideNavItem label="Home" href="/" />+ * </XDSMobileNav>+ * }>+ *+ * // Standalone — manage state yourself+ * <XDSMobileNav isOpen={isOpen} onOpenChange={setIsOpen} title="Navigation">+ * <XDSSideNavItem label="Home" href="/" />* </XDSMobileNav>* ```*/export function XDSMobileNav({- isOpen,- onOpenChange,+ isOpen: isOpenProp,+ onOpenChange: onOpenChangeProp,children,title,- width = 280,- side = 'start',+ header,+ width = 320,+ side = 'end',+ label,'data-testid': testId,xstyle,className,style,ref,}: XDSMobileNavProps) {+ // Read from AppShell context as fallback+ const appShellMobile = useXDSAppShellMobile();+ const isOpen = isOpenProp ?? appShellMobile.isMobileNavOpen;+ const onOpenChange =+ onOpenChangeProp ??+ ((open: boolean) => {+ if (open) {+ appShellMobile.openMobileNav();+ } else {+ appShellMobile.closeMobileNav();+ }+ });+const dialogRef = useRef<HTMLDialogElement>(null);+ const closeTimeoutRef = useRef<ReturnType<typeof setTimeout>>(null);// Merge refsconst setRefs = useCallback(@@ -257,19 +296,35 @@ export function XDSMobileNav({);// Open/close the dialog via showModal()/close()+ // close() is delayed so the slide-out transition can play.useEffect(() => {const dialog = dialogRef.current;if (!dialog) return;+ if (closeTimeoutRef.current) {+ clearTimeout(closeTimeoutRef.current);+ closeTimeoutRef.current = null;+ }+if (isOpen) {if (!dialog.open) {dialog.showModal();}- } else {- if (dialog.open) {+ } else if (dialog.open) {+ const duration = window.matchMedia('(prefers-reduced-motion: reduce)')+ .matches+ ? 10+ : 250;+ closeTimeoutRef.current = setTimeout(() => {dialog.close();- }+ }, duration);}++ return () => {+ if (closeTimeoutRef.current) {+ clearTimeout(closeTimeoutRef.current);+ }+ };}, [isOpen]);// Handle native cancel event (Escape key) — prevent default and route through onOpenChange@@ -299,7 +354,7 @@ export function XDSMobileNav({<dialogref={setRefs}data-testid={testId}- aria-label={title ?? 'Navigation'}+ aria-label={label ?? title ?? 'Navigation'}onClick={handleDialogClick}onCancel={handleCancel}{...mergeProps(@@ -311,7 +366,6 @@ export function XDSMobileNav({xstyle,),)}>- xstyle, className, style,{/* Drawer panel */}<div{...stylex.props(@@ -322,9 +376,14 @@ export function XDSMobileNav({!isStart && styles.drawerEnd,!isStart && isOpen && styles.drawerEndOpen,)}>- {/* Header with optional title and close button */}- <div {...stylex.props(styles.header, !title && styles.headerNoTitle)}>- {title && <XDSHeading level={2}>{title}</XDSHeading>}+ {/* Header — custom content or title + close button */}+ <div+ {...stylex.props(+ styles.header,+ !title && !header && styles.headerNoTitle,+ )}>+ {header ??+ (title ? <XDSHeading level={2}>{title}</XDSHeading> : null)}<XDSButtonvariant="ghost"label="Close navigation"diff --git a/packages/core/src/MobileNav/XDSMobileNavToggle.tsx b/packages/core/src/MobileNav/XDSMobileNavToggle.tsxnew file mode 100644index 0000000000..e73f97a582--- /dev/null+++ b/packages/core/src/MobileNav/XDSMobileNavToggle.tsx@@ -0,0 +1,90 @@+/**+ * @file XDSMobileNavToggle.tsx+ * @input Uses React, XDSButton, XDSIcon, AppShell mobile context+ * @output Exports XDSMobileNavToggle component+ * @position Standalone toggle button; can be placed anywhere in the AppShell tree.+ *+ * Hamburger button that opens/closes the mobile nav drawer.+ * Reads from AppShell mobile context — renders nothing above the mobile breakpoint.+ * Can be placed anywhere in the component tree (TopNav, content area, custom toolbar, etc.).+ */++'use client';++import {type ReactNode} from 'react';+import {XDSButton} from '../Button';+import {XDSIcon} from '../Icon';+import {useXDSAppShellMobile} from '../AppShell/XDSAppShellMobileContext';+import {XDSBaseProps} from '../XDSBaseProps';++export interface XDSMobileNavToggleProps extends Pick<+ XDSBaseProps,+ 'xstyle' | 'className' | 'style'+> {+ /**+ * Custom content to render instead of the default hamburger icon.+ */+ children?: ReactNode;+ /**+ * Accessible label for the toggle button.+ * @default 'Open navigation'+ */+ label?: string;+ /**+ * Test ID for the button element.+ */+ 'data-testid'?: string;+}++/**+ * Mobile nav toggle button. Reads from AppShell context to open/close+ * the mobile navigation drawer.+ *+ * Renders nothing when above the mobile breakpoint — safe to include+ * unconditionally in your layout.+ *+ * @example+ * ```+ * // In a custom toolbar+ * <div className="my-toolbar">+ * <XDSMobileNavToggle />+ * <h1>Page Title</h1>+ * </div>+ *+ * // With custom icon+ * <XDSMobileNavToggle label="Menu">+ * <MyCustomMenuIcon />+ * </XDSMobileNavToggle>+ * ```+ */+export function XDSMobileNavToggle({+ children,+ label = 'Open navigation',+ 'data-testid': testId,+ xstyle,+ className,+ style,+}: XDSMobileNavToggleProps) {+ const {isMobile, isMobileNavEnabled, toggleMobileNav} =+ useXDSAppShellMobile();++ // Don't render above the breakpoint or when mobile nav is disabled+ if (!isMobile || !isMobileNavEnabled) {+ return null;+ }++ return (+ <XDSButton+ variant="ghost"+ label={label}+ icon={children ?? <XDSIcon icon="menu" color="inherit" />}+ onClick={toggleMobileNav}+ data-testid={testId ?? 'mobile-nav-toggle'}+ xstyle={xstyle}+ className={className}+ style={style}+ />+ );+}++XDSMobileNavToggle.displayName = 'XDSMobileNavToggle';diff --git a/packages/core/src/MobileNav/index.ts b/packages/core/src/MobileNav/index.tsindex 1b01e7f7a7..95facccdfe 100644--- a/packages/core/src/MobileNav/index.ts+++ b/packages/core/src/MobileNav/index.ts@@ -1,9 +1,11 @@/*** @file index.ts- * @input Imports from XDSMobileNav.tsx- * @output Re-exports XDSMobileNav component and XDSMobileNavProps type+ * @input Imports from XDSMobileNav.tsx, XDSMobileNavToggle.tsx+ * @output Re-exports MobileNav components and types* @position Barrel export; consumed by packages/core/src/index.ts*/export {XDSMobileNav} from './XDSMobileNav';export type {XDSMobileNavProps} from './XDSMobileNav';+export {XDSMobileNavToggle} from './XDSMobileNavToggle';+export type {XDSMobileNavToggleProps} from './XDSMobileNavToggle';diff --git a/packages/core/src/SideNav/XDSSideNav.tsx b/packages/core/src/SideNav/XDSSideNav.tsxindex 48532bd786..043783d594 100644--- a/packages/core/src/SideNav/XDSSideNav.tsx+++ b/packages/core/src/SideNav/XDSSideNav.tsx@@ -24,6 +24,8 @@ import {colorVars, spacingVars} from '../theme/tokens.stylex';import {xdsClassName, mergeProps} from '../utils';import {XDSSideNavCollapseContext} from './XDSSideNavCollapseContext';import {XDSSideNavCollapseButton} from './XDSSideNavCollapseButton';+import {useXDSSideNavRenderMode} from './XDSSideNavRenderContext';+import {XDSMobileNav} from '../MobileNav/XDSMobileNav';// =============================================================================// Styles@@ -109,6 +111,25 @@ const styles = stylex.create({borderBlockStart: 'none',paddingBlockStart: 0,},+ // Topbar mode — horizontal layout for mobile top bar+ topbar: {+ display: 'flex',+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between',+ height: 48,+ width: '100%',+ paddingInline: spacingVars['--spacing-2'],+ backgroundColor: 'inherit',+ boxSizing: 'border-box',+ overflow: 'hidden',+ },+ topbarIcons: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ marginInlineStart: 'auto',+ },});// =============================================================================@@ -252,6 +273,44 @@ export function XDSSideNav({isCollapsible,};+ // Render mode — when inside AppShell mobile layout, render subsets+ const renderMode = useXDSSideNavRenderMode();++ // =========================================================================+ // Topbar mode — heading + footerIcons in a horizontal bar+ // =========================================================================+ if (renderMode === 'topbar') {+ return (+ <div+ data-testid={testId}+ {...mergeProps(+ xdsClassName('side-nav', {mode: 'topbar'}),+ stylex.props(styles.topbar, xstyle),+ className,+ style,+ )}>+ {header}+ <div {...stylex.props(styles.topbarIcons)}>{footerIcons}</div>+ </div>+ );+ }++ // =========================================================================+ // Drawer mode — render inside XDSMobileNav with heading as header+ // =========================================================================+ if (renderMode === 'drawer') {+ return (+ <XDSMobileNav header={header} data-testid={testId}>+ {topContent}+ {children}+ {footer}+ </XDSMobileNav>+ );+ }++ // =========================================================================+ // Default mode — full sidebar+ // =========================================================================const hasStickyTop = !!(header || topContent);const hasStickyBottom = !!(footer || footerIcons);diff --git a/packages/core/src/SideNav/XDSSideNavCollapseButton.tsx b/packages/core/src/SideNav/XDSSideNavCollapseButton.tsxindex f151047613..5bdd1923bb 100644--- a/packages/core/src/SideNav/XDSSideNavCollapseButton.tsx+++ b/packages/core/src/SideNav/XDSSideNavCollapseButton.tsx@@ -20,6 +20,7 @@ import {transitionVars} from '../theme/tokens.stylex';import {getIcon} from '../Icon/globalIconRegistry';import {XDSButton} from '../Button';import {useXDSSideNavCollapse} from './XDSSideNavCollapseContext';+import {useXDSAppShellMobile} from '../AppShell/XDSAppShellMobileContext';// =============================================================================// Styles@@ -92,6 +93,7 @@ export function XDSSideNavCollapseButton({children,}: XDSSideNavCollapseButtonProps) {const {isCollapsed, toggle, isCollapsible} = useXDSSideNavCollapse();+ const {isMobile} = useXDSAppShellMobile();const handleClick = useCallback(() => {toggle();@@ -101,7 +103,9 @@ export function XDSSideNavCollapseButton({// For now, the button only works via context (inside sidenav or// when AppShell provides the context at the shell level).- if (!isCollapsible) {+ // Hide when not collapsible, or when in mobile mode (sidenav is in+ // the mobile drawer — collapse doesn't apply there)+ if (!isCollapsible || isMobile) {return null;}diff --git a/packages/core/src/SideNav/XDSSideNavRenderContext.ts b/packages/core/src/SideNav/XDSSideNavRenderContext.tsnew file mode 100644index 0000000000..dd0ca498fd--- /dev/null+++ b/packages/core/src/SideNav/XDSSideNavRenderContext.ts@@ -0,0 +1,26 @@+/**+ * @file XDSSideNavRenderContext.ts+ * @input React createContext, useContext+ * @output Exports XDSSideNavRenderContext and useXDSSideNavRenderMode hook+ * @position Internal context for controlling SideNav rendering mode+ *+ * When AppShell renders the SideNav in multiple locations (inline, top bar,+ * mobile drawer), this context tells SideNav which parts to render:+ * - 'default': full sidebar (desktop inline)+ * - 'topbar': heading + footerIcons only, laid out horizontally (mobile top bar)+ * - 'drawer': children only, skip heading + footerIcons (mobile drawer)+ */++import {createContext, useContext} from 'react';++export type XDSSideNavRenderMode = 'default' | 'topbar' | 'drawer';++export const XDSSideNavRenderContext =+ createContext<XDSSideNavRenderMode>('default');++/**+ * Read the current SideNav render mode from context.+ */+export function useXDSSideNavRenderMode(): XDSSideNavRenderMode {+ return useContext(XDSSideNavRenderContext);+}diff --git a/packages/core/src/SideNav/index.ts b/packages/core/src/SideNav/index.tsindex ca261565c4..4da932c677 100644--- a/packages/core/src/SideNav/index.ts+++ b/packages/core/src/SideNav/index.ts@@ -23,3 +23,9 @@ export {XDSSideNavCollapseButton} from './XDSSideNavCollapseButton';export type {XDSSideNavCollapseButtonProps} from './XDSSideNavCollapseButton';export {useXDSSideNavCollapse} from './XDSSideNavCollapseContext';++export {+ XDSSideNavRenderContext,+ useXDSSideNavRenderMode,+} from './XDSSideNavRenderContext';+export type {XDSSideNavRenderMode} from './XDSSideNavRenderContext';