Skip to content

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

TypeScript

fix(AppShell): remove useXDSSlotPresence, fix mobile nav with heading-only TopNav (#2243) (#2589)

Cindy Zhang71104e50f0c8
diff --git a/apps/sandbox/src/app/(raw)/pages/shell-lab/page.tsx b/apps/sandbox/src/app/(raw)/pages/shell-lab/page.tsx
index eeb91eff2e..94a4b45a45 100644
--- a/apps/sandbox/src/app/(raw)/pages/shell-lab/page.tsx
+++ b/apps/sandbox/src/app/(raw)/pages/shell-lab/page.tsx
@@ -2,7 +2,8 @@
'use client';
-import {useState, useCallback} from 'react';
+import {Suspense, useState, useCallback, useEffect, useMemo} from 'react';
+import {useSearchParams} from 'next/navigation';
import * as stylex from '@stylexjs/stylex';
import {XDSAppShell} from '@xds/core/AppShell';
@@ -943,11 +944,66 @@ const styles = stylex.create({
},
});
+// =============================================================================
+// URL param serialization helpers
+// =============================================================================
+
+function configToParams(config: ShellConfig): URLSearchParams {
+ const params = new URLSearchParams();
+ for (const [key, value] of Object.entries(config)) {
+ const defaultValue = DEFAULT_CONFIG[key as keyof ShellConfig];
+ if (value !== defaultValue) {
+ params.set(key, String(value));
+ }
+ }
+ return params;
+}
+
+function paramsToConfig(params: URLSearchParams): ShellConfig {
+ const config = {...DEFAULT_CONFIG};
+ for (const [key, value] of params.entries()) {
+ if (key in DEFAULT_CONFIG) {
+ const defaultValue = DEFAULT_CONFIG[key as keyof ShellConfig];
+ if (typeof defaultValue === 'boolean') {
+ (config as Record<string, unknown>)[key] = value === 'true';
+ } else {
+ (config as Record<string, unknown>)[key] = value;
+ }
+ }
+ }
+ return config;
+}
+
export default function ShellLabPage() {
- const [config, setConfig] = useState<ShellConfig>(DEFAULT_CONFIG);
+ return (
+ <Suspense>
+ <ShellLabContent />
+ </Suspense>
+ );
+}
+
+function ShellLabContent() {
+ const searchParams = useSearchParams();
+
+ // Initialize config from URL params on mount
+ const initialConfig = useMemo(
+ () => paramsToConfig(searchParams),
+ [], // only read URL on mount
+ );
+ const [config, setConfig] = useState<ShellConfig>(initialConfig);
const [showConfig, setShowConfig] = useState(true);
const [externalCollapsed, setExternalCollapsed] = useState(false);
+ // Sync config changes to URL
+ useEffect(() => {
+ const params = configToParams(config);
+ const paramString = params.toString();
+ const newUrl = paramString
+ ? `${window.location.pathname}?${paramString}`
+ : window.location.pathname;
+ window.history.replaceState(null, '', newUrl);
+ }, [config]);
+
const handleConfigChange = useCallback((update: Partial<ShellConfig>) => {
setConfig(prev => ({...prev, ...update}));
}, []);
diff --git a/packages/core/src/AppShell/XDSAppShell.test.tsx b/packages/core/src/AppShell/XDSAppShell.test.tsx
index 17ddd85a73..92b034c6a2 100644
--- a/packages/core/src/AppShell/XDSAppShell.test.tsx
+++ b/packages/core/src/AppShell/XDSAppShell.test.tsx
@@ -330,6 +330,128 @@ describe('XDSAppShell', () => {
expect(screen.getAllByText('Side item').length).toBeGreaterThan(0);
});
+ it('shows mobile nav toggle for sideNav-only layout with heading-only topNav (#2243)', () => {
+ mockMql = createMockMatchMedia(true);
+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue(mockMql));
+
+ render(
+ <XDSAppShell
+ topNav={
+ <XDSTopNav
+ label="Main navigation"
+ heading={<XDSTopNavHeading heading="My App" />}
+ />
+ }
+ sideNav={<TestSideNav>Home</TestSideNav>}
+ mobileNav={{breakpoint: 'md'}}>
+ <div>Content</div>
+ </XDSAppShell>,
+ );
+
+ expect(
+ screen.getByRole('button', {name: /open navigation/i}),
+ ).toBeInTheDocument();
+ });
+
+ it('renders sidenav items exactly once in mobile drawer when topNav has only heading (#2243)', () => {
+ mockMql = createMockMatchMedia(true);
+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue(mockMql));
+
+ render(
+ <XDSAppShell
+ variant="section"
+ topNav={
+ <XDSTopNav
+ label="Main navigation"
+ heading={<XDSTopNavHeading heading="My App" />}
+ />
+ }
+ sideNav={
+ <XDSSideNav>
+ <XDSSideNavItem label="Dashboard" href="/" isSelected />
+ <XDSSideNavItem label="Settings" href="/settings" />
+ </XDSSideNav>
+ }
+ mobileNav={{breakpoint: 'md'}}
+ contentPadding={4}>
+ <div>Content</div>
+ </XDSAppShell>,
+ );
+
+ expect(
+ screen.getByRole('button', {name: /open navigation/i}),
+ ).toBeInTheDocument();
+ expect(screen.getAllByText('Dashboard')).toHaveLength(1);
+ expect(screen.getAllByText('Settings')).toHaveLength(1);
+ });
+
+ it('does not show auto mobile toggle when sideNav is explicitly undefined (#2243)', () => {
+ mockMql = createMockMatchMedia(true);
+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue(mockMql));
+
+ render(
+ <XDSAppShell
+ topNav={
+ <XDSTopNav
+ label="Main navigation"
+ heading={<XDSTopNavHeading heading="My App" />}
+ />
+ }
+ sideNav={undefined}
+ mobileNav={{breakpoint: 'md'}}>
+ <div>Content</div>
+ </XDSAppShell>,
+ );
+
+ expect(
+ screen.queryByRole('button', {name: /open navigation/i}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not show auto mobile toggle when sideNav is omitted entirely', () => {
+ mockMql = createMockMatchMedia(true);
+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue(mockMql));
+
+ render(
+ <XDSAppShell
+ topNav={
+ <XDSTopNav
+ label="Main navigation"
+ heading={<XDSTopNavHeading heading="My App" />}
+ />
+ }
+ mobileNav={{breakpoint: 'md'}}>
+ <div>Content</div>
+ </XDSAppShell>,
+ );
+
+ expect(
+ screen.queryByRole('button', {name: /open navigation/i}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('heading-only topNav does not prevent sidenav from collapsing to mobile (#2243)', () => {
+ mockMql = createMockMatchMedia(true);
+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue(mockMql));
+
+ const {container} = render(
+ <XDSAppShell
+ topNav={
+ <XDSTopNav
+ label="Main navigation"
+ heading={<XDSTopNavHeading heading="My App" />}
+ />
+ }
+ sideNav={<TestSideNav>Home</TestSideNav>}
+ mobileNav={{breakpoint: 'md'}}>
+ <div>Content</div>
+ </XDSAppShell>,
+ );
+
+ const inlinePanel = container.querySelector('.xds-layout-panel');
+ expect(inlinePanel).toBeNull();
+ });
+
it('renders mobile layout on first render when defaultIsMobile is true', () => {
// matchMedia says mobile too — simulates correct SSR hint
mockMql = createMockMatchMedia(true);
diff --git a/packages/core/src/AppShell/XDSAppShell.tsx b/packages/core/src/AppShell/XDSAppShell.tsx
index 8d1f82f7c9..7ff82d1830 100644
--- a/packages/core/src/AppShell/XDSAppShell.tsx
+++ b/packages/core/src/AppShell/XDSAppShell.tsx
@@ -46,11 +46,10 @@ import {XDSSideNavRenderContext} from '../SideNav/XDSSideNavRenderContext';
import {XDSTopNavRenderContext} from '../TopNav/XDSTopNavRenderContext';
import {XDSTopNavMobileContentContext} from '../TopNav/XDSTopNavMobileContentContext';
import {XDSAppShellMobileContext} from './XDSAppShellMobileContext';
-import {useXDSSlotPresence} from './useXDSSlotPresence';
import type {XDSAppShellMobileContextValue} from './XDSAppShellMobileContext';
import type {SpacingStep} from '../utils/types';
import type {XDSBaseProps} from '../XDSBaseProps';
-import {xdsClassName, mergeProps, mergeRefs} from '../utils';
+import {xdsClassName, mergeProps, mergeRefs, isRenderable} from '../utils';
import {useMediaQuery} from '../hooks/useMediaQuery';
import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
@@ -241,11 +240,37 @@ export interface XDSAppShellProps extends XDSBaseProps<HTMLDivElement> {
/**
* Side navigation — typically an XDSSideNav.
+ *
+ * Pass `undefined` (or omit) when a page has no side navigation.
+ * Do NOT pass a component that renders `null` — AppShell treats any
+ * renderable value as "sidenav exists".
+ *
+ * **Next.js parallel routes:** Conditionally pass the slot based on
+ * the current route rather than relying on a `default.tsx` that
+ * returns `null`:
+ *
+ * @example
+ * ```tsx
+ * const SIDEBAR_ROUTES = ['/dashboard', '/settings'];
+ *
+ * function Layout({ children, sidebar }) {
+ * const hasSidebar = SIDEBAR_ROUTES.some(r => pathname.startsWith(r));
+ * return (
+ * <XDSAppShell
+ * sideNav={hasSidebar ? sidebar : undefined}
+ * mobileNav={hasSidebar ? { breakpoint: 'md' } : false}
+ * >
+ * {children}
+ * </XDSAppShell>
+ * );
+ * }
+ * ```
*/
sideNav?: ReactNode;
/**
* Top navigation — typically an XDSTopNav.
+ * Same contract as `sideNav` — pass `undefined` when there's no top nav.
*/
topNav?: ReactNode;
}
@@ -478,12 +503,6 @@ export function XDSAppShell({
// Refs are attached to wrapper divs around each slot; a MutationObserver
// checks childNodes to track whether each slot has rendered content.
// =========================================================================
- const {ref: topNavRef, hasContent: hasTopNavContent} = useXDSSlotPresence(
- topNav != null,
- );
- const {ref: sideNavRef, hasContent: hasSideNavContent} = useXDSSlotPresence(
- sideNav != null,
- );
// =========================================================================
// Mobile nav open state (controlled + uncontrolled)
@@ -513,12 +532,10 @@ export function XDSAppShell({
const isAuto = height === 'auto';
// Nav style derived values
- const hasBanner = banner != null;
- // Mounting: props were passed — mount the container so children can register
- const hasTopNav = topNav != null;
- const hasSideNav = sideNav != null;
- // Visibility: children actually rendered — drives mobile nav decisions
- const hasNavContent = hasSideNavContent || hasTopNavContent;
+ const hasBanner = isRenderable(banner);
+ const hasTopNav = isRenderable(topNav);
+ const hasSideNav = isRenderable(sideNav);
+ const hasNavContent = hasTopNav || hasSideNav;
const mobileNavEnabled =
!mobileNavDisabled && hasNavContent && mobileNavReactNode == null;
const navHasDividers = variant === 'section';
@@ -612,16 +629,14 @@ export function XDSAppShell({
// Wrap with mobile content context so TopNav knows there's SideNav content
// in the drawer and shows the toggle even without its own collapsible items.
const mobileContentValue =
- hasSideNavContent && mobileNavHasToggle ? (
+ hasSideNav && mobileNavHasToggle ? (
// eslint-disable-next-line @eslint-react/no-unstable-context-value -- context transports ReactNode; instability is inherent
<XDSSideNavRenderContext value="drawer-content">
- <div ref={sideNavRef} style={{display: 'contents'}}>
- {sideNav}
- </div>
+ {sideNav}
</XDSSideNavRenderContext>
) : null;
- const drawerMobileContentValue = hasSideNavContent ? (
+ const drawerMobileContentValue = hasSideNav ? (
// eslint-disable-next-line @eslint-react/no-unstable-context-value -- context transports ReactNode; instability is inherent
<XDSSideNavRenderContext value="drawer-content">
{sideNav}
@@ -632,9 +647,7 @@ export function XDSAppShell({
isBelowBreakpoint && !mobileNavDisabled && mobileNavReactNode == null ? (
<XDSTopNavMobileContentContext value={mobileContentValue}>
<XDSTopNavRenderContext value="mobile-bar">
- <div ref={topNavRef} style={{display: 'contents'}}>
- {topNav}
- </div>
+ {topNav}
</XDSTopNavRenderContext>
</XDSTopNavMobileContentContext>
) : (
@@ -648,11 +661,7 @@ export function XDSAppShell({
{hasBanner && (
<div {...stylex.props(styles.banner, navAreaStyle)}>{banner}</div>
)}
- {hasTopNav && (
- <div ref={topNavRef} style={{display: 'contents'}}>
- {topNavContent}
- </div>
- )}
+ {hasTopNav && topNavContent}
</XDSLayoutHeader>
) : undefined;
@@ -687,9 +696,7 @@ export function XDSAppShell({
isAuto && stickyBgStyle,
isAuto && styles.panelAutoFill,
]}>
- <div ref={sideNavRef} style={{display: 'contents'}}>
- {sideNav}
- </div>
+ {sideNav}
</XDSLayoutPanel>
) : undefined;
@@ -703,8 +710,7 @@ export function XDSAppShell({
// =========================================================================
// Build main content
// =========================================================================
- const shouldElevateWithCorner =
- isElevated && hasTopNavContent && showSideNavInline;
+ const shouldElevateWithCorner = isElevated && hasTopNav && showSideNavInline;
const mainInner = (
<XDSLayoutContent
@@ -742,7 +748,7 @@ export function XDSAppShell({
// 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 && !hasTopNavContent && hasSideNav ? (
+ shouldShowAutoToggle && !hasTopNav && hasSideNav ? (
<div
{...mergeProps(
xdsClassName('app-shell-header', {variant}),
@@ -754,9 +760,7 @@ export function XDSAppShell({
role="navigation"
aria-label="Mobile navigation">
<XDSSideNavRenderContext value="topbar">
- <div ref={sideNavRef} style={{display: 'contents'}}>
- {sideNav}
- </div>
+ {sideNav}
</XDSSideNavRenderContext>
<XDSMobileNavToggle />
</div>
@@ -819,16 +823,12 @@ export function XDSAppShell({
{/* SideNav drawer — always mounted so presence detection works.
Hidden when TopNav owns the drawer (combined mode passes
sideNav via TopNav's mobile content context instead). */}
- {hasSideNav && (
- <div
- ref={sideNavRef}
- style={{display: hasTopNavContent ? 'none' : 'contents'}}>
- <XDSSideNavRenderContext value="drawer">
- {sideNav}
- </XDSSideNavRenderContext>
- </div>
+ {hasSideNav && !hasTopNav && (
+ <XDSSideNavRenderContext value="drawer">
+ {sideNav}
+ </XDSSideNavRenderContext>
)}
- {hasTopNav && hasTopNavContent && (
+ {hasTopNav && (
<XDSTopNavMobileContentContext value={drawerMobileContentValue}>
<XDSTopNavRenderContext value="drawer">
{topNav}
diff --git a/packages/core/src/AppShell/useXDSSlotPresence.tsx b/packages/core/src/AppShell/useXDSSlotPresence.tsx
deleted file mode 100644
index d633f0b39a..0000000000
--- a/packages/core/src/AppShell/useXDSSlotPresence.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-'use client';
-
-/**
- * @file useXDSSlotPresence.tsx
- * @input Uses React useCallback, useEffect, useRef, useState
- * @output Exports useXDSSlotPresence hook
- * @position Internal hook for detecting whether slot containers have rendered content.
- *
- * Solves the "empty component" problem: when a framework (e.g. Next.js parallel
- * routes) passes a React element to a slot but the component renders null, prop
- * checks like `sideNav != null` are true even though nothing rendered.
- *
- * AppShell wraps each slot render in a `display:contents` div with a ref from
- * this hook. The hook checks `childNodes` to determine whether the slot actually
- * produced DOM output. Multiple elements can share the same ref (via callback
- * ref) — only one mounts at a time, and the hook observes whichever is active.
- */
-
-import {useCallback, useEffect, useRef, useState} from 'react';
-
-function hasChildContent(el: HTMLElement): boolean {
- for (let i = 0; i < el.childNodes.length; i++) {
- const node = el.childNodes[i];
- if (node.nodeType === Node.ELEMENT_NODE) {
- return true;
- }
- if (
- node.nodeType === Node.TEXT_NODE &&
- node.textContent &&
- node.textContent.trim() !== ''
- ) {
- return true;
- }
- }
- return false;
-}
-
-/**
- * Hook that detects whether a DOM container has rendered children.
- *
- * Returns a callback ref to attach to `display:contents` wrapper divs.
- * Multiple wrappers can share the same ref — only one is active at a time
- * (e.g. sideNav renders inline OR in the mobile drawer, not both).
- *
- * @param initialValue - Initial assumption before the first DOM check.
- * Pass `prop != null` to assume content exists until proven otherwise.
- */
-export function useXDSSlotPresence(initialValue = false) {
- const [hasContent, setHasContent] = useState(initialValue);
- const observerRef = useRef<MutationObserver | null>(null);
- const elementRef = useRef<HTMLDivElement | null>(null);
-
- // Callback ref — called when elements mount/unmount
- const ref = useCallback((node: HTMLDivElement | null) => {
- // Clean up previous observer
- if (observerRef.current) {
- observerRef.current.disconnect();
- observerRef.current = null;
- }
-
- elementRef.current = node;
-
- if (!node) {
- setHasContent(false);
- return;
- }
-
- if (node) {
- // Check immediately
- setHasContent(hasChildContent(node));
-
- // Observe for changes
- const observer = new MutationObserver(() => {
- setHasContent(hasChildContent(node));
- });
- observer.observe(node, {childList: true, subtree: true});
- observerRef.current = observer;
- }
- }, []);
-
- // Clean up on unmount
- useEffect(() => {
- return () => {
- if (observerRef.current) {
- observerRef.current.disconnect();
- }
- };
- }, []);
-
- return {ref, hasContent};
-}
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index b8287d3648..b28cf7a90d 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -72,3 +72,4 @@ export {mergeRefs} from './mergeRefs';
export {groupItems, getItemGroup} from './groupItems';
export type {ItemGroup} from './groupItems';
export {observeResize, unobserveResize} from './sharedResizeObserver';
+export {isRenderable} from './isRenderable';
diff --git a/packages/core/src/utils/isRenderable.ts b/packages/core/src/utils/isRenderable.ts
new file mode 100644
index 0000000000..5e681c57a9
--- /dev/null
+++ b/packages/core/src/utils/isRenderable.ts
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file isRenderable.ts
+ * @input A ReactNode value
+ * @output Boolean indicating whether the value will produce DOM output
+ * @position Utility for checking if a React slot prop has meaningful content.
+ *
+ * React treats null, undefined, true, false, and '' as empty — they render
+ * nothing. This utility checks if a ReactNode is NOT one of those values,
+ * meaning it will produce actual DOM output when rendered.
+ *
+ * Use this instead of `prop != null` when checking if a slot has content,
+ * since boolean/empty-string props also render nothing.
+ */
+
+import type {ReactNode} from 'react';
+
+/**
+ * Returns true if a ReactNode value will produce DOM output when rendered.
+ * Returns false for null, undefined, true, false, and empty string.
+ *
+ * @example
+ * ```tsx
+ * const hasSideNav = isRenderable(sideNav);
+ * const hasTopNav = isRenderable(topNav);
+ * ```
+ */
+export function isRenderable(node: ReactNode): boolean {
+ return node != null && typeof node !== 'boolean' && node !== '';
+}