An open source design system that's fully customizable and agent ready
TypeScript
feat(AppShell): add XDSAppShell component (#247)
Cindy Zhangb119a50e7357
diff --git a/apps/storybook/stories/AppShell.stories.tsx b/apps/storybook/stories/AppShell.stories.tsxnew file mode 100644index 0000000000..d45223a6f0--- /dev/null+++ b/apps/storybook/stories/AppShell.stories.tsx@@ -0,0 +1,290 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {XDSAppShell} from '@xds/core/AppShell';+import {XDSBanner} from '@xds/core/Banner';+import {XDSButton} from '@xds/core/Button';+import {XDSText} from '@xds/core/Text';+import {XDSTopNav, XDSTopNavTitle, XDSTopNavItem} from '@xds/core/TopNav';+import * as stylex from '@stylexjs/stylex';+import {colorVars, spacingVars} from '@xds/core/theme/tokens.stylex';+import {+ HomeIcon,+ Cog6ToothIcon,+ ChartBarIcon,+ UserCircleIcon,+ Bars3Icon,+} from '@heroicons/react/24/outline';++const styles = stylex.create({+ pageNav: {+ padding: spacingVars['--spacing-4'],+ },+ navItem: {+ display: 'block',+ padding: `${spacingVars['--spacing-2']} ${spacingVars['--spacing-3']}`,+ borderRadius: 6,+ cursor: 'pointer',+ color: colorVars['--color-text-primary'],+ fontSize: 14,+ textDecoration: 'none',+ backgroundColor: {+ default: 'transparent',+ ':hover': colorVars['--color-hover-overlay'],+ },+ },+ navItemActive: {+ backgroundColor: colorVars['--color-accent-deemphasized'],+ color: colorVars['--color-accent-text'],+ },+ content: {+ padding: spacingVars['--spacing-6'],+ },+ longContent: {+ display: 'flex',+ flexDirection: 'column' as const,+ gap: 16,+ },+});++function MockPageNav() {+ return (+ <div {...stylex.props(styles.pageNav)}>+ <a {...stylex.props(styles.navItem, styles.navItemActive)}>Dashboard</a>+ <a {...stylex.props(styles.navItem)}>Analytics</a>+ <a {...stylex.props(styles.navItem)}>Settings</a>+ <a {...stylex.props(styles.navItem)}>Users</a>+ <a {...stylex.props(styles.navItem)}>Reports</a>+ </div>+ );+}++function MockContent({paragraphs = 3}: {paragraphs?: number}) {+ return (+ <div {...stylex.props(styles.content)}>+ <XDSText type="large">Page Content</XDSText>+ <div {...stylex.props(styles.longContent)}>+ {Array.from({length: paragraphs}, (_, i) => (+ <XDSText key={i}>+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do+ eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim+ ad minim veniam, quis nostrud exercitation ullamco laboris.+ </XDSText>+ ))}+ </div>+ </div>+ );+}++const meta: Meta<typeof XDSAppShell> = {+ title: 'Core/XDSAppShell',+ component: XDSAppShell,+ tags: ['autodocs'],+ parameters: {+ layout: 'fullscreen',+ },+ argTypes: {+ height: {+ control: 'radio',+ options: ['fill', 'auto'],+ },+ sideNavBreakpoint: {+ control: 'radio',+ options: ['sm', 'md', 'lg', 'none'],+ },+ sideNavWidth: {+ control: 'number',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSAppShell>;++export const Default: Story = {+ render: () => (+ <XDSAppShell+ topNav={+ <XDSTopNav+ label="Main navigation"+ title={<XDSTopNavTitle title="My App" />}+ startContent={+ <>+ <XDSTopNavItem label="Home" href="#" isSelected />+ <XDSTopNavItem label="Products" href="#" />+ </>+ }+ endContent={+ <XDSButton+ label="Profile"+ variant="ghost"+ icon={<UserCircleIcon style={{width: 16, height: 16}} />}+ />+ }+ />+ }+ sideNav={<MockPageNav />}>+ <MockContent />+ </XDSAppShell>+ ),+};++export const HeaderOnly: Story = {+ render: () => (+ <XDSAppShell+ topNav={+ <XDSTopNav+ label="Main navigation"+ title={<XDSTopNavTitle title="Landing Page" />}+ />+ }>+ <MockContent paragraphs={5} />+ </XDSAppShell>+ ),+};++export const WithBanner: Story = {+ render: () => (+ <XDSAppShell+ topNav={+ <XDSTopNav+ label="Main navigation"+ title={<XDSTopNavTitle title="My App" />}+ startContent={+ <>+ <XDSTopNavItem label="Home" href="#" isSelected />+ <XDSTopNavItem label="Products" href="#" />+ </>+ }+ />+ }+ sideNav={<MockPageNav />}+ banner={+ <XDSBanner+ status="info"+ variant="section"+ title="System maintenance scheduled"+ description="The system will undergo maintenance tonight at 10pm UTC."+ isDismissable+ />+ }>+ <MockContent />+ </XDSAppShell>+ ),+};++export const AutoHeight: Story = {+ render: () => (+ <XDSAppShell+ topNav={+ <XDSTopNav+ label="Main navigation"+ title={<XDSTopNavTitle title="Documentation" />}+ startContent={+ <>+ <XDSTopNavItem+ label="Docs"+ href="#"+ isSelected+ icon={<HomeIcon style={{width: 16, height: 16}} />}+ />+ <XDSTopNavItem+ label="API"+ href="#"+ icon={<ChartBarIcon style={{width: 16, height: 16}} />}+ />+ </>+ }+ />+ }+ sideNav={<MockPageNav />}+ height="auto">+ <MockContent paragraphs={20} />+ </XDSAppShell>+ ),+};++/**+ * Controlled collapse with external state.+ *+ * NOTE: Collapse controls require coordination between the shell and nav —+ * the toggle button lives in the topNav but the collapse state lives in+ * AppShell. This is a known design tension. For now, the toggle is passed+ * as endContent in the topNav.+ */+export const ControlledCollapse: Story = {+ render: function ControlledCollapseStory() {+ const [collapsed, setCollapsed] = useState(false);+ return (+ <XDSAppShell+ topNav={+ <XDSTopNav+ label="Main navigation"+ title={<XDSTopNavTitle title="Controlled" />}+ endContent={+ <XDSButton+ label="Toggle sidebar"+ variant="ghost"+ icon={<Bars3Icon style={{width: 16, height: 16}} />}+ onClick={() => setCollapsed(!collapsed)}+ />+ }+ />+ }+ sideNav={<MockPageNav />}+ isSideNavCollapsed={collapsed}+ onSideNavCollapsedChange={setCollapsed}>+ <MockContent />+ </XDSAppShell>+ );+ },+};++export const InitiallyCollapsed: Story = {+ render: () => (+ <XDSAppShell+ topNav={+ <XDSTopNav+ label="Main navigation"+ title={<XDSTopNavTitle title="Collapsed" />}+ />+ }+ sideNav={<MockPageNav />}+ initialIsSideNavCollapsed={true}>+ <MockContent />+ </XDSAppShell>+ ),+};++export const CustomSideNavWidth: Story = {+ render: () => (+ <XDSAppShell+ topNav={+ <XDSTopNav+ label="Main navigation"+ title={<XDSTopNavTitle title="Wide SideNav" />}+ startContent={+ <>+ <XDSTopNavItem+ label="Settings"+ href="#"+ isSelected+ icon={<Cog6ToothIcon style={{width: 16, height: 16}} />}+ />+ </>+ }+ />+ }+ sideNav={<MockPageNav />}+ sideNavWidth={320}>+ <MockContent />+ </XDSAppShell>+ ),+};++export const ContentOnly: Story = {+ render: () => (+ <XDSAppShell>+ <MockContent paragraphs={5} />+ </XDSAppShell>+ ),+};diff --git a/packages/core/src/AppShell/README.md b/packages/core/src/AppShell/README.mdnew file mode 100644index 0000000000..048044a850--- /dev/null+++ b/packages/core/src/AppShell/README.md@@ -0,0 +1,121 @@+# /packages/core/src/AppShell++Application-level layout shell component.++<!-- SYNC: When files in this directory change, update this document. -->++## Overview++XDSAppShell provides the structural frame for an application: header, side navigation, and main content area. It composes XDSLayout internally and replaces the internal XDSPage + XDSPageLayout pattern.++## Import++```tsx+import {XDSAppShell} from '@xds/core/AppShell';+```++## Usage++```tsx+// Standard app shell — fill mode, sideNav + header+<XDSAppShell+ topNav={<XDSTopNav title="My App" />}+ sideNav={<XDSPageNav items={navItems} />}+ banner={<XDSBanner status="info" title="System update" />}+>+ <DashboardContent />+</XDSAppShell>++// Header only (no sideNav)+<XDSAppShell topNav={<XDSTopNav title="Landing" />}>+ <LandingContent />+</XDSAppShell>++// Auto-height for content-heavy pages+<XDSAppShell+ topNav={<XDSTopNav title="Docs" />}+ sideNav={<XDSPageNav items={docNav} />}+ height="auto"+>+ <LongDocumentContent />+</XDSAppShell>++// Controlled sideNav collapse+<XDSAppShell+ topNav={<XDSTopNav title="App" />}+ sideNav={<XDSPageNav items={navItems} />}+ isSideNavCollapsed={collapsed}+ onSideNavCollapsedChange={setCollapsed}+>+ <Content />+</XDSAppShell>+```++## Props++| Prop | Type | Default | Description |+| --------------------------- | -------------------------------- | -------- | ------------------------------------------- |+| `children` | `ReactNode` | — | Main content area (rendered as `<main>`) |+| `topNav` | `ReactNode` | — | Top navigation slot (typically XDSTopNav) |+| `sideNav` | `ReactNode` | — | Side navigation slot (typically XDSPageNav) |+| `banner` | `ReactNode` | — | Banner slot for system-wide announcements |+| `height` | `'fill' \| 'auto'` | `'fill'` | Height behavior |+| `isSideNavCollapsed` | `boolean` | — | Whether sideNav is collapsed (controlled) |+| `initialIsSideNavCollapsed` | `boolean` | `false` | Initial collapsed state (uncontrolled) |+| `onSideNavCollapsedChange` | `(isCollapsed: boolean) => void` | — | Collapse change callback |+| `sideNavBreakpoint` | `'sm' \| 'md' \| 'lg' \| 'none'` | `'md'` | Breakpoint for auto-collapse |+| `sideNavWidth` | `number` | `260` | SideNav width in pixels |+| `xstyle` | `StyleXStyles` | — | StyleX overrides |+| `data-testid` | `string` | — | Test ID |++## Height Modes++### Fill (default)++- Shell fills viewport (`100dvh`)+- TopNav is pinned at top+- SideNav has its own scroll container+- Content area scrolls independently+- Best for: dashboards, admin panels, tools++### Auto++- Shell grows with content, page scrolls+- TopNav gets `position: sticky; top: 0`+- SideNav gets `position: sticky; top: <header-height>`+- Best for: docs sites, content-heavy pages++## SideNav Behavior++- **Controlled**: Use `isSideNavCollapsed` + `onSideNavCollapsedChange`+- **Uncontrolled**: Use `initialIsSideNavCollapsed`+- **Responsive**: `sideNavBreakpoint` auto-collapses below the specified width+- **Mobile**: Collapsed sideNav renders as an overlay with backdrop+- **Animations**: Snap open/closed for now; ViewTransitions support planned++## Internal Composition++XDSAppShell composes `XDSLayout` internally with:++- `header` → `XDSLayoutHeader` containing topNav + banner+- `start` → `XDSLayoutPanel` containing sideNav+- `content` → `XDSLayoutContent` containing children as `<main>`++This gives automatic padding collapse, scroll containment, and slot awareness.++## Accessibility++- Semantic HTML via XDSLayout slots+- `<main>` has `role="main"` for landmark navigation+- SideNav has `role="navigation"` with `aria-label="Application navigation"`+- Skip-to-content link (visually hidden, shown on focus)+- Escape closes mobile sideNav overlay++## Files++| File | Role | Purpose |+| ---------------------- | --------- | --------------------------- |+| `index.ts` | Entry | Exports component and types |+| `XDSAppShell.tsx` | Component | Main shell implementation |+| `XDSAppShell.test.tsx` | Tests | Unit tests |+| `README.md` | Docs | This documentation |diff --git a/packages/core/src/AppShell/XDSAppShell.test.tsx b/packages/core/src/AppShell/XDSAppShell.test.tsxnew file mode 100644index 0000000000..101f05861a--- /dev/null+++ b/packages/core/src/AppShell/XDSAppShell.test.tsx@@ -0,0 +1,378 @@+/**+ * @file XDSAppShell.test.tsx+ * @input Uses vitest, @testing-library/react, XDSAppShell component+ * @output Unit tests for XDSAppShell component behavior+ * @position Testing; validates XDSAppShell.tsx implementation+ *+ * SYNC: When XDSAppShell.tsx changes, update tests to match new behavior+ */++import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {render, screen, fireEvent, act} from '@testing-library/react';+import {XDSAppShell} from './XDSAppShell';++// Mock ResizeObserver+class MockResizeObserver {+ callback: ResizeObserverCallback;+ constructor(callback: ResizeObserverCallback) {+ this.callback = callback;+ }+ observe() {}+ unobserve() {}+ disconnect() {}+}++vi.stubGlobal('ResizeObserver', MockResizeObserver);++// Mock matchMedia+function createMockMatchMedia(matches: boolean) {+ const listeners: Array<(e: MediaQueryListEvent) => void> = [];+ const mql = {+ matches,+ media: '',+ onchange: null,+ addEventListener: vi.fn(+ (_event: string, handler: (e: MediaQueryListEvent) => void) => {+ listeners.push(handler);+ },+ ),+ removeEventListener: vi.fn(+ (_event: string, handler: (e: MediaQueryListEvent) => void) => {+ const idx = listeners.indexOf(handler);+ if (idx >= 0) listeners.splice(idx, 1);+ },+ ),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ // Expose for test control+ _listeners: listeners,+ _setMatches: (newMatches: boolean) => {+ mql.matches = newMatches;+ for (const listener of listeners) {+ listener({matches: newMatches} as MediaQueryListEvent);+ }+ },+ };+ return mql;+}++let mockMql: ReturnType<typeof createMockMatchMedia>;++beforeEach(() => {+ mockMql = createMockMatchMedia(false);+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue(mockMql));+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('XDSAppShell', () => {+ // ===========================================================================+ // Basic rendering+ // ===========================================================================++ it('renders children as main content', () => {+ render(+ <XDSAppShell>+ <div>Main content</div>+ </XDSAppShell>,+ );+ expect(screen.getByText('Main content')).toBeInTheDocument();+ });++ it('renders main element with role="main"', () => {+ render(+ <XDSAppShell>+ <div>Content</div>+ </XDSAppShell>,+ );+ expect(screen.getByRole('main')).toBeInTheDocument();+ });++ it('renders topNav in the header area', () => {+ render(+ <XDSAppShell topNav={<div>Top Nav</div>}>+ <div>Content</div>+ </XDSAppShell>,+ );+ expect(screen.getByText('Top Nav')).toBeInTheDocument();+ });++ it('renders banner when provided', () => {+ render(+ <XDSAppShell banner={<div>System banner</div>}>+ <div>Content</div>+ </XDSAppShell>,+ );+ expect(screen.getByText('System banner')).toBeInTheDocument();+ });++ it('renders sideNav in a nav element', () => {+ render(+ <XDSAppShell sideNav={<div>Side Nav</div>}>+ <div>Content</div>+ </XDSAppShell>,+ );+ const nav = screen.getByRole('navigation');+ expect(nav).toBeInTheDocument();+ expect(screen.getByText('Side Nav')).toBeInTheDocument();+ });++ it('renders without optional slots', () => {+ render(+ <XDSAppShell>+ <div>Just content</div>+ </XDSAppShell>,+ );+ expect(screen.getByText('Just content')).toBeInTheDocument();+ expect(screen.queryByRole('navigation')).not.toBeInTheDocument();+ });++ it('supports data-testid', () => {+ render(+ <XDSAppShell data-testid="my-shell">+ <div>Content</div>+ </XDSAppShell>,+ );+ expect(screen.getByTestId('my-shell')).toBeInTheDocument();+ });++ // ===========================================================================+ // Skip-to-content link+ // ===========================================================================++ it('renders a skip-to-content link', () => {+ render(+ <XDSAppShell>+ <div>Content</div>+ </XDSAppShell>,+ );+ const skipLink = screen.getByTestId('skip-to-content');+ expect(skipLink).toBeInTheDocument();+ expect(skipLink).toHaveAttribute('href', '#xds-app-shell-main');+ expect(skipLink.textContent).toBe('Skip to content');+ });++ it('main content has the correct id for skip link', () => {+ render(+ <XDSAppShell>+ <div>Content</div>+ </XDSAppShell>,+ );+ const main = screen.getByRole('main');+ expect(main).toHaveAttribute('id', 'xds-app-shell-main');+ });++ // ===========================================================================+ // SideNav accessibility+ // ===========================================================================++ it('sideNav has aria-label', () => {+ render(+ <XDSAppShell sideNav={<div>Nav</div>}>+ <div>Content</div>+ </XDSAppShell>,+ );+ const nav = screen.getByRole('navigation');+ expect(nav).toHaveAttribute('aria-label', 'Application navigation');+ });++ // ===========================================================================+ // SideNav collapse — uncontrolled+ // ===========================================================================++ it('sideNav is visible by default (uncontrolled)', () => {+ render(+ <XDSAppShell sideNav={<div>Nav Items</div>}>+ <div>Content</div>+ </XDSAppShell>,+ );+ expect(screen.getByText('Nav Items')).toBeInTheDocument();+ expect(screen.getByRole('navigation')).toBeInTheDocument();+ });++ it('sideNav is hidden when initialIsSideNavCollapsed is true', () => {+ render(+ <XDSAppShell+ sideNav={<div>Nav Items</div>}+ initialIsSideNavCollapsed={true}>+ <div>Content</div>+ </XDSAppShell>,+ );+ expect(screen.queryByRole('navigation')).not.toBeInTheDocument();+ });++ // ===========================================================================+ // SideNav collapse — controlled+ // ===========================================================================++ it('sideNav is hidden when isSideNavCollapsed is true (controlled)', () => {+ render(+ <XDSAppShell+ sideNav={<div>Nav Items</div>}+ isSideNavCollapsed={true}+ onSideNavCollapsedChange={() => {}}>+ <div>Content</div>+ </XDSAppShell>,+ );+ expect(screen.queryByRole('navigation')).not.toBeInTheDocument();+ });++ it('sideNav is visible when isSideNavCollapsed is false (controlled)', () => {+ render(+ <XDSAppShell+ sideNav={<div>Nav Items</div>}+ isSideNavCollapsed={false}+ onSideNavCollapsedChange={() => {}}>+ <div>Content</div>+ </XDSAppShell>,+ );+ expect(screen.getByRole('navigation')).toBeInTheDocument();+ });++ // ===========================================================================+ // Responsive breakpoint+ // ===========================================================================++ it('auto-collapses sideNav below breakpoint', () => {+ const onChange = vi.fn();+ render(+ <XDSAppShell+ sideNav={<div>Nav</div>}+ sideNavBreakpoint="md"+ onSideNavCollapsedChange={onChange}>+ <div>Content</div>+ </XDSAppShell>,+ );++ // Simulate going below breakpoint+ act(() => {+ mockMql._setMatches(true);+ });++ expect(onChange).toHaveBeenCalledWith(true);+ });++ it('does not auto-collapse when sideNavBreakpoint is none', () => {+ const onChange = vi.fn();+ render(+ <XDSAppShell+ sideNav={<div>Nav</div>}+ sideNavBreakpoint="none"+ onSideNavCollapsedChange={onChange}>+ <div>Content</div>+ </XDSAppShell>,+ );++ expect(window.matchMedia).not.toHaveBeenCalled();+ });++ // ===========================================================================+ // Mobile overlay+ // ===========================================================================++ it('shows overlay sideNav when below breakpoint and not collapsed', () => {+ // Start below breakpoint with sideNav expanded+ mockMql = createMockMatchMedia(true);+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue(mockMql));++ render(+ <XDSAppShell+ sideNav={<div>Nav Items</div>}+ isSideNavCollapsed={false}+ onSideNavCollapsedChange={() => {}}>+ <div>Content</div>+ </XDSAppShell>,+ );++ // Should show backdrop+ expect(screen.getByTestId('sidenav-backdrop')).toBeInTheDocument();+ // Should show nav in overlay+ expect(screen.getByText('Nav Items')).toBeInTheDocument();+ });++ it('clicking backdrop calls onSideNavCollapsedChange', () => {+ mockMql = createMockMatchMedia(true);+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue(mockMql));++ const onChange = vi.fn();+ render(+ <XDSAppShell+ sideNav={<div>Nav</div>}+ isSideNavCollapsed={false}+ onSideNavCollapsedChange={onChange}>+ <div>Content</div>+ </XDSAppShell>,+ );++ fireEvent.click(screen.getByTestId('sidenav-backdrop'));+ expect(onChange).toHaveBeenCalledWith(true);+ });++ it('pressing Escape closes mobile overlay', () => {+ mockMql = createMockMatchMedia(true);+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue(mockMql));++ const onChange = vi.fn();+ render(+ <XDSAppShell+ sideNav={<div>Nav</div>}+ isSideNavCollapsed={false}+ onSideNavCollapsedChange={onChange}>+ <div>Content</div>+ </XDSAppShell>,+ );++ fireEvent.keyDown(document, {key: 'Escape'});+ expect(onChange).toHaveBeenCalledWith(true);+ });++ // ===========================================================================+ // Height modes+ // ===========================================================================++ it('defaults to fill mode', () => {+ render(+ <XDSAppShell data-testid="shell">+ <div>Content</div>+ </XDSAppShell>,+ );+ // The root element should exist (fill is default)+ expect(screen.getByTestId('shell')).toBeInTheDocument();+ });++ it('supports auto height mode', () => {+ render(+ <XDSAppShell height="auto" data-testid="shell">+ <div>Content</div>+ </XDSAppShell>,+ );+ expect(screen.getByTestId('shell')).toBeInTheDocument();+ });++ it('renders topNav in auto mode', () => {+ render(+ <XDSAppShell height="auto" topNav={<div>Nav</div>} data-testid="shell">+ <div>Content</div>+ </XDSAppShell>,+ );+ expect(screen.getByText('Nav')).toBeInTheDocument();+ });++ // ===========================================================================+ // Ref forwarding+ // ===========================================================================++ it('forwards ref to root element', () => {+ const ref = vi.fn();+ render(+ <XDSAppShell ref={ref} data-testid="shell">+ <div>Content</div>+ </XDSAppShell>,+ );+ expect(ref).toHaveBeenCalled();+ expect(ref.mock.calls[0][0]).toBe(screen.getByTestId('shell'));+ });+});diff --git a/packages/core/src/AppShell/XDSAppShell.tsx b/packages/core/src/AppShell/XDSAppShell.tsxnew file mode 100644index 0000000000..916f3b3504--- /dev/null+++ b/packages/core/src/AppShell/XDSAppShell.tsx@@ -0,0 +1,442 @@+/**+ * @file XDSAppShell.tsx+ * @input Uses React, XDSLayout, XDSLayoutHeader, XDSLayoutPanel, XDSLayoutContent, StyleX+ * @output Exports XDSAppShell component and XDSAppShellProps type+ * @position Application-level layout shell — the top-level wrapper for any app.+ * Composes XDSLayout internally to provide header, sideNav, and main content areas.+ * Use for any app that needs a top nav, side navigation, and scrollable content.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/AppShell/README.md+ * - /packages/core/src/AppShell/index.ts+ * - /packages/core/src/AppShell/XDSAppShell.test.tsx+ * - /apps/storybook/stories/AppShell.stories.tsx+ */++import {+ forwardRef,+ useCallback,+ useEffect,+ useState,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {StyleXStyles} from '@stylexjs/stylex';+import {colorVars, fontWeightVars, textSizeVars} from '../theme/tokens.stylex';+import {XDSLayout} from '../Layout/XDSLayout';+import {XDSLayoutHeader} from '../Layout/XDSLayoutHeader';+import {XDSLayoutPanel} from '../Layout/XDSLayoutPanel';+import {XDSLayoutContent} from '../Layout/XDSLayoutContent';++// =============================================================================+// Constants+// =============================================================================++const DEFAULT_SIDENAV_WIDTH = 260;++const BREAKPOINT_VALUES: Record<XDSAppShellBreakpoint, number> = {+ sm: 640,+ md: 768,+ lg: 1024,+ none: 0,+};++const MAIN_CONTENT_ID = 'xds-app-shell-main';++// =============================================================================+// Types+// =============================================================================++/**+ * SideNav breakpoint options.+ * - `sm`: 640px+ * - `md`: 768px+ * - `lg`: 1024px+ * - `none`: Never auto-collapse+ */+export type XDSAppShellBreakpoint = 'sm' | 'md' | 'lg' | 'none';++export interface XDSAppShellProps {+ /**+ * Optional banner slot for system-wide announcements.+ * Renders above the top nav and scrolls away with the page in auto mode.+ */+ banner?: ReactNode;++ /**+ * Main content area (rendered as `<main>`).+ */+ children: ReactNode;++ /**+ * Test ID for the root element.+ */+ 'data-testid'?: string;++ /**+ * Height behavior:+ * - `fill`: Shell fills viewport, content scrolls internally (default)+ * - `auto`: Shell grows with content, page scrolls as a whole+ * @default 'fill'+ */+ height?: 'fill' | 'auto';++ /**+ * Initial collapsed state for uncontrolled usage.+ * @default false+ */+ initialIsSideNavCollapsed?: boolean;++ /**+ * Whether the side nav is collapsed (controlled).+ */+ isSideNavCollapsed?: boolean;++ /**+ * Callback when side nav collapsed state changes.+ */+ onSideNavCollapsedChange?: (isCollapsed: boolean) => void;++ /**+ * Side navigation — typically an XDSPageNav.+ */+ sideNav?: ReactNode;++ /**+ * Breakpoint below which side nav auto-collapses.+ * @default 'md'+ */+ sideNavBreakpoint?: XDSAppShellBreakpoint;++ /**+ * Width of side nav when expanded (in pixels).+ * @default 260+ */+ sideNavWidth?: number;++ /**+ * Top navigation — typically an XDSTopNav.+ */+ topNav?: ReactNode;++ /**+ * StyleX overrides for the root element.+ */+ xstyle?: StyleXStyles;+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ root: {+ display: 'flex',+ flexDirection: 'column',+ position: 'relative',+ },+ rootFill: {+ height: '100dvh',+ overflow: 'hidden',+ },+ rootAuto: {+ minHeight: '100dvh',+ },+ skipLink: {+ position: 'absolute',+ top: 0,+ left: 0,+ padding: '8px 16px',+ backgroundColor: colorVars['--color-surface'],+ color: colorVars['--color-accent-text'],+ zIndex: 9999,+ textDecoration: 'none',+ fontWeight: fontWeightVars['--font-weight-semibold'],+ fontSize: textSizeVars['--text-base'],+ // Visually hidden by default+ transform: 'translateY(-100%)',+ // Show on focus+ ':focus': {+ transform: 'translateY(0)',+ },+ },+ banner: {+ flexShrink: 0,+ },+ // Mobile overlay sideNav+ overlay: {+ position: 'fixed',+ inset: 0,+ zIndex: 100,+ display: 'flex',+ },+ backdrop: {+ position: 'fixed',+ inset: 0,+ backgroundColor: colorVars['--color-overlay'],+ zIndex: 100,+ },+ overlaySideNav: {+ position: 'relative',+ zIndex: 101,+ backgroundColor: colorVars['--color-surface'],+ overflow: 'auto',+ height: '100%',+ borderInlineEndWidth: 1,+ borderInlineEndStyle: 'solid',+ borderInlineEndColor: colorVars['--color-divider'],+ },+ hidden: {+ display: 'none',+ },+});++const dynamicStyles = stylex.create({+ sideNavWidth: (width: number) => ({+ width,+ }),+});++// =============================================================================+// Component+// =============================================================================++/**+ * Application-level layout shell. Provides the structural frame for an app:+ * header, side navigation, and main content area.+ *+ * Composes XDSLayout internally. Replaces internal XDSPage + XDSPageLayout pattern.+ *+ * Features:+ * - Slot-based API: `topNav`, `sideNav`, `banner`, `children`+ * - Two height modes: `fill` (100dvh, independent scroll) and `auto` (page scroll, sticky navs)+ * - SideNav collapse: controlled + uncontrolled patterns+ * - Responsive sideNav collapse via breakpoint+ * - Mobile overlay sideNav with backdrop+ * - Skip-to-content link+ * - Semantic HTML: `<header>`, `<nav>`, `<main>`+ *+ * @example+ * ```tsx+ * // Standard app shell — fill mode, sideNav + header+ * <XDSAppShell+ * topNav={<XDSTopNav title="My App" />}+ * sideNav={<XDSPageNav items={navItems} />}+ * >+ * <DashboardContent />+ * </XDSAppShell>+ *+ * // Header only (no sideNav)+ * <XDSAppShell topNav={<XDSTopNav title="Landing" />}>+ * <LandingContent />+ * </XDSAppShell>+ *+ * // Auto-height for content-heavy pages+ * <XDSAppShell+ * topNav={<XDSTopNav title="Docs" />}+ * sideNav={<XDSPageNav items={docNav} />}+ * height="auto"+ * >+ * <LongDocumentContent />+ * </XDSAppShell>+ * ```+ */+export const XDSAppShell = forwardRef<HTMLDivElement, XDSAppShellProps>(+ function XDSAppShell(+ {+ banner,+ children,+ 'data-testid': dataTestId,+ height = 'fill',+ initialIsSideNavCollapsed = false,+ isSideNavCollapsed: controlledCollapsed,+ onSideNavCollapsedChange,+ sideNav,+ sideNavBreakpoint = 'md',+ sideNavWidth = DEFAULT_SIDENAV_WIDTH,+ topNav,+ xstyle,+ },+ ref,+ ) {+ // =========================================================================+ // SideNav collapse state (controlled + uncontrolled)+ // =========================================================================+ const isControlled = controlledCollapsed !== undefined;+ const [uncontrolledCollapsed, setUncontrolledCollapsed] = useState(+ initialIsSideNavCollapsed,+ );+ const isCollapsed = isControlled+ ? controlledCollapsed+ : uncontrolledCollapsed;++ // Track whether we're below the breakpoint+ const [isBelowBreakpoint, setIsBelowBreakpoint] = useState(false);++ const isFill = height === 'fill';+ const hasSideNav = sideNav != null;+ const hasTopNav = topNav != null;+ const hasBanner = banner != null;++ // =========================================================================+ // Responsive breakpoint handling+ //+ // Uses matchMedia which is event-driven — the listener only fires when the+ // media query match state actually changes, not on every resize. This is+ // efficient and does not over-trigger.+ // =========================================================================+ useEffect(() => {+ if (sideNavBreakpoint === 'none' || !hasSideNav) return;++ const breakpointPx = BREAKPOINT_VALUES[sideNavBreakpoint];+ const mql = window.matchMedia(`(max-width: ${breakpointPx}px)`);++ const handleChange = (e: MediaQueryListEvent | MediaQueryList) => {+ const matches = 'matches' in e ? e.matches : false;+ setIsBelowBreakpoint(matches);+ if (matches) {+ // Auto-collapse below breakpoint+ if (!isControlled) {+ setUncontrolledCollapsed(true);+ }+ onSideNavCollapsedChange?.(true);+ }+ };++ // Check initial state+ handleChange(mql);++ mql.addEventListener('change', handleChange);+ return () => mql.removeEventListener('change', handleChange);+ }, [sideNavBreakpoint, hasSideNav, isControlled, onSideNavCollapsedChange]);++ // =========================================================================+ // Toggle handler — snaps open/closed (no transitions for now)+ // TODO: Add ViewTransitions support with React transition API+ // =========================================================================+ const handleToggleCollapse = useCallback(() => {+ const newValue = !isCollapsed;+ if (!isControlled) {+ setUncontrolledCollapsed(newValue);+ }+ onSideNavCollapsedChange?.(newValue);+ }, [isCollapsed, isControlled, onSideNavCollapsedChange]);++ // =========================================================================+ // Close mobile sideNav on Escape+ // =========================================================================+ useEffect(() => {+ if (!isBelowBreakpoint || isCollapsed) return;++ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ handleToggleCollapse();+ }+ };++ document.addEventListener('keydown', handleKeyDown);+ return () => document.removeEventListener('keydown', handleKeyDown);+ }, [isBelowBreakpoint, isCollapsed, handleToggleCollapse]);++ // =========================================================================+ // Determine if sideNav should show as overlay (mobile) or inline+ // =========================================================================+ const showSideNavInline = hasSideNav && !isCollapsed && !isBelowBreakpoint;+ const showSideNavOverlay = hasSideNav && !isCollapsed && isBelowBreakpoint;++ // =========================================================================+ // Build header content (topNav + banner)+ // =========================================================================+ const headerContent =+ hasTopNav || hasBanner ? (+ <XDSLayoutHeader isFullBleed hasDivider={hasTopNav}>+ {hasBanner && <div {...stylex.props(styles.banner)}>{banner}</div>}+ {hasTopNav && topNav}+ </XDSLayoutHeader>+ ) : undefined;++ // =========================================================================+ // Build sideNav content+ // =========================================================================+ const sideNavContent = showSideNavInline ? (+ <XDSLayoutPanel+ isFullBleed+ hasDivider+ width={sideNavWidth}+ role="navigation"+ label="Application navigation"+ isScrollable={isFill}>+ {sideNav}+ </XDSLayoutPanel>+ ) : undefined;++ // =========================================================================+ // Build main content+ // =========================================================================+ const mainContent = (+ <XDSLayoutContent+ isFullBleed+ role="main"+ id={MAIN_CONTENT_ID}+ isScrollable={isFill}>+ {children}+ </XDSLayoutContent>+ );++ // =========================================================================+ // Render+ //+ // TODO: Include root providers (ThemeProvider, ProseProvider, LayerProvider)+ // at the app level once they're available for wrapping.+ // =========================================================================+ return (+ <div+ ref={ref}+ data-testid={dataTestId}+ {...stylex.props(+ styles.root,+ isFill ? styles.rootFill : styles.rootAuto,+ xstyle,+ )}>+ {/* 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}+ isFullBleed+ header={headerContent}+ start={sideNavContent}+ content={mainContent}+ />++ {/* Mobile overlay sideNav */}+ {showSideNavOverlay && (+ <>+ <div+ {...stylex.props(styles.backdrop)}+ onClick={handleToggleCollapse}+ data-testid="sidenav-backdrop"+ aria-hidden="true"+ />+ <nav+ aria-label="Application navigation"+ {...stylex.props(+ styles.overlaySideNav,+ dynamicStyles.sideNavWidth(sideNavWidth),+ )}>+ {sideNav}+ </nav>+ </>+ )}+ </div>+ );+ },+);++XDSAppShell.displayName = 'XDSAppShell';diff --git a/packages/core/src/AppShell/index.ts b/packages/core/src/AppShell/index.tsnew file mode 100644index 0000000000..ce183c4859--- /dev/null+++ b/packages/core/src/AppShell/index.ts@@ -0,0 +1,11 @@+/**+ * @file index.ts+ * @input Imports XDSAppShell component and types from XDSAppShell.tsx+ * @output Exports XDSAppShell and related types+ * @position Component entry point; re-exported by /packages/core/src/index.ts+ *+ * SYNC: When modified, update this header and /packages/core/src/AppShell/README.md+ */++export {XDSAppShell} from './XDSAppShell';+export type {XDSAppShellProps, XDSAppShellBreakpoint} from './XDSAppShell';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 8f3305a27c..d0a30a2840 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -8,6 +8,7 @@*/// Components+export * from './AppShell';export * from './AspectRatio';export * from './Avatar';export * from './Badge';