Sidebar app shell

An application layout with a sidebar and a top bar. The sidebar has a workspace switcher, grouped navigation with badges and an optional footer, and collapses to icons with label tips (Ctrl/Cmd+B, remembered in localStorage). The top bar holds the page title, a search field (Ctrl/Cmd+K), your action buttons and an account menu. Below 1024px the sidebar opens as a drawer with focus trapping, Escape to close and scroll lock.

DashboardsBlockTailwind v4

Source

"use client";

import * as React from "react";
import { Check, ChevronsUpDown, LogOut, Menu, PanelLeft, Plus, Search, Settings, User, X, type LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";

export interface NavItem {
  label: string;
  href: string;
  icon: LucideIcon;
  /** Small count or label shown at the end of the row. */
  badge?: string | number;
}

export interface NavGroup {
  label?: string;
  items: NavItem[];
}

export interface Workspace {
  id: string;
  name: string;
  plan?: string;
}

export interface UserMenuItem {
  label: string;
  icon?: LucideIcon;
  href?: string;
  onSelect?: () => void;
  /** Draws a separator above the item. */
  separated?: boolean;
}

export interface SidebarShellProps {
  nav: NavGroup[];
  activeHref?: string;
  /** Intercept navigation for a client router. Call event.preventDefault() to stop the browser. */
  onNavigate?: (href: string, event: React.MouseEvent<HTMLAnchorElement>) => void;
  workspaces: Workspace[];
  workspaceId: string;
  onWorkspaceChange?: (id: string) => void;
  onCreateWorkspace?: () => void;
  user: { name: string; email: string };
  userMenu?: UserMenuItem[];
  /** Page title or breadcrumb in the top bar. */
  title?: React.ReactNode;
  searchPlaceholder?: string;
  onSearch?: (query: string) => void;
  /** Extra top-bar buttons, placed before the avatar menu. */
  actions?: React.ReactNode;
  /** Content at the bottom of the expanded sidebar, such as a usage meter. */
  sidebarFooter?: React.ReactNode;
  defaultCollapsed?: boolean;
  /** Remembers the collapsed state in localStorage under this key. Pass null to disable. */
  storageKey?: string | null;
  children: React.ReactNode;
  className?: string;
}

const DEFAULT_USER_MENU: UserMenuItem[] = [
  { label: "Profile", icon: User, href: "#profile" },
  { label: "Settings", icon: Settings, href: "#settings" },
  { label: "Sign out", icon: LogOut, href: "#sign-out", separated: true },
];

const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-ring";
const TINTS = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)"];

function tintOf(text: string) {
  let hash = 0;
  for (const char of text) hash = (hash * 31 + char.charCodeAt(0)) | 0;
  return TINTS[Math.abs(hash) % TINTS.length];
}

function initialsOf(name: string) {
  const parts = name.trim().split(/\s+/);
  return ((parts[0]?.[0] || "") + (parts.length > 1 ? parts[parts.length - 1][0] : "")).toUpperCase();
}

function WorkspaceMark({ name, className }: { name: string; className?: string }) {
  const tint = tintOf(name);
  return (
    <span
      aria-hidden
      className={cn("grid size-8 shrink-0 place-items-center rounded-lg text-sm font-semibold text-white", className)}
      style={{ background: `linear-gradient(140deg, ${tint}, color-mix(in oklab, ${tint} 60%, black))` }}
    >
      {name.charAt(0).toUpperCase()}
    </span>
  );
}

/* A menu button: arrow keys move, Escape closes and returns focus, Tab or an outside click closes. */
function useMenu() {
  const [open, setOpen] = React.useState(false);
  const triggerRef = React.useRef<HTMLButtonElement>(null);
  const menuRef = React.useRef<HTMLDivElement>(null);
  const id = React.useId();
  const items = () => Array.from(menuRef.current?.querySelectorAll<HTMLElement>('[role^="menuitem"]') ?? []);

  React.useEffect(() => {
    if (!open) return;
    const list = items();
    (list.find((item) => item.getAttribute("aria-checked") === "true") || list[0])?.focus();
    const onPointerDown = (event: PointerEvent) => {
      const target = event.target as Node;
      if (!menuRef.current?.contains(target) && !triggerRef.current?.contains(target)) setOpen(false);
    };
    document.addEventListener("pointerdown", onPointerDown);
    return () => document.removeEventListener("pointerdown", onPointerDown);
  }, [open]);

  const close = () => {
    setOpen(false);
    triggerRef.current?.focus();
  };

  const onMenuKeyDown = (event: React.KeyboardEvent) => {
    const list = items();
    const index = list.indexOf(document.activeElement as HTMLElement);
    const move = (next: number) => {
      event.preventDefault();
      list[(next + list.length) % list.length]?.focus();
    };
    if (event.key === "ArrowDown") move(index + 1);
    else if (event.key === "ArrowUp") move(index - 1);
    else if (event.key === "Home") move(0);
    else if (event.key === "End") move(list.length - 1);
    else if (event.key === "Escape") {
      event.preventDefault();
      close();
    } else if (event.key === "Tab") setOpen(false);
  };

  return {
    open,
    close,
    trigger: {
      ref: triggerRef,
      "aria-haspopup": "menu" as const,
      "aria-expanded": open,
      "aria-controls": open ? id : undefined,
      onClick: () => setOpen((value) => !value),
      onKeyDown: (event: React.KeyboardEvent) => {
        if (event.key === "ArrowDown" && !open) {
          event.preventDefault();
          setOpen(true);
        }
      },
    },
    menu: { ref: menuRef, id, role: "menu", tabIndex: -1, onKeyDown: onMenuKeyDown },
  };
}

const menuPanel = "absolute z-50 min-w-56 rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg";
const menuItem =
  "flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-left text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground";

/* Stays mounted until the exit transition ends. Entry is animated with @starting-style (Tailwind `starting:`). */
function usePresence(open: boolean, duration = 220) {
  const [mounted, setMounted] = React.useState(open);
  React.useEffect(() => {
    if (open) {
      setMounted(true);
      return;
    }
    const timer = setTimeout(() => setMounted(false), duration);
    return () => clearTimeout(timer);
  }, [open, duration]);
  return mounted || open;
}

function WorkspaceSwitcher({
  workspaces,
  workspaceId,
  onChange,
  onCreate,
  collapsed,
}: {
  workspaces: Workspace[];
  workspaceId: string;
  onChange?: (id: string) => void;
  onCreate?: () => void;
  collapsed: boolean;
}) {
  const menu = useMenu();
  const current = workspaces.find((item) => item.id === workspaceId) || workspaces[0];
  return (
    <div className="relative min-w-0 flex-1">
      <button
        type="button"
        {...menu.trigger}
        aria-label={collapsed ? `Workspace: ${current?.name}` : undefined}
        className={cn(
          "flex w-full items-center gap-2.5 rounded-lg p-1.5 text-left transition-colors hover:bg-accent",
          focusRing,
          collapsed && "justify-center",
        )}
      >
        <WorkspaceMark name={current?.name || "?"} />
        {!collapsed && (
          <>
            <span className="min-w-0 flex-1">
              <span className="block truncate text-sm font-semibold">{current?.name}</span>
              {current?.plan && <span className="block truncate text-xs text-muted-foreground">{current.plan}</span>}
            </span>
            <ChevronsUpDown aria-hidden className="size-4 shrink-0 text-muted-foreground" />
          </>
        )}
      </button>
      {menu.open && (
        <div {...menu.menu} aria-label="Switch workspace" className={cn(menuPanel, "top-full left-0 mt-1 w-64")}>
          {workspaces.map((workspace) => (
            <button
              key={workspace.id}
              type="button"
              role="menuitemradio"
              aria-checked={workspace.id === current?.id}
              tabIndex={-1}
              onClick={() => {
                onChange?.(workspace.id);
                menu.close();
              }}
              className={menuItem}
            >
              <WorkspaceMark name={workspace.name} className="size-6 rounded-md text-xs" />
              <span className="min-w-0 flex-1 truncate">{workspace.name}</span>
              {workspace.id === current?.id && <Check aria-hidden className="size-4" />}
            </button>
          ))}
          {onCreate && (
            <>
              <div role="separator" className="-mx-1 my-1 h-px bg-border" />
              <button
                type="button"
                role="menuitem"
                tabIndex={-1}
                onClick={() => {
                  menu.close();
                  onCreate();
                }}
                className={cn(menuItem, "text-muted-foreground")}
              >
                <span className="grid size-6 place-items-center rounded-md border border-dashed">
                  <Plus aria-hidden className="size-3.5" />
                </span>
                New workspace
              </button>
            </>
          )}
        </div>
      )}
    </div>
  );
}

function SidebarNav({
  nav,
  activeHref,
  collapsed,
  onNavigate,
}: {
  nav: NavGroup[];
  activeHref?: string;
  collapsed: boolean;
  onNavigate?: (href: string, event: React.MouseEvent<HTMLAnchorElement>) => void;
}) {
  // Collapsed rows show their label in a fixed-position tip so the scrolling nav cannot clip it.
  const [tip, setTip] = React.useState<{ label: string; top: number; left: number } | null>(null);
  const showTip = (label: string, element: HTMLElement) => {
    if (!collapsed) return;
    const rect = element.getBoundingClientRect();
    setTip({ label, top: rect.top + rect.height / 2, left: rect.right + 10 });
  };

  return (
    <nav aria-label="Main" className="flex-1 overflow-x-hidden overflow-y-auto px-3 py-4" onScroll={() => setTip(null)}>
      {nav.map((group, groupIndex) => (
        <div key={group.label || groupIndex} className={cn(groupIndex > 0 && "mt-6")}>
          {group.label &&
            (collapsed ? (
              <div aria-hidden className="mx-auto mb-2 h-px w-5 bg-border" />
            ) : (
              <p className="mb-1.5 px-2.5 text-xs font-medium text-muted-foreground">{group.label}</p>
            ))}
          <ul className="space-y-0.5">
            {group.items.map((item) => {
              const active = item.href === activeHref;
              return (
                <li key={item.href}>
                  <a
                    href={item.href}
                    aria-current={active ? "page" : undefined}
                    onClick={(event) => onNavigate?.(item.href, event)}
                    onMouseEnter={(event) => showTip(item.label, event.currentTarget)}
                    onMouseLeave={() => setTip(null)}
                    onFocus={(event) => showTip(item.label, event.currentTarget)}
                    onBlur={() => setTip(null)}
                    className={cn(
                      "relative flex h-9 items-center gap-3 rounded-md px-2.5 text-sm font-medium transition-colors",
                      focusRing,
                      collapsed && "justify-center px-0",
                      active
                        ? "bg-background text-foreground shadow-xs ring-1 ring-border"
                        : "text-muted-foreground hover:bg-accent hover:text-accent-foreground",
                    )}
                  >
                    <item.icon aria-hidden className="size-4 shrink-0" />
                    <span className={collapsed ? "sr-only" : "min-w-0 flex-1 truncate"}>{item.label}</span>
                    {item.badge !== undefined &&
                      (collapsed ? (
                        <span aria-hidden className="absolute top-1.5 right-2 size-1.5 rounded-full bg-primary" />
                      ) : (
                        <span className="rounded-full bg-muted px-1.5 py-px text-xs text-muted-foreground tabular-nums">{item.badge}</span>
                      ))}
                  </a>
                </li>
              );
            })}
          </ul>
        </div>
      ))}
      {tip && (
        <span
          aria-hidden
          className="pointer-events-none fixed z-50 -translate-y-1/2 rounded-md bg-primary px-2 py-1 text-xs font-medium whitespace-nowrap text-primary-foreground shadow-md"
          style={{ top: tip.top, left: tip.left }}
        >
          {tip.label}
        </span>
      )}
    </nav>
  );
}

function UserMenu({ user, items }: { user: { name: string; email: string }; items: UserMenuItem[] }) {
  const menu = useMenu();
  return (
    <div className="relative">
      <button
        type="button"
        {...menu.trigger}
        aria-label={`Account menu for ${user.name}`}
        className={cn("grid size-8 place-items-center rounded-full bg-muted text-xs font-semibold ring-1 ring-border transition hover:ring-ring", focusRing, "focus-visible:ring-offset-2 focus-visible:ring-offset-background")}
      >
        {initialsOf(user.name)}
      </button>
      {menu.open && (
        <div {...menu.menu} aria-label="Account" className={cn(menuPanel, "top-full right-0 mt-2 w-60")}>
          <div className="px-2 py-1.5">
            <p className="truncate text-sm font-medium">{user.name}</p>
            <p className="truncate text-xs text-muted-foreground">{user.email}</p>
          </div>
          <div role="separator" className="-mx-1 my-1 h-px bg-border" />
          {items.map((item) => {
            const content = (
              <>
                {item.icon && <item.icon aria-hidden className="size-4 text-muted-foreground" />}
                {item.label}
              </>
            );
            return (
              <React.Fragment key={item.label}>
                {item.separated && <div role="separator" className="-mx-1 my-1 h-px bg-border" />}
                {item.href ? (
                  <a role="menuitem" tabIndex={-1} href={item.href} onClick={() => { item.onSelect?.(); menu.close(); }} className={menuItem}>
                    {content}
                  </a>
                ) : (
                  <button type="button" role="menuitem" tabIndex={-1} onClick={() => { item.onSelect?.(); menu.close(); }} className={menuItem}>
                    {content}
                  </button>
                )}
              </React.Fragment>
            );
          })}
        </div>
      )}
    </div>
  );
}

export function SidebarShell({
  nav,
  activeHref,
  onNavigate,
  workspaces,
  workspaceId,
  onWorkspaceChange,
  onCreateWorkspace,
  user,
  userMenu = DEFAULT_USER_MENU,
  title,
  searchPlaceholder = "Search",
  onSearch,
  actions,
  sidebarFooter,
  defaultCollapsed = false,
  storageKey = "sidebar-collapsed",
  children,
  className,
}: SidebarShellProps) {
  const [collapsed, setCollapsed] = React.useState(defaultCollapsed);
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const [searchOpen, setSearchOpen] = React.useState(false);
  const [shortcut, setShortcut] = React.useState("Ctrl K");
  const searchRef = React.useRef<HTMLInputElement>(null);
  const drawerRef = React.useRef<HTMLDivElement>(null);
  const menuButtonRef = React.useRef<HTMLButtonElement>(null);
  const drawerMounted = usePresence(drawerOpen);

  // Restore the remembered state after mount; storage can throw in sandboxed frames.
  React.useEffect(() => {
    if (/Mac|iPhone|iPad/.test(navigator.userAgent)) setShortcut("⌘K");
    if (!storageKey) return;
    try {
      const saved = localStorage.getItem(storageKey);
      if (saved !== null) setCollapsed(saved === "1");
    } catch {}
  }, [storageKey]);

  const toggleCollapsed = React.useCallback(() => {
    setCollapsed((value) => {
      if (storageKey)
        try {
          localStorage.setItem(storageKey, value ? "0" : "1");
        } catch {}
      return !value;
    });
  }, [storageKey]);

  // Ctrl/⌘ K focuses search, Ctrl/⌘ B collapses the sidebar.
  React.useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (!(event.metaKey || event.ctrlKey)) return;
      const key = event.key.toLowerCase();
      if (key === "k") {
        event.preventDefault();
        setSearchOpen(true);
        setTimeout(() => searchRef.current?.focus());
      } else if (key === "b" && window.matchMedia("(min-width: 1024px)").matches) {
        event.preventDefault();
        toggleCollapsed();
      }
    };
    document.addEventListener("keydown", onKeyDown);
    return () => document.removeEventListener("keydown", onKeyDown);
  }, [toggleCollapsed]);

  // Drawer: focus the panel, trap Tab, close on Escape, lock page scroll, restore focus on close.
  React.useEffect(() => {
    if (!drawerOpen) return;
    const panel = drawerRef.current;
    const trigger = menuButtonRef.current;
    const focusables = () =>
      Array.from(panel?.querySelectorAll<HTMLElement>('a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])') ?? []);
    setTimeout(() => focusables()[0]?.focus());
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.defaultPrevented) return;
      if (event.key === "Escape") {
        event.preventDefault();
        setDrawerOpen(false);
      } else if (event.key === "Tab") {
        const list = focusables();
        if (!list.length) return;
        const first = list[0];
        const last = list[list.length - 1];
        if (event.shiftKey && document.activeElement === first) {
          event.preventDefault();
          last.focus();
        } else if (!event.shiftKey && document.activeElement === last) {
          event.preventDefault();
          first.focus();
        }
      }
    };
    const overflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = overflow;
      trigger?.focus();
    };
  }, [drawerOpen]);

  const navigate = (href: string, event: React.MouseEvent<HTMLAnchorElement>) => {
    onNavigate?.(href, event);
    setDrawerOpen(false);
  };

  return (
    <div className={cn("flex h-dvh overflow-hidden bg-background text-foreground", className)}>
      <aside
        aria-label="Sidebar"
        className={cn(
          "relative z-20 hidden shrink-0 flex-col border-r bg-muted/40 motion-safe:transition-[width] motion-safe:duration-200 lg:flex",
          collapsed ? "w-[68px]" : "w-64",
        )}
      >
        <div className={cn("flex h-14 shrink-0 items-center border-b", collapsed ? "px-2.5" : "px-3")}>
          <WorkspaceSwitcher
            workspaces={workspaces}
            workspaceId={workspaceId}
            onChange={onWorkspaceChange}
            onCreate={onCreateWorkspace}
            collapsed={collapsed}
          />
        </div>
        <SidebarNav nav={nav} activeHref={activeHref} collapsed={collapsed} onNavigate={onNavigate} />
        {sidebarFooter && !collapsed && <div className="shrink-0 p-3">{sidebarFooter}</div>}
      </aside>

      {drawerMounted && (
        <div className="fixed inset-0 z-50 lg:hidden">
          <div
            aria-hidden
            onClick={() => setDrawerOpen(false)}
            className={cn("absolute inset-0 bg-black/40 motion-safe:transition-opacity motion-safe:duration-200 dark:bg-black/60", drawerOpen ? "opacity-100 starting:opacity-0" : "opacity-0")}
          />
          <div
            ref={drawerRef}
            role="dialog"
            aria-modal="true"
            aria-label="Navigation"
            className={cn(
              "absolute inset-y-0 left-0 flex w-[min(20rem,85vw)] flex-col border-r bg-background shadow-xl motion-safe:transition-transform motion-safe:duration-200 motion-safe:ease-out",
              drawerOpen ? "translate-x-0 starting:-translate-x-full" : "-translate-x-full",
            )}
          >
            <div className="flex h-14 shrink-0 items-center gap-2 border-b px-3">
              <WorkspaceSwitcher workspaces={workspaces} workspaceId={workspaceId} onChange={onWorkspaceChange} onCreate={onCreateWorkspace} collapsed={false} />
              <button
                type="button"
                onClick={() => setDrawerOpen(false)}
                aria-label="Close navigation"
                className={cn("grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground", focusRing)}
              >
                <X aria-hidden className="size-4" />
              </button>
            </div>
            <SidebarNav nav={nav} activeHref={activeHref} collapsed={false} onNavigate={navigate} />
            {sidebarFooter && <div className="shrink-0 p-3">{sidebarFooter}</div>}
          </div>
        </div>
      )}

      <div className="flex min-w-0 flex-1 flex-col">
        <header className="relative flex h-14 shrink-0 items-center gap-2 border-b bg-background px-3 sm:px-4 lg:px-6">
          <button
            ref={menuButtonRef}
            type="button"
            onClick={() => setDrawerOpen(true)}
            aria-label="Open navigation"
            aria-expanded={drawerOpen}
            className={cn("grid size-8 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground lg:hidden", focusRing)}
          >
            <Menu aria-hidden className="size-[18px]" />
          </button>
          <button
            type="button"
            onClick={toggleCollapsed}
            aria-label={collapsed ? "Expand sidebar" : "Collapse sidebar"}
            aria-keyshortcuts="Control+B Meta+B"
            className={cn("-ml-2 hidden size-8 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground lg:grid", focusRing)}
          >
            <PanelLeft aria-hidden className="size-[18px]" />
          </button>
          <span aria-hidden className="mx-1 hidden h-5 w-px bg-border lg:block" />
          <div className="min-w-0 flex-1 truncate text-sm font-medium">{title}</div>

          <form
            role="search"
            onSubmit={(event) => {
              event.preventDefault();
              onSearch?.(searchRef.current?.value || "");
            }}
            className={cn(
              "hidden items-center sm:relative sm:flex sm:w-64",
              searchOpen && "max-sm:absolute max-sm:inset-0 max-sm:z-10 max-sm:flex max-sm:gap-2 max-sm:bg-background max-sm:px-3",
            )}
          >
            <Search aria-hidden className="pointer-events-none absolute left-6 size-4 text-muted-foreground sm:left-2.5" />
            <input
              ref={searchRef}
              type="search"
              aria-label="Search"
              placeholder={searchPlaceholder}
              onKeyDown={(event) => {
                if (event.key === "Escape") {
                  event.currentTarget.blur();
                  setSearchOpen(false);
                }
              }}
              className="h-9 w-full rounded-md border border-input bg-muted/40 pr-14 pl-9 text-sm outline-none transition-colors placeholder:text-muted-foreground focus-visible:border-ring focus-visible:bg-background focus-visible:ring-2 focus-visible:ring-ring/30 sm:pr-14"
            />
            <kbd className="pointer-events-none absolute right-2 hidden rounded border bg-background px-1.5 py-0.5 font-sans text-[11px] text-muted-foreground sm:block">
              {shortcut}
            </kbd>
            <button
              type="button"
              onClick={() => setSearchOpen(false)}
              aria-label="Close search"
              className={cn("grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent sm:hidden", focusRing)}
            >
              <X aria-hidden className="size-4" />
            </button>
          </form>
          <button
            type="button"
            onClick={() => {
              setSearchOpen(true);
              setTimeout(() => searchRef.current?.focus());
            }}
            aria-label="Search"
            className={cn("grid size-8 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-accent-foreground sm:hidden", focusRing)}
          >
            <Search aria-hidden className="size-[18px]" />
          </button>
          {actions}
          <UserMenu user={user} items={userMenu} />
        </header>
        <main className="min-h-0 flex-1 overflow-y-auto">{children}</main>
      </div>
    </div>
  );
}