Navigation · Material 3: Navigation drawer and rail (app shell)
Sidebar
The app shell's navigation column, built on Navigation. Collapses from drawer to rail on desktop (⌘B); opens as a Sheet on phones.
Examples and variants
Collapsible
Collapse with the trigger or ⌘B. Narrow the window to see the phone Sheet.
Press the trigger (or ⌘B) to collapse to a rail.
function SidebarShell() {
const [active, setActive] = useState("Home")
const items = [
{ label: "Home", icon: <HomeIcon /> },
{ label: "Inbox", icon: <InboxIcon /> },
{ label: "Projects", icon: <FolderIcon /> },
{ label: "Settings", icon: <SettingsIcon /> },
]
return (
<SidebarProvider className="h-80 min-h-0 w-full max-w-xl overflow-hidden rounded-(--shape-lg) shadow-1">
<Sidebar className="static h-full">
<SidebarHeader className="px-2">
<span className="inline-flex size-8 shrink-0 items-center justify-center rounded-(--shape-md) bg-primary text-sm font-semibold text-primary-foreground">N</span>
<SidebarLabel className="font-medium">Northwind</SidebarLabel>
</SidebarHeader>
<SidebarNav>
{items.map((item) => (
<NavigationItem
key={item.label}
href="#"
icon={item.icon}
label={item.label}
active={active === item.label}
onClick={(event) => {
event.preventDefault()
setActive(item.label)
}}
/>
))}
</SidebarNav>
</Sidebar>
<SidebarInset className="bg-canvas p-3">
<div className="flex items-center gap-2">
<SidebarTrigger />
<span className="text-sm font-medium">{active}</span>
</div>
<p className="mt-3 text-sm text-muted-foreground">Press the trigger (or ⌘B) to collapse to a rail.</p>
</SidebarInset>
</SidebarProvider>
)
}Spec drawing
Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.
Install
With the CLI
The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/sidebar.json
npx shadcn@latest add https://isotopi.com/r/navigation.json
npx shadcn@latest add https://isotopi.com/r/sheet.jsonBy hand
No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.
Install the packages it uses.
Terminalnpm install @base-ui/react class-variance-authority cn lucide-reactCopy these 4 files to the same paths in your project. Imports use the
@/alias for your project root.components/ui/button.tsxbutton
components/ui/button.tsx"use client" import { useRef, useState } from "react" import { Button as ButtonPrimitive } from "@base-ui/react/button" import { CheckIcon, XIcon } from "lucide-react" import { tokenMs } from "@/lib/motion/token-ms" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "cn" // Minimal: no strokes on controls (DESIGN.md rule 11), token sizes, token focus ring, // liquid press squash instead of shadcn's translate-y nudge. // Every visual spec reads a component token (styles/tokens/components.css, --button-*). // Sizes: sm | md | lg (default = md). Variants: primary (default) | secondary | outline | ghost | link. const filled = { primary: "bg-(--button-primary-container) text-(--button-primary-label) hover:bg-(--button-primary-container-hover) active:bg-(--button-primary-container-pressed)", secondary: "bg-(--button-secondary-container) text-(--button-secondary-label) hover:bg-(--button-secondary-container-hover) active:bg-(--button-secondary-container-pressed) aria-expanded:bg-(--button-secondary-container-hover)", } const buttonVariants = cva( "liquid-press group/button relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-(--button-corner) border-solid border-(length:--button-stroke-width) border-(--stroke-color-default) bg-clip-padding text-(length:--button-label-size) [font-weight:var(--button-label-weight)] whitespace-nowrap outline-none select-none focus-visible:shadow-(--focus-ring) disabled:pointer-events-none disabled:bg-(--button-container-disabled) disabled:text-(--button-label-disabled) disabled:shadow-none aria-invalid:shadow-(--focus-ring-invalid) [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-(--button-icon-size)", { variants: { variant: { primary: filled.primary, default: filled.primary, secondary: filled.secondary, outline: "bg-(--button-outline-container) text-(--button-secondary-label) shadow-(--button-outline-elevation) hover:bg-(--button-outline-container-hover) active:bg-(--button-outline-container-pressed) aria-expanded:bg-(--button-outline-container-hover)", ghost: "text-(--button-secondary-label) hover:bg-(--button-ghost-container-hover) active:bg-(--button-ghost-container-pressed) aria-expanded:bg-(--button-ghost-container-hover) disabled:bg-transparent", destructive: "", link: "text-(--button-link-label) underline-offset-4 hover:underline disabled:bg-transparent", }, size: { xs: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-xs) gap-(--button-gap-sm) px-(--button-padding-x-xs) text-(length:--button-label-size-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", sm: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-sm) gap-(--button-gap-sm) px-(--button-padding-x-sm) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", md: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)", default: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-md) gap-(--button-gap) px-(--button-padding-x-md) has-data-[icon=inline-end]:pe-(--button-padding-x-sm) has-data-[icon=inline-start]:ps-(--button-padding-x-sm)", lg: "active:not-disabled:rounded-(--button-corner-pressed) h-(--button-height-lg) gap-(--button-gap) px-(--button-padding-x-lg) has-data-[icon=inline-end]:pe-(--button-padding-x-md) has-data-[icon=inline-start]:ps-(--button-padding-x-md) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)", icon: "size-(--icon-button-size-md) rounded-(--icon-button-corner)", "icon-xs": "size-(--button-height-xs) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", "icon-sm": "size-(--icon-button-size-sm) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-sm)", "icon-md": "size-(--icon-button-size-md) rounded-(--icon-button-corner)", "icon-lg": "size-(--icon-button-size-lg) rounded-(--icon-button-corner) [&_svg:not([class*='size-'])]:size-(--button-icon-size-lg)", }, tone: { neutral: "", danger: "", success: "", }, }, // tone: colour intent on any variant (component-model.md §7). destructive = tone danger. compoundVariants: [ { tone: "danger", variant: ["primary", "default", "secondary", "outline", "destructive"], className: "bg-(--button-danger-container) text-(--button-danger-label) shadow-none hover:bg-(--button-danger-container-hover) active:bg-(--button-danger-container-pressed) [--focus-ring-color:var(--color-danger)]", }, { tone: "danger", variant: ["ghost", "link"], className: "text-(--button-danger-label) hover:bg-(--button-danger-container) active:bg-(--button-danger-container-hover) [--focus-ring-color:var(--color-danger)]", }, { tone: "success", variant: ["primary", "default", "secondary", "outline"], className: "bg-(--button-success-container) text-(--button-success-label) shadow-none hover:bg-(--button-success-container-hover) active:bg-(--button-success-container-pressed)", }, ], defaultVariants: { variant: "primary", size: "md", tone: "neutral", }, } ) type Wash = { id: number; x: number; y: number } type Status = "idle" | "loading" | "success" | "error" type ButtonProps = ButtonPrimitive.Props & VariantProps<typeof buttonVariants> & { /** * The button shows its own result inside a fixed width: spinner, then a * check or a cross. Prefer this to a toast (component-model.md §5). */ status?: Status /** "hold": the click only happens after holding for --duration-fill (pointer, Space or Enter). */ confirm?: "hold" /** Screen reader text for the success and error states. */ statusLabel?: { success?: string; error?: string } /** @deprecated use status="loading" */ loading?: boolean /** @deprecated use status="success" */ success?: boolean } function Button({ className, variant = "primary", size = "md", tone = "neutral", status: statusProp, confirm, statusLabel, loading = false, success = false, children, onClick, onPointerUp, onPointerDown, onPointerLeave, onKeyDown, onKeyUp, ...props }: ButtonProps) { const status: Status = statusProp ?? (loading ? "loading" : success ? "success" : "idle") const busy = status === "loading" const [wash, setWash] = useState<Wash | null>(null) const [held, setHeld] = useState(false) const holdTimer = useRef(0) const allowClick = useRef(false) const self = useRef<HTMLElement | null>(null) const resolvedTone = variant === "destructive" ? "danger" : tone function startHold(element: HTMLElement) { if (confirm !== "hold" || busy) return self.current = element setHeld(true) window.clearTimeout(holdTimer.current) holdTimer.current = window.setTimeout(() => { setHeld(false) allowClick.current = true self.current?.click() allowClick.current = false }, tokenMs("--duration-fill", element)) } function stopHold() { if (confirm !== "hold") return setHeld(false) window.clearTimeout(holdTimer.current) } function handleClick(event: Parameters<NonNullable<ButtonProps["onClick"]>>[0]) { if (busy || (confirm === "hold" && !allowClick.current)) { event.preventDefault() return } onClick?.(event) } function handlePointerUp(event: Parameters<NonNullable<ButtonProps["onPointerUp"]>>[0]) { onPointerUp?.(event) stopHold() if (event.defaultPrevented || busy || confirm === "hold") return if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return const motion = event.currentTarget.closest<HTMLElement>("[data-motion]")?.dataset.motion if (motion === "calm" || motion === "still") return const rect = event.currentTarget.getBoundingClientRect() setWash({ id: Date.now(), x: event.clientX - rect.left, y: event.clientY - rect.top, }) } const showResult = status === "success" || status === "error" return ( <ButtonPrimitive data-slot="button" data-icon={typeof size === "string" && size.startsWith("icon") ? "" : undefined} data-tone={resolvedTone} data-status={status} data-confirm={confirm} aria-busy={busy || undefined} aria-disabled={busy || undefined} {...props} className={cn( buttonVariants({ variant, size, tone: resolvedTone, className }), status === "error" && "animate-[isotope-nudge_var(--duration-fast)_var(--ease-out)]" )} onClick={handleClick} onPointerUp={handlePointerUp} onPointerDown={(event) => { onPointerDown?.(event) if (event.button === 0) startHold(event.currentTarget) }} onPointerLeave={(event) => { onPointerLeave?.(event) stopHold() }} onKeyDown={(event) => { onKeyDown?.(event) if (confirm === "hold" && (event.key === " " || event.key === "Enter") && !event.repeat) { startHold(event.currentTarget) } }} onKeyUp={(event) => { onKeyUp?.(event) if (event.key === " " || event.key === "Enter") stopHold() }} > {confirm === "hold" ? ( <span aria-hidden data-held={held ? "" : undefined} className="hold-fill pointer-events-none absolute inset-y-0 left-0 w-full bg-current opacity-20" /> ) : null} <span className={cn( "button-label relative inline-flex items-center justify-center gap-[inherit]", (busy || showResult) && "opacity-0 blur-(--motion-blur-enter) transition-[opacity,filter] duration-(--duration-fast) ease-(--ease-out)" )} > {children} {confirm === "hold" ? <span className="sr-only">(hold to confirm)</span> : null} </span> {showResult ? ( <span className="button-success absolute inset-0 inline-flex items-center justify-center" role="status"> <span className="sr-only"> {status === "success" ? statusLabel?.success ?? "Done" : statusLabel?.error ?? "Failed"} </span> {status === "success" ? <CheckIcon aria-hidden /> : <XIcon aria-hidden />} </span> ) : null} {busy ? ( <span className="absolute inset-0 inline-flex items-center justify-center gap-inline-xs"> <span className="sr-only">Loading</span> {[0, 1, 2].map((dot) => ( <span key={dot} aria-hidden className="size-inline-xs rounded-full bg-current animate-[isotope-pulse_var(--duration-pulse)_var(--ease-out)_infinite]" style={{ animationDelay: `calc(var(--duration-stagger) * ${dot})` }} /> ))} </span> ) : null} {wash ? ( <span key={wash.id} aria-hidden onAnimationEnd={() => setWash(null)} className="pointer-events-none absolute size-[calc(var(--size-control-lg)*4)] rounded-full bg-current animate-[isotope-wash_var(--duration-settle)_var(--ease-out)_both]" style={{ left: wash.x, top: wash.y }} /> ) : null} </ButtonPrimitive> ) } export { Button, buttonVariants } export type { ButtonProps }components/ui/navigation.tsxnavigation
components/ui/navigation.tsx"use client" import * as React from "react" import { cn } from "cn" import { layoutTop } from "@/lib/motion/layout-offset" /* Navigation: one component for the app's main destinations (Material 3's navigation bar, rail and drawer). The items stay the same; the layout changes with the variant: - bar: bottom of the screen on phones, icons with short labels. - rail: a narrow column on tablets, icons over labels. - drawer: a wide column on desktop, icon and label in a row. The active indicator slides between items on a spring. */ type Variant = "bar" | "rail" | "drawer" const VariantContext = React.createContext<Variant>("drawer") function Navigation({ className, variant = "drawer", children, "aria-label": label = "Main", ...props }: React.ComponentProps<"nav"> & { variant?: Variant }) { const listRef = React.useRef<HTMLUListElement>(null) const [box, setBox] = React.useState<{ top: number; left: number; width: number; height: number } | null>(null) React.useLayoutEffect(() => { const list = listRef.current if (!list) return const measure = () => { // Bar and rail: the pill wraps the icon. Drawer: the whole row. const active = list.querySelector<HTMLElement>("[aria-current=page] [data-slot=navigation-indicator-anchor]") ?? list.querySelector<HTMLElement>("[aria-current=page]") if (!active) return setBox(null) const listBox = list.getBoundingClientRect() const box = active.getBoundingClientRect() // Horizontal from the box (items reflow between variants); vertical from layout. setBox({ top: layoutTop(active, list), left: box.left - listBox.left, width: active.offsetWidth, height: active.offsetHeight }) } measure() const observer = new MutationObserver(measure) observer.observe(list, { subtree: true, attributes: true, attributeFilter: ["aria-current"] }) const resize = new ResizeObserver(measure) resize.observe(list) return () => { observer.disconnect() resize.disconnect() } }, [variant]) return ( <VariantContext.Provider value={variant}> <nav data-slot="navigation" data-variant={variant} aria-label={label} className={cn( "bg-(--nav-container)", variant === "bar" && "h-(--nav-bar-height) w-full px-2", variant === "rail" && "w-(--nav-rail-width) py-3", variant === "drawer" && "w-(--nav-drawer-width) p-3", className )} {...props} > <ul ref={listRef} className={cn("relative flex", variant === "bar" ? "h-full items-center justify-around" : "flex-col gap-1", variant === "rail" && "items-center")}> {box ? ( <span aria-hidden className="navigation-indicator pointer-events-none absolute rounded-(--nav-item-corner) bg-(--nav-item-active)" style={{ top: box.top, left: box.left, width: box.width, height: box.height }} /> ) : null} {children} </ul> </nav> </VariantContext.Provider> ) } function NavigationItem({ className, icon, label, active = false, badge, render, ...props }: Omit<React.ComponentProps<"a">, "children"> & { icon: React.ReactNode label: string active?: boolean badge?: React.ReactNode /** Render as your router's link: render={<Link href="/inbox" />}. */ render?: React.ReactElement<Record<string, unknown>> }) { const variant = React.useContext(VariantContext) const stacked = variant !== "drawer" const content = ( <> <span data-slot={stacked ? "navigation-indicator-anchor" : undefined} className={cn( "relative z-[1] inline-flex items-center justify-center [&_svg]:size-(--size-icon-lg)", stacked && "h-(--size-control-sm) w-14 rounded-(--nav-item-corner)" )} > {icon} {badge && stacked ? <span className="absolute -top-0.5 right-2">{badge}</span> : null} </span> <span className={cn("relative z-[1]", stacked ? "text-caption normal-case" : "text-sm")}>{label}</span> {badge && !stacked ? <span className="relative z-[1] ms-auto">{badge}</span> : null} </> ) const itemClass = cn( "flex outline-none focus-visible:shadow-(--focus-ring) text-muted-foreground hover:text-foreground aria-[current=page]:text-(--nav-item-active-label) aria-[current=page]:font-medium", stacked ? "flex-col items-center gap-1 rounded-(--shape-md) px-1 py-1" : "h-(--nav-item-height) items-center gap-3 rounded-(--nav-item-corner) px-4 hover:bg-(--nav-item-container-hover) active:bg-(--nav-item-container-pressed)", className ) const shared = { "data-slot": "navigation-item", "aria-current": active ? ("page" as const) : undefined, className: itemClass } return ( <li className={cn(variant === "bar" && "flex-1", "flex justify-center", variant === "drawer" && "block")}> {render ? React.cloneElement(render, { ...shared, ...props, children: content }) : <a {...shared} {...props}>{content}</a>} </li> ) } export { Navigation, NavigationItem }components/ui/sheet.tsxsheet
components/ui/sheet.tsx"use client" import * as React from "react" import { Dialog as DialogPrimitive } from "@base-ui/react/dialog" import { Drawer as DrawerPrimitive } from "@base-ui/react/drawer" import { cn } from "cn" import { usePortalMotion } from "@/lib/overlay" /* One Sheet for every panel that slides in from an edge (component-model.md §3). - side: start | end | top | bottom (logical, mirrors in RTL) - draggable: bottom sheets you can drag, flick and snap (phones). Uses Base UI Drawer. - modal={false}: no scrim, the page stays usable (a side panel next to content). Not for a short list of actions: use a Menu from the button. Drawer* exports are presets of this component for shadcn compatibility. */ type Side = "start" | "end" | "top" | "bottom" | "left" | "right" const SheetContext = React.createContext<{ draggable: boolean }>({ draggable: false }) type SheetProps = DialogPrimitive.Root.Props & { /** * modal (default): slides in from `side` with a scrim. * draggable: a bottom sheet that follows the finger, flicks closed and snaps. */ variant?: "modal" | "draggable" /** @deprecated use variant="draggable" */ draggable?: boolean /** Snap points for draggable sheets, as fractions of the sheet height. */ snapPoints?: DrawerPrimitive.Root.Props["snapPoints"] } function Sheet({ variant = "modal", draggable: legacyDraggable, snapPoints, ...props }: SheetProps) { const draggable = variant === "draggable" || legacyDraggable === true return ( <SheetContext.Provider value={{ draggable }}> {draggable ? ( <DrawerPrimitive.Root snapPoints={snapPoints} {...(props as DrawerPrimitive.Root.Props)} /> ) : ( <DialogPrimitive.Root {...props} /> )} </SheetContext.Provider> ) } function SheetTrigger(props: DialogPrimitive.Trigger.Props) { const { draggable } = React.useContext(SheetContext) return draggable ? ( <DrawerPrimitive.Trigger data-slot="sheet-trigger" {...(props as DrawerPrimitive.Trigger.Props)} /> ) : ( <DialogPrimitive.Trigger data-slot="sheet-trigger" {...props} /> ) } function SheetClose(props: DialogPrimitive.Close.Props) { const { draggable } = React.useContext(SheetContext) return draggable ? ( <DrawerPrimitive.Close data-slot="sheet-close" {...(props as DrawerPrimitive.Close.Props)} /> ) : ( <DialogPrimitive.Close data-slot="sheet-close" {...props} /> ) } function SheetTitle({ className, ...props }: DialogPrimitive.Title.Props) { const { draggable } = React.useContext(SheetContext) const Title = draggable ? DrawerPrimitive.Title : DialogPrimitive.Title return <Title className={cn("text-title", className)} {...props} /> } function SheetDescription({ className, ...props }: DialogPrimitive.Description.Props) { const { draggable } = React.useContext(SheetContext) const Description = draggable ? DrawerPrimitive.Description : DialogPrimitive.Description return <Description className={cn("text-sm text-muted-foreground", className)} {...props} /> } function SheetHeader({ className, ...props }: React.ComponentProps<"div">) { return <div data-slot="sheet-header" className={cn("flex flex-col gap-1", className)} {...props} /> } function SheetBody({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="sheet-body" className={cn("flex min-h-0 flex-1 flex-col gap-stack-md overflow-y-auto", className)} {...props} /> ) } function SheetFooter({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="sheet-footer" className={cn("mt-auto flex flex-wrap justify-end gap-inline-sm pt-2", className)} {...props} /> ) } function logical(side: Side): "start" | "end" | "top" | "bottom" { if (side === "left") return "start" if (side === "right") return "end" return side } const edges = { start: "inset-y-0 start-0 w-(--sheet-width) max-w-[calc(100vw-var(--space-6))]", end: "inset-y-0 end-0 w-(--sheet-width) max-w-[calc(100vw-var(--space-6))]", top: "inset-x-0 top-0 max-h-[80vh]", bottom: "inset-x-0 bottom-0 max-h-[80vh]", } as const function SheetContent({ className, children, side = "end", modal = true, ...props }: DialogPrimitive.Popup.Props & { side?: Side /** false: no scrim and the page stays usable. */ modal?: boolean }) { const ref = React.useRef<HTMLDivElement>(null) const { draggable } = React.useContext(SheetContext) usePortalMotion(ref) if (draggable) { return ( <DrawerPrimitive.Portal> <DrawerPrimitive.Backdrop className="overlay-scrim fixed inset-0 z-modal" /> <DrawerPrimitive.Viewport className="fixed inset-0 z-modal flex items-end justify-center"> <DrawerPrimitive.Popup ref={ref} data-slot="sheet-content" data-side="bottom" className={cn( "overlay-surface drawer-panel relative flex max-h-[80vh] w-full flex-col gap-stack-md rounded-t-(--sheet-corner) p-(--sheet-padding) pt-3 text-foreground outline-none sm:max-w-(--layout-dialog-md)", className )} {...(props as DrawerPrimitive.Popup.Props)} > <div aria-hidden className="drawer-handle mx-auto h-(--sheet-handle-height) w-(--sheet-handle-width) shrink-0 rounded-(--radius-pill) bg-(--sheet-handle)" /> {children} </DrawerPrimitive.Popup> </DrawerPrimitive.Viewport> </DrawerPrimitive.Portal> ) } const edge = logical(side) return ( <DialogPrimitive.Portal> {modal ? <DialogPrimitive.Backdrop className="overlay-scrim fixed inset-0 z-modal" /> : null} <DialogPrimitive.Popup ref={ref} data-slot="sheet-content" data-side={edge === "start" ? "left" : edge === "end" ? "right" : edge} className={cn( "overlay-surface sheet-panel fixed z-modal flex flex-col gap-stack-md p-(--sheet-padding) text-foreground outline-none", edges[edge], className )} {...props} > {children} </DialogPrimitive.Popup> </DialogPrimitive.Portal> ) } /* shadcn-compatible presets: a Drawer is a draggable bottom Sheet. */ function Drawer(props: Omit<SheetProps, "variant" | "draggable">) { return <Sheet variant="draggable" snapPoints={[1]} {...props} /> } const DrawerTrigger = SheetTrigger const DrawerClose = SheetClose const DrawerTitle = SheetTitle const DrawerDescription = SheetDescription const DrawerHeader = SheetHeader const DrawerFooter = SheetFooter function DrawerContent(props: React.ComponentProps<typeof SheetContent>) { return <SheetContent side="bottom" {...props} /> } export { Sheet, SheetTrigger, SheetClose, SheetContent, SheetHeader, SheetBody, SheetFooter, SheetTitle, SheetDescription, Drawer, DrawerTrigger, DrawerClose, DrawerContent, DrawerHeader, DrawerFooter, DrawerTitle, DrawerDescription, }components/ui/sidebar.tsxsidebar
components/ui/sidebar.tsx"use client" import * as React from "react" import { PanelLeftIcon } from "lucide-react" import { cn } from "cn" import { Button } from "@/components/ui/button" import { Navigation } from "@/components/ui/navigation" import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet" /* Sidebar: the app shell's navigation column, built on Navigation. - Desktop: a drawer that collapses to a rail (⌘B / Ctrl+B or the trigger). Width moves on the sheet curve; labels fade before the width shrinks. - Phones (< 768px): the same content opens as a Sheet from the start edge. */ type SidebarState = { collapsed: boolean setCollapsed: (value: boolean) => void mobileOpen: boolean setMobileOpen: (value: boolean) => void mobile: boolean } const SidebarContext = React.createContext<SidebarState | null>(null) function useSidebar() { const state = React.useContext(SidebarContext) if (!state) throw new Error("Sidebar parts must be inside <SidebarProvider>") return state } const query = "(max-width: 767px)" function useMobile() { return React.useSyncExternalStore( (notify) => { const media = window.matchMedia(query) media.addEventListener("change", notify) return () => media.removeEventListener("change", notify) }, () => window.matchMedia(query).matches, () => false ) } function SidebarProvider({ defaultCollapsed = false, className, children, ...props }: React.ComponentProps<"div"> & { defaultCollapsed?: boolean }) { const [collapsed, setCollapsed] = React.useState(defaultCollapsed) const [mobileOpen, setMobileOpen] = React.useState(false) const mobile = useMobile() React.useEffect(() => { const onKey = (event: KeyboardEvent) => { if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "b") { event.preventDefault() if (window.matchMedia(query).matches) setMobileOpen((open) => !open) else setCollapsed((value) => !value) } } window.addEventListener("keydown", onKey) return () => window.removeEventListener("keydown", onKey) }, []) const state = React.useMemo(() => ({ collapsed, setCollapsed, mobileOpen, setMobileOpen, mobile }), [collapsed, mobileOpen, mobile]) return ( <SidebarContext.Provider value={state}> <div data-slot="sidebar-provider" className={cn("flex min-h-svh w-full", className)} {...props}> {children} </div> </SidebarContext.Provider> ) } function Sidebar({ className, children, label = "Sidebar" }: { className?: string; children: React.ReactNode; label?: string }) { const { collapsed, mobile, mobileOpen, setMobileOpen } = useSidebar() if (mobile) { return ( <Sheet open={mobileOpen} onOpenChange={setMobileOpen}> <SheetContent side="start" className="w-(--sidebar-width) p-3"> <SheetTitle className="sr-only">{label}</SheetTitle> <div className="flex h-full flex-col gap-stack-md">{children}</div> </SheetContent> </Sheet> ) } return ( <aside data-slot="sidebar" data-collapsed={collapsed || undefined} aria-label={label} className={cn( "sidebar sticky top-0 flex h-svh shrink-0 flex-col gap-stack-md overflow-hidden bg-(--sidebar-container) py-3", collapsed ? "w-(--sidebar-width-collapsed) px-0" : "w-(--sidebar-width) px-3", className )} > {children} </aside> ) } /** The Navigation inside a Sidebar: drawer when open, rail when collapsed. */ function SidebarNav({ children, className, ...props }: React.ComponentProps<typeof Navigation>) { const { collapsed, mobile } = useSidebar() return ( <Navigation variant={collapsed && !mobile ? "rail" : "drawer"} className={cn("w-full bg-transparent p-0", className)} {...props}> {children} </Navigation> ) } function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) { return <div data-slot="sidebar-header" className={cn("flex min-h-(--size-control-md) items-center gap-inline-sm", className)} {...props} /> } function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) { return <div data-slot="sidebar-footer" className={cn("mt-auto flex items-center gap-inline-sm", className)} {...props} /> } /** Text that fades out before the sidebar collapses (logos, names, section labels). */ function SidebarLabel({ className, ...props }: React.ComponentProps<"span">) { return <span data-slot="sidebar-label" className={cn("sidebar-label truncate", className)} {...props} /> } function SidebarTrigger({ className, ...props }: React.ComponentProps<typeof Button>) { const { collapsed, setCollapsed, mobile, mobileOpen, setMobileOpen } = useSidebar() return ( <Button size="icon" variant="ghost" aria-label={mobile ? "Open navigation" : collapsed ? "Expand sidebar" : "Collapse sidebar"} aria-expanded={mobile ? mobileOpen : !collapsed} onClick={() => (mobile ? setMobileOpen(!mobileOpen) : setCollapsed(!collapsed))} className={className} {...props} > <PanelLeftIcon /> </Button> ) } function SidebarInset({ className, ...props }: React.ComponentProps<"main">) { return <main data-slot="sidebar-inset" className={cn("flex min-w-0 flex-1 flex-col", className)} {...props} /> } export { SidebarProvider, Sidebar, SidebarNav, SidebarHeader, SidebarFooter, SidebarLabel, SidebarTrigger, SidebarInset, useSidebar }
Imports
What the examples on this page import:
import { FolderIcon, HomeIcon, InboxIcon, SettingsIcon } from "lucide-react"
import { NavigationItem } from "@/components/ui/navigation"
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable"
import { Sidebar, SidebarHeader, SidebarInset, SidebarLabel, SidebarNav, SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar"Anatomy
- 1Provider · Holds collapsed and phone state; lays out the sidebar and inset.
- 2Sidebar · --sidebar-width, --sidebar-width-collapsed, --sidebar-container.
- 3Header / footer · Logo, workspace, account. SidebarLabel text fades before collapsing.
- 4Nav · Navigation as drawer (open) or rail (collapsed).
- 5Trigger · Collapses on desktop, opens the Sheet on phones.
- 6Inset · The main content area.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
SidebarProvider defaultCollapsed | boolean | false | Start as a rail. |
useSidebar() | { collapsed, setCollapsed, mobile, mobileOpen, setMobileOpen } | — | Read or change the state anywhere inside. |
Sidebar label | string | "Sidebar" | Accessible name. |
Tokens
Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.
| Token | Points to | Light | Dark |
|---|---|---|---|
--nav-item-height | var(--size-row) | 40px | same |
--nav-item-corner | var(--shape-full) | 999px | same |
--nav-item-container-hover | var(--color-bg-hover) | oklch(0.965 0.005 95) | oklch(0.22 0 0) |
--nav-item-container-pressed | var(--color-bg-pressed) | oklch(0.94 0.007 95) | oklch(0.27 0 0) |
--nav-item-active | var(--color-bg-selected) | color-mix(in oklch, var(--ref-select) 12%, transparent) | color-mix(in oklch, var(--ref-select) 16%, transparent) |
--nav-item-active-label | var(--on-surface) | oklch(0.22 0.01 260) | oklch(1 0 0) |
--nav-bar-height | var(--space-16) | 64px | same |
--nav-rail-width | var(--space-20) | 80px | same |
--nav-drawer-width | var(--layout-sidebar) | 256px | same |
--nav-container | var(--surface-container-low) | oklch(0.985 0.004 95) | oklch(0.17 0 0) |
--sidebar-width | var(--layout-sidebar) | 256px | same |
--sidebar-width-collapsed | var(--nav-rail-width) | 80px | same |
--sidebar-container | var(--surface-container-low) | oklch(0.985 0.004 95) | oklch(0.17 0 0) |
Motion
| Trigger | What happens | Tokens |
|---|---|---|
| Collapse | Labels fade and slide 4px, then the width shrinks on the sheet curve; icons stay put. | --duration-quick, --duration-medium, --ease-sheet |
| Phone | Opens as a Sheet from the start edge. | --duration-medium |
Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.
Accessibility
- aside with a label; the trigger says what it will do and has aria-expanded.
- ⌘B / Ctrl+B toggles.
- The current item has aria-current=page.
Usage
Do
- Use for apps with 5+ sections.
Don’t
- Don't use on marketing sites (use App bar + Navigation menu).
Code
"use client"
import * as React from "react"
import { PanelLeftIcon } from "lucide-react"
import { cn } from "cn"
import { Button } from "@/components/ui/button"
import { Navigation } from "@/components/ui/navigation"
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"
/*
Sidebar: the app shell's navigation column, built on Navigation.
- Desktop: a drawer that collapses to a rail (⌘B / Ctrl+B or the trigger).
Width moves on the sheet curve; labels fade before the width shrinks.
- Phones (< 768px): the same content opens as a Sheet from the start edge.
*/
type SidebarState = {
collapsed: boolean
setCollapsed: (value: boolean) => void
mobileOpen: boolean
setMobileOpen: (value: boolean) => void
mobile: boolean
}
const SidebarContext = React.createContext<SidebarState | null>(null)
function useSidebar() {
const state = React.useContext(SidebarContext)
if (!state) throw new Error("Sidebar parts must be inside <SidebarProvider>")
return state
}
const query = "(max-width: 767px)"
function useMobile() {
return React.useSyncExternalStore(
(notify) => {
const media = window.matchMedia(query)
media.addEventListener("change", notify)
return () => media.removeEventListener("change", notify)
},
() => window.matchMedia(query).matches,
() => false
)
}
function SidebarProvider({
defaultCollapsed = false,
className,
children,
...props
}: React.ComponentProps<"div"> & { defaultCollapsed?: boolean }) {
const [collapsed, setCollapsed] = React.useState(defaultCollapsed)
const [mobileOpen, setMobileOpen] = React.useState(false)
const mobile = useMobile()
React.useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "b") {
event.preventDefault()
if (window.matchMedia(query).matches) setMobileOpen((open) => !open)
else setCollapsed((value) => !value)
}
}
window.addEventListener("keydown", onKey)
return () => window.removeEventListener("keydown", onKey)
}, [])
const state = React.useMemo(() => ({ collapsed, setCollapsed, mobileOpen, setMobileOpen, mobile }), [collapsed, mobileOpen, mobile])
return (
<SidebarContext.Provider value={state}>
<div data-slot="sidebar-provider" className={cn("flex min-h-svh w-full", className)} {...props}>
{children}
</div>
</SidebarContext.Provider>
)
}
function Sidebar({ className, children, label = "Sidebar" }: { className?: string; children: React.ReactNode; label?: string }) {
const { collapsed, mobile, mobileOpen, setMobileOpen } = useSidebar()
if (mobile) {
return (
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
<SheetContent side="start" className="w-(--sidebar-width) p-3">
<SheetTitle className="sr-only">{label}</SheetTitle>
<div className="flex h-full flex-col gap-stack-md">{children}</div>
</SheetContent>
</Sheet>
)
}
return (
<aside
data-slot="sidebar"
data-collapsed={collapsed || undefined}
aria-label={label}
className={cn(
"sidebar sticky top-0 flex h-svh shrink-0 flex-col gap-stack-md overflow-hidden bg-(--sidebar-container) py-3",
collapsed ? "w-(--sidebar-width-collapsed) px-0" : "w-(--sidebar-width) px-3",
className
)}
>
{children}
</aside>
)
}
/** The Navigation inside a Sidebar: drawer when open, rail when collapsed. */
function SidebarNav({ children, className, ...props }: React.ComponentProps<typeof Navigation>) {
const { collapsed, mobile } = useSidebar()
return (
<Navigation variant={collapsed && !mobile ? "rail" : "drawer"} className={cn("w-full bg-transparent p-0", className)} {...props}>
{children}
</Navigation>
)
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="sidebar-header" className={cn("flex min-h-(--size-control-md) items-center gap-inline-sm", className)} {...props} />
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="sidebar-footer" className={cn("mt-auto flex items-center gap-inline-sm", className)} {...props} />
}
/** Text that fades out before the sidebar collapses (logos, names, section labels). */
function SidebarLabel({ className, ...props }: React.ComponentProps<"span">) {
return <span data-slot="sidebar-label" className={cn("sidebar-label truncate", className)} {...props} />
}
function SidebarTrigger({ className, ...props }: React.ComponentProps<typeof Button>) {
const { collapsed, setCollapsed, mobile, mobileOpen, setMobileOpen } = useSidebar()
return (
<Button
size="icon"
variant="ghost"
aria-label={mobile ? "Open navigation" : collapsed ? "Expand sidebar" : "Collapse sidebar"}
aria-expanded={mobile ? mobileOpen : !collapsed}
onClick={() => (mobile ? setMobileOpen(!mobileOpen) : setCollapsed(!collapsed))}
className={className}
{...props}
>
<PanelLeftIcon />
</Button>
)
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return <main data-slot="sidebar-inset" className={cn("flex min-w-0 flex-1 flex-col", className)} {...props} />
}
export { SidebarProvider, Sidebar, SidebarNav, SidebarHeader, SidebarFooter, SidebarLabel, SidebarTrigger, SidebarInset, useSidebar }