Skip to content

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

TypeScript

fix(AppShell): detect empty slots via presence registration (#1377)

Cindy Zhangb742798fecca
diff --git a/apps/sandbox/src/app/(raw)/layout.tsx b/apps/sandbox/src/app/(raw)/layout.tsx
new file mode 100644
index 0000000000..82d88bfea2
--- /dev/null
+++ b/apps/sandbox/src/app/(raw)/layout.tsx
@@ -0,0 +1,3 @@
+export default function RawLayout({children}: {children: React.ReactNode}) {
+ return <>{children}</>;
+}
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx b/apps/sandbox/src/app/(raw)/pages/shell-lab/page.tsx
similarity index 95%
rename from apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx
rename to apps/sandbox/src/app/(raw)/pages/shell-lab/page.tsx
index 0225382454..ca401c7284 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/shell-lab/page.tsx
+++ b/apps/sandbox/src/app/(raw)/pages/shell-lab/page.tsx
@@ -102,12 +102,21 @@ const DocsIcon = (props: React.SVGProps<SVGSVGElement>) => (
</svg>
);
+/**
+ * A React component that renders null. Simulates the Next.js parallel route
+ * pattern where a slot (e.g. @sidebar/default.tsx) returns null — the slot
+ * still receives a React element, but it produces no DOM output.
+ */
+function EmptySlot() {
+ return null;
+}
+
interface ShellConfig {
variant: 'wash' | 'surface' | 'section' | 'elevated';
height: 'fill' | 'auto';
sideNavBreakpoint: 'sm' | 'md' | 'lg' | 'none';
- showSideNav: boolean;
- showTopNav: boolean;
+ sideNavMode: 'show' | 'hide' | 'empty-component';
+ topNavMode: 'show' | 'hide' | 'empty-component';
showBanner: boolean;
showFooter: boolean;
showFooterIcons: boolean;
@@ -122,7 +131,7 @@ interface ShellConfig {
collapseToggleLocation: 'sidenav' | 'topnav';
mobileNavMode: 'auto' | 'customContent' | 'customToggle' | 'disabled';
mobileNavSide: 'start' | 'end';
- topNavAlignment: 'start' | 'center' | 'end';
+ topNavAlignment: 'none' | 'start' | 'center' | 'end';
topNavStyle: 'items' | 'menus' | 'mega';
showTopNavHeading: boolean;
topNavHeadingStyle: 'none' | 'simple' | 'link' | 'menu' | 'full';
@@ -135,8 +144,8 @@ const DEFAULT_CONFIG: ShellConfig = {
variant: 'section',
height: 'fill',
sideNavBreakpoint: 'md',
- showSideNav: true,
- showTopNav: true,
+ sideNavMode: 'show',
+ topNavMode: 'show',
showBanner: false,
showFooter: false,
showFooterIcons: true,
@@ -215,10 +224,19 @@ function ConfigPanel({
<XDSText type="label" weight="bold">
SideNav
</XDSText>
- <ToggleRow
- label="Show"
- value={config.showSideNav}
- onChange={v => onChange({showSideNav: v})}
+ <SelectorRow
+ label="Mode"
+ value={config.sideNavMode}
+ onChange={v =>
+ onChange({
+ sideNavMode: v as ShellConfig['sideNavMode'],
+ })
+ }
+ options={[
+ {value: 'show', label: 'Show'},
+ {value: 'hide', label: 'Hide'},
+ {value: 'empty-component', label: 'Empty Component'},
+ ]}
/>
<SelectorRow
label="Heading"
@@ -312,10 +330,19 @@ function ConfigPanel({
<XDSText type="label" weight="bold">
TopNav
</XDSText>
- <ToggleRow
- label="Show"
- value={config.showTopNav}
- onChange={v => onChange({showTopNav: v})}
+ <SelectorRow
+ label="Mode"
+ value={config.topNavMode}
+ onChange={v =>
+ onChange({
+ topNavMode: v as ShellConfig['topNavMode'],
+ })
+ }
+ options={[
+ {value: 'show', label: 'Show'},
+ {value: 'hide', label: 'Hide'},
+ {value: 'empty-component', label: 'Empty Component'},
+ ]}
/>
<ToggleRow
label="Heading"
@@ -374,6 +401,7 @@ function ConfigPanel({
onChange({topNavAlignment: v as ShellConfig['topNavAlignment']})
}
options={[
+ {value: 'none', label: 'None'},
{value: 'start', label: 'Start'},
{value: 'center', label: 'Center'},
{value: 'end', label: 'End'},
@@ -966,7 +994,7 @@ export default function ShellLabPage() {
height={config.height}
contentPadding={6}
topNav={
- config.showTopNav ? (
+ config.topNavMode === 'show' ? (
<SampleTopNav
config={config}
onToggleCollapse={
@@ -976,15 +1004,19 @@ export default function ShellLabPage() {
: undefined
}
/>
+ ) : config.topNavMode === 'empty-component' ? (
+ <EmptySlot />
) : undefined
}
sideNav={
- config.showSideNav ? (
+ config.sideNavMode === 'show' ? (
<SampleSideNav
config={config}
externalCollapsed={externalCollapsed}
setExternalCollapsed={setExternalCollapsed}
/>
+ ) : config.sideNavMode === 'empty-component' ? (
+ <EmptySlot />
) : undefined
}
mobileNav={mobileNav}
diff --git a/packages/core/src/AppShell/XDSAppShell.tsx b/packages/core/src/AppShell/XDSAppShell.tsx
index 02d078d428..38dc631dae 100644
--- a/packages/core/src/AppShell/XDSAppShell.tsx
+++ b/packages/core/src/AppShell/XDSAppShell.tsx
@@ -1,5 +1,7 @@
'use client';
+import React from 'react';
+
/**
* @file XDSAppShell.tsx
* @input Uses React, XDSLayout, XDSLayoutHeader, XDSLayoutPanel, XDSLayoutContent, StyleX
@@ -43,10 +45,22 @@ import {XDSSideNavRenderContext} from '../SideNav/XDSSideNavRenderContext';
import {XDSTopNavRenderContext} from '../TopNav/XDSTopNavRenderContext';
import {XDSTopNavMobileContentContext} from '../TopNav/XDSTopNavMobileContentContext';
import {XDSAppShellMobileContext} from './XDSAppShellMobileContext';
+import {useXDSSlotPresence} from './XDSAppShellSlotPresence';
import type {XDSAppShellMobileContextValue} from './XDSAppShellMobileContext';
import type {SpacingStep} from '../utils/types';
import {xdsClassName, mergeProps} from '../utils';
+const HasActivity = typeof React.Activity !== 'undefined';
+const ActivityWrapper = HasActivity
+ ? ({
+ mode,
+ children,
+ }: {
+ mode: 'visible' | 'hidden';
+ children: React.ReactNode;
+ }) => <React.Activity mode={mode}>{children}</React.Activity>
+ : ({children}: {mode: string; children: React.ReactNode}) => <>{children}</>;
+
// =============================================================================
// Constants
// =============================================================================
@@ -466,6 +480,18 @@ export function XDSAppShell({
const mobileNavHasToggle = mobileNavConfig?.hasToggle !== false;
const mobileNavIsControlled = mobileNavConfig?.isOpen !== undefined;
+ // =========================================================================
+ // Slot presence — checks whether slot containers have rendered DOM content.
+ // Refs are attached to wrapper divs around each slot; useLayoutEffect checks
+ // childNodes so presence is known before paint.
+ // =========================================================================
+ const {ref: topNavRef, hasContent: hasTopNavContent} = useXDSSlotPresence(
+ topNav != null,
+ );
+ const {ref: sideNavRef, hasContent: hasSideNavContent} = useXDSSlotPresence(
+ sideNav != null,
+ );
+
// =========================================================================
// Mobile nav open state (controlled + uncontrolled)
// =========================================================================
@@ -490,11 +516,11 @@ export function XDSAppShell({
// 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;
- const hasNavContent = hasSideNav || hasTopNav;
- // Mobile nav auto-management is enabled when not disabled, there's nav content,
- // AND the user hasn't provided a ReactNode (full escape hatch = user owns everything)
+ // Visibility: children actually rendered — drives mobile nav decisions
+ const hasNavContent = hasSideNavContent || hasTopNavContent;
const mobileNavEnabled =
!mobileNavDisabled && hasNavContent && mobileNavReactNode == null;
const navHasDividers = variant === 'section';
@@ -564,7 +590,7 @@ export function XDSAppShell({
// efficient and does not over-trigger.
// =========================================================================
useEffect(() => {
- if (sideNavBreakpoint === 'none' || !hasNavContent) return;
+ if (sideNavBreakpoint === 'none') return;
const breakpointPx = BREAKPOINT_VALUES[sideNavBreakpoint];
const mql = window.matchMedia(`(max-width: ${breakpointPx}px)`);
@@ -579,34 +605,25 @@ export function XDSAppShell({
mql.addEventListener('change', handleChange);
return () => mql.removeEventListener('change', handleChange);
- }, [sideNavBreakpoint, hasNavContent]);
+ }, [sideNavBreakpoint]);
// =========================================================================
// Determine if sideNav should show as overlay (mobile) or inline
// =========================================================================
const showSideNavInline = hasSideNav && !isBelowBreakpoint;
- // Three mobile nav rendering modes:
- // 1. ReactNode shorthand — render the user's element as-is (they own the drawer)
+
+ // Mobile nav rendering modes:
+ // 1. ReactNode shorthand — user provided <XDSMobileNav> directly
const shouldRenderMobileNavReactNode = mobileNavReactNode != null;
- // 2. Config with custom content — render directly
+ // 2. Config with custom content
const shouldRenderConfigContent =
mobileNavEnabled && mobileNavConfigContent != null && isBelowBreakpoint;
- // 3. Auto — render nav content in drawer mode
+ // 3. Auto — mount drawer structure when props exist, use presence for path selection
const shouldRenderAutoMobileNav =
- mobileNavEnabled &&
- !mobileNavReactNode &&
+ !mobileNavDisabled &&
+ mobileNavReactNode == null &&
!mobileNavConfigContent &&
- isBelowBreakpoint &&
- hasNavContent;
- // TopNav-only auto mobile (no SideNav) — TopNav handles its own drawer
- const shouldRenderTopNavDrawer =
- shouldRenderAutoMobileNav && hasTopNav && !hasSideNav;
- // TopNav + SideNav combined — TopNav owns drawer, SideNav content via context
- const shouldRenderCombinedDrawer =
- shouldRenderAutoMobileNav && hasTopNav && hasSideNav;
- // SideNav-only auto mobile (no TopNav) — SideNav handles its own drawer
- const shouldRenderSideNavDrawer =
- shouldRenderAutoMobileNav && !hasTopNav && hasSideNav;
+ isBelowBreakpoint;
// =========================================================================
// Mobile context — shared with XDSMobileNavToggle and future TopNav mobile
@@ -634,17 +651,21 @@ 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 topNavContent = hasTopNav ? (
- isBelowBreakpoint && mobileNavEnabled ? (
+ isBelowBreakpoint && !mobileNavDisabled && mobileNavReactNode == null ? (
<XDSTopNavMobileContentContext
value={
- hasSideNav ? (
+ hasSideNavContent ? (
<XDSSideNavRenderContext value="drawer-content">
- {sideNav}
+ <div ref={sideNavRef} style={{display: 'contents'}}>
+ {sideNav}
+ </div>
</XDSSideNavRenderContext>
) : null
}>
<XDSTopNavRenderContext value="mobile-bar">
- {topNav}
+ <div ref={topNavRef} style={{display: 'contents'}}>
+ {topNav}
+ </div>
</XDSTopNavRenderContext>
</XDSTopNavMobileContentContext>
) : (
@@ -659,7 +680,11 @@ export function XDSAppShell({
hasDivider={navHasDividers && hasTopNav}
xstyle={navAreaStyle}>
{hasBanner && <div {...stylex.props(styles.banner)}>{banner}</div>}
- {topNavContent}
+ {hasTopNav && (
+ <div ref={topNavRef} style={{display: 'contents'}}>
+ {topNavContent}
+ </div>
+ )}
</XDSLayoutHeader>
) : undefined;
@@ -689,7 +714,9 @@ export function XDSAppShell({
hasDivider={navHasDividers}
isScrollable={isFill}
xstyle={[navAreaStyle, isAuto && styles.panelAutoFill]}>
- {sideNav}
+ <div ref={sideNavRef} style={{display: 'contents'}}>
+ {sideNav}
+ </div>
</XDSLayoutPanel>
) : undefined;
@@ -707,7 +734,8 @@ export function XDSAppShell({
// =========================================================================
// Build main content
// =========================================================================
- const shouldElevateWithCorner = isElevated && hasTopNav && showSideNavInline;
+ const shouldElevateWithCorner =
+ isElevated && hasTopNavContent && showSideNavInline;
const mainInner = (
<XDSLayoutContent
@@ -740,12 +768,12 @@ export function XDSAppShell({
// Injected into the headerContent when mobileNav is enabled and hasToggle
// =========================================================================
const shouldShowAutoToggle =
- mobileNavEnabled && mobileNavHasToggle && isBelowBreakpoint;
+ !mobileNavDisabled && 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 ? (
+ shouldShowAutoToggle && !hasTopNavContent && hasSideNav ? (
<div
{...stylex.props(
isAuto && styles.headerSticky,
@@ -760,7 +788,9 @@ export function XDSAppShell({
role="navigation"
aria-label="Mobile navigation">
<XDSSideNavRenderContext value="topbar">
- {sideNav}
+ <div ref={sideNavRef} style={{display: 'contents'}}>
+ {sideNav}
+ </div>
</XDSSideNavRenderContext>
<XDSMobileNavToggle />
</div>
@@ -811,35 +841,39 @@ export function XDSAppShell({
content={mainContent}
/>
- {/* Mobile nav — rendering modes:
- 1. ReactNode shorthand: render user's element as-is
- 2. Config content: render directly
- 3. TopNav-only: TopNav renders its own drawer
- 4. TopNav+SideNav: TopNav owns drawer, SideNav passed via context
- 5. SideNav-only: SideNav renders its own drawer */}
+ {/* Mobile nav — always mounted below breakpoint via Activity so DOM
+ presence detection works. Hidden until the drawer opens. */}
{shouldRenderMobileNavReactNode && mobileNavReactNode}
{shouldRenderConfigContent && mobileNavConfigContent}
- {shouldRenderTopNavDrawer && (
- <XDSTopNavRenderContext value="drawer">
- {topNav}
- </XDSTopNavRenderContext>
- )}
- {shouldRenderCombinedDrawer && (
- <XDSTopNavMobileContentContext
- value={
- <XDSSideNavRenderContext value="drawer-content">
- {sideNav}
- </XDSSideNavRenderContext>
- }>
- <XDSTopNavRenderContext value="drawer">
- {topNav}
- </XDSTopNavRenderContext>
- </XDSTopNavMobileContentContext>
- )}
- {shouldRenderSideNavDrawer && (
- <XDSSideNavRenderContext value="drawer">
- {sideNav}
- </XDSSideNavRenderContext>
+ {shouldRenderAutoMobileNav && (
+ <ActivityWrapper mode={isMobileNavOpen ? 'visible' : 'hidden'}>
+ {/* SideNav detection — always mounted so presence is known.
+ Hidden when TopNav owns the drawer (combined mode renders
+ sideNav via TopNav's mobile content context instead). */}
+ {hasSideNav && (
+ <div
+ ref={sideNavRef}
+ style={{display: hasTopNavContent ? 'none' : 'contents'}}>
+ <XDSSideNavRenderContext value="drawer">
+ {sideNav}
+ </XDSSideNavRenderContext>
+ </div>
+ )}
+ {hasTopNav && hasTopNavContent && (
+ <XDSTopNavMobileContentContext
+ value={
+ hasSideNavContent ? (
+ <XDSSideNavRenderContext value="drawer-content">
+ {sideNav}
+ </XDSSideNavRenderContext>
+ ) : null
+ }>
+ <XDSTopNavRenderContext value="drawer">
+ {topNav}
+ </XDSTopNavRenderContext>
+ </XDSTopNavMobileContentContext>
+ )}
+ </ActivityWrapper>
)}
</div>
</XDSAppShellMobileContext.Provider>
diff --git a/packages/core/src/AppShell/XDSAppShellSlotPresence.tsx b/packages/core/src/AppShell/XDSAppShellSlotPresence.tsx
new file mode 100644
index 0000000000..c28077032c
--- /dev/null
+++ b/packages/core/src/AppShell/XDSAppShellSlotPresence.tsx
@@ -0,0 +1,89 @@
+'use client';
+
+/**
+ * @file XDSAppShellSlotPresence.tsx
+ * @input Uses React useCallback, useLayoutEffect, 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, useLayoutEffect, 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);
+
+ const check = useCallback(() => {
+ const el = elementRef.current;
+ setHasContent(el ? hasChildContent(el) : false);
+ }, []);
+
+ // 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) {
+ // 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
+ useLayoutEffect(() => {
+ return () => {
+ if (observerRef.current) {
+ observerRef.current.disconnect();
+ }
+ };
+ }, []);
+
+ return {ref, hasContent};
+}
diff --git a/packages/core/src/TopNav/XDSTopNav.tsx b/packages/core/src/TopNav/XDSTopNav.tsx
index c7007c8244..601cb42b75 100644
--- a/packages/core/src/TopNav/XDSTopNav.tsx
+++ b/packages/core/src/TopNav/XDSTopNav.tsx
@@ -178,9 +178,11 @@ export function XDSTopNav({
const hasMobileDrawerContent = hasCollapsibleContent || mobileContent != null;
// =========================================================================
- // Mobile bar mode — heading + endContent + toggle, hide nav items
+ // Mobile bar mode — heading + endContent + toggle, hide nav items.
+ // Falls through to default when there's no drawer content — no reason
+ // to strip down the TopNav if there's nothing to put in the drawer.
// =========================================================================
- if (renderMode === 'mobile-bar') {
+ if (renderMode === 'mobile-bar' && hasMobileDrawerContent) {
return (
<nav
ref={ref}
@@ -196,7 +198,7 @@ export function XDSTopNav({
{heading && <div {...stylex.props(styles.heading)}>{heading}</div>}
<div {...stylex.props(styles.mobileBarEnd)}>
{endContent}
- {hasMobileDrawerContent && <XDSMobileNavToggle />}
+ <XDSMobileNavToggle />
</div>
</nav>
);