Skip to content
Shaken UI
Sign in

Sidebar

Save

An app sidebar with a header, labelled and collapsible groups, icons, counts, an active item, an icon-only mode with tooltips, and a sheet on narrow screens.

Category
Navigation
Version
0.1.1
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Sidebar preview

Runs

Press the panel button or ⌘B to switch between the full sidebar and icons only.

Fix invoice rounding
Upgrade to React 19
Nightly evaluation
Rotate API keys

Installation

npx @shakenui/cli add sidebar

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add sidebar --dry-run

Usage

sidebar-example.tsx
"use client";

import { useState } from "react";
import {
  Sidebar,
  SidebarCollapsibleGroup,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarInset,
  SidebarMenu,
  SidebarMenuBadge,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarProvider,
  SidebarTrigger,
} from "@/components/shaken/ui/sidebar";

const icon = { "aria-hidden": true, viewBox: "0 0 16 16", fill: "none" } as const;
const stroke = { stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" } as const;

const icons = {
  inbox: (
    <svg {...icon}>
      <path d="M2.75 9.25 4.4 3.9a1 1 0 0 1 .96-.65h5.28a1 1 0 0 1 .96.65l1.65 5.35v2.5a1 1 0 0 1-1 1h-8.5a1 1 0 0 1-1-1z" {...stroke} />
      <path d="M2.75 9.25h3l.75 1.5h3l.75-1.5h3" {...stroke} />
    </svg>
  ),
  runs: (
    <svg {...icon}>
      <path d="M4.5 3.25v9.5L12.5 8z" {...stroke} />
    </svg>
  ),
  approvals: (
    <svg {...icon}>
      <circle cx="8" cy="8" r="5.25" {...stroke} />
      <path d="M6.6 6.1v3.8M9.4 6.1v3.8" {...stroke} />
    </svg>
  ),
  artifacts: (
    <svg {...icon}>
      <path d="M4.25 2.75h5l2.5 2.5v7a1 1 0 0 1-1 1h-6.5a1 1 0 0 1-1-1v-8.5a1 1 0 0 1 1-1z" {...stroke} />
      <path d="M9 2.75v2.75h2.75" {...stroke} />
    </svg>
  ),
  integrations: (
    <svg {...icon}>
      <path d="M6 2.75v2.5M10 2.75v2.5M4.5 5.25h7v2.5a3.5 3.5 0 0 1-7 0zM8 11.25v2" {...stroke} />
    </svg>
  ),
  members: (
    <svg {...icon}>
      <circle cx="6" cy="5.75" r="2.25" {...stroke} />
      <path d="M2.25 12.75c.5-1.9 1.9-3 3.75-3s3.25 1.1 3.75 3M10.5 3.75a2.25 2.25 0 0 1 0 4.25M11.75 9.9c1 .4 1.7 1.4 2 2.85" {...stroke} />
    </svg>
  ),
  billing: (
    <svg {...icon}>
      <rect x="2.25" y="3.75" width="11.5" height="8.5" rx="1.5" {...stroke} />
      <path d="M2.25 6.75h11.5M4.75 9.75h2" {...stroke} />
    </svg>
  ),
};

const workspace = [
  { key: "inbox", label: "Inbox", count: 4 },
  { key: "runs", label: "Runs" },
  { key: "approvals", label: "Approvals", count: 2, tone: "warning" as const },
  { key: "artifacts", label: "Artifacts" },
] as const;

const settings = [
  { key: "integrations", label: "Integrations" },
  { key: "members", label: "Members" },
  { key: "billing", label: "Billing" },
] as const;

type Page = (typeof workspace)[number]["key"] | (typeof settings)[number]["key"];

export default function SidebarExample() {
  const [page, setPage] = useState<Page>("runs");
  const title = [...workspace, ...settings].find((item) => item.key === page)?.label;

  return (
    <div className="h-[30rem] w-full max-w-3xl overflow-hidden rounded-xl border border-zinc-950/10 bg-white dark:border-white/10 dark:bg-black">
      <SidebarProvider mobileBreakpoint={600}>
        <Sidebar aria-label="Workspace">
          <SidebarHeader>
            <SidebarMenu>
              <SidebarMenuItem>
                <SidebarMenuButton size="lg" tooltip="Northwind">
                  <span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-zinc-950 text-xs font-semibold text-white dark:bg-white dark:text-black">
                    N
                  </span>
                  <span className="flex min-w-0 flex-col leading-tight">
                    <span className="truncate font-medium text-zinc-950 dark:text-white">Northwind</span>
                    <span className="truncate text-xs text-zinc-500">Team plan</span>
                  </span>
                </SidebarMenuButton>
              </SidebarMenuItem>
            </SidebarMenu>
          </SidebarHeader>

          <SidebarContent>
            <SidebarGroup>
              <SidebarGroupLabel>Workspace</SidebarGroupLabel>
              <SidebarMenu>
                {workspace.map((item) => (
                  <SidebarMenuItem key={item.key}>
                    <SidebarMenuButton isActive={page === item.key} tooltip={item.label} onClick={() => setPage(item.key)}>
                      {icons[item.key]}
                      <span className="truncate">{item.label}</span>
                      {"count" in item ? (
                        <SidebarMenuBadge tone={"tone" in item ? item.tone : "neutral"}>
                          {item.count}
                          <span className="sr-only"> {item.key === "approvals" ? "waiting" : "unread"}</span>
                        </SidebarMenuBadge>
                      ) : null}
                    </SidebarMenuButton>
                  </SidebarMenuItem>
                ))}
              </SidebarMenu>
            </SidebarGroup>

            <SidebarCollapsibleGroup label="Settings">
              <SidebarMenu>
                {settings.map((item) => (
                  <SidebarMenuItem key={item.key}>
                    <SidebarMenuButton isActive={page === item.key} tooltip={item.label} onClick={() => setPage(item.key)}>
                      {icons[item.key]}
                      <span className="truncate">{item.label}</span>
                    </SidebarMenuButton>
                  </SidebarMenuItem>
                ))}
              </SidebarMenu>
            </SidebarCollapsibleGroup>
          </SidebarContent>

          <SidebarFooter>
            <SidebarMenu>
              <SidebarMenuItem>
                <SidebarMenuButton size="lg" tooltip="Maya Chen">
                  <span className="flex size-8 shrink-0 items-center justify-center rounded-full border border-zinc-950/10 text-xs font-medium text-zinc-600 dark:border-white/15 dark:text-zinc-300">
                    MC
                  </span>
                  <span className="flex min-w-0 flex-col leading-tight">
                    <span className="truncate font-medium text-zinc-950 dark:text-white">Maya Chen</span>
                    <span className="truncate text-xs text-zinc-500">maya@northwind.dev</span>
                  </span>
                </SidebarMenuButton>
              </SidebarMenuItem>
            </SidebarMenu>
          </SidebarFooter>
        </Sidebar>

        <SidebarInset>
          <header className="flex h-12 shrink-0 items-center gap-2 border-b border-zinc-950/[0.07] px-3 dark:border-white/[0.08]">
            <SidebarTrigger />
            <span className="h-4 w-px bg-zinc-950/10 dark:bg-white/15" aria-hidden="true" />
            <h2 className="m-0 text-sm font-semibold text-zinc-950 dark:text-white">{title}</h2>
          </header>
          <div className="flex flex-1 flex-col gap-2 overflow-auto p-4">
            <p className="m-0 text-sm text-zinc-600 dark:text-zinc-400">
              Press the panel button or <kbd className="font-mono text-xs">⌘B</kbd> to switch between the full sidebar and icons only.
            </p>
            <div className="mt-2 grid gap-2 sm:grid-cols-2">
              {["Fix invoice rounding", "Upgrade to React 19", "Nightly evaluation", "Rotate API keys"].map((name) => (
                <div key={name} className="rounded-lg border border-zinc-950/[0.07] px-3 py-2.5 text-sm text-zinc-700 dark:border-white/[0.08] dark:text-zinc-300">
                  {name}
                </div>
              ))}
            </div>
          </div>
        </SidebarInset>
      </SidebarProvider>
    </div>
  );
}

API

PropTypeDefaultDescription
SidebarProvider collapsed / defaultCollapsed / onCollapsedChangeboolean / boolean / (collapsed) => void—Icon-only state. Leave collapsed unset for an uncontrolled sidebar.
SidebarProvider mobileBreakpointnumber768Below this width (measured on the provider, not the window) the sidebar moves into a sheet.
SidebarProvider keyboardShortcutstring | false"b"Letter that toggles the sidebar with Cmd or Ctrl. Ignored while typing in a field.
SidebarProvider width / collapsedWidthstring"16rem" / "3.5rem"Expanded and icon-only column widths as CSS lengths.
Sidebar aria-labelstring"Sidebar"Name of the nav landmark, and of the sheet on mobile.
SidebarMenuButton href / renderstring / ReactElement—With href the row is an <a>; or pass render={<Link href="…" />}. Otherwise a <button>.
SidebarMenuButton isActivebooleanfalseThe current page: aria-current="page" and the selected tint.
SidebarMenuButton tooltipReactNode—Shown on the right while the sidebar is icon-only.
SidebarMenuButton size"md" | "lg""md"32px rows, or 48px rows with a 32px tile for the header and footer.
SidebarMenuBadge tone"neutral" | "info" | "success" | "warning" | "danger""neutral"A plain mono count at the end of a row, colored only when it carries meaning.
SidebarCollapsibleGroup label / defaultOpen / open / onOpenChangeReactNode / boolean / boolean / (open) => voiddefaultOpen trueA group whose label toggles its menu. Stays open while icon-only.
SidebarGroup / SidebarGroupLabelComponentProps<"div">—A role="group" section named by its label.
SidebarTriggerComponentProps<"button">—Collapses or expands on desktop and opens the sheet on mobile.
useSidebar()() => { collapsed, setCollapsed, mobile, mobileOpen, setMobileOpen, toggle }—Reads and changes the state from custom controls.

Accessibility

  • The sidebar is a nav landmark; groups are role="group" named by their labels with aria-labelledby, and each menu is a list.
  • The current page row has aria-current="page" and reads by tint and weight, not color.
  • Labels stay in the accessibility tree while icon-only (they are only faded), and each row shows its tooltip on hover or keyboard focus.
  • SidebarTrigger reports aria-expanded, points at the sidebar with aria-controls, and lists the shortcut in aria-keyshortcuts. Cmd or Ctrl + B toggles it, except while typing in a field.
  • Collapsible group toggles are buttons with aria-expanded; while icon-only they are disabled and hidden so focus does not land on invisible controls.
  • On narrow layouts the sidebar is a modal sheet (Base UI Dialog): focus moves into it and is trapped, Escape or the backdrop closes it, and following a link closes it.
  • Collapsing animates the column width in 220ms while labels fade in 150ms, so icons never move; the sheet slides in over 260ms and out in 180ms. All of it is instant with reduced motion.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/sidebar.tsxsidebar
  • Also installs tooltip@0.1.1registry dependency
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/sidebar/0.1.1.json.

ui/sidebar.tsxShow
ui/sidebar.tsx
"use client";

import { Collapsible } from "@base-ui/react/collapsible";
import { Dialog } from "@base-ui/react/dialog";
import { mergeProps } from "@base-ui/react/merge-props";
import { useRender } from "@base-ui/react/use-render";
import {
  type ComponentProps,
  createContext,
  type CSSProperties,
  type MouseEvent,
  type ReactNode,
  useCallback,
  useContext,
  useEffect,
  useId,
  useMemo,
  useRef,
  useState,
} from "react";
import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const quint = "ease-[cubic-bezier(0.22,1,0.36,1)]";
const focusRing = "focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500";

interface SidebarContextValue {
  /** Whether the desktop sidebar shows icons only. */
  collapsed: boolean;
  setCollapsed: (collapsed: boolean) => void;
  /** Whether the provider is narrower than `mobileBreakpoint`, so the sidebar lives in a sheet. */
  mobile: boolean;
  /** Whether the mobile sheet is open. */
  mobileOpen: boolean;
  setMobileOpen: (open: boolean) => void;
  /** Collapses or expands on desktop; opens or closes the sheet on mobile. */
  toggle: () => void;
  /** Id of the sidebar element, for `aria-controls`. */
  sidebarId: string;
  shortcut: string | false;
}

const SidebarContext = createContext<SidebarContextValue | null>(null);

/** Reads the sidebar state from the nearest `SidebarProvider`, for custom triggers and layouts. */
export function useSidebar() {
  const context = useContext(SidebarContext);
  if (!context) throw new Error("useSidebar must be used inside a SidebarProvider.");
  return context;
}

export interface SidebarProviderProps extends ComponentProps<"div"> {
  /** Whether the sidebar shows icons only. Pass with `onCollapsedChange` to control it. */
  collapsed?: boolean;
  /** Initial collapsed state when uncontrolled. */
  defaultCollapsed?: boolean;
  /** Called when the sidebar collapses or expands. */
  onCollapsedChange?: (collapsed: boolean) => void;
  /**
   * Below this width, in pixels, the sidebar moves into a sheet opened by `SidebarTrigger`.
   * Measured on the provider itself, not the window, so it also works in a narrow pane.
   */
  mobileBreakpoint?: number;
  /** Letter that toggles the sidebar with Cmd (macOS) or Ctrl. `false` turns the shortcut off. */
  keyboardShortcut?: string | false;
  /** Expanded width, as a CSS length. */
  width?: string;
  /** Icon-only width, as a CSS length. The default centers 16px icons in the column. */
  collapsedWidth?: string;
}

/**
 * Holds the sidebar state and lays out a `Sidebar` beside a `SidebarInset`, its two direct children.
 * Collapsing animates the sidebar column (220ms, quint ease-out) while labels fade, so icons never
 * move; with reduced motion it switches instantly.
 */
export function SidebarProvider({
  collapsed: collapsedProp,
  defaultCollapsed = false,
  onCollapsedChange,
  mobileBreakpoint = 768,
  keyboardShortcut = "b",
  width = "16rem",
  collapsedWidth = "3.5rem",
  className,
  style,
  children,
  ...props
}: SidebarProviderProps) {
  const [uncontrolled, setUncontrolled] = useState(defaultCollapsed);
  const collapsed = collapsedProp ?? uncontrolled;
  const [mobile, setMobile] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const sidebarId = useId();

  const setCollapsed = useCallback(
    (next: boolean) => {
      if (collapsedProp === undefined) setUncontrolled(next);
      onCollapsedChange?.(next);
    },
    [collapsedProp, onCollapsedChange],
  );

  const toggle = useCallback(() => {
    if (mobile) setMobileOpen((open) => !open);
    else setCollapsed(!collapsed);
  }, [mobile, collapsed, setCollapsed]);

  useEffect(() => {
    const wrapper = wrapperRef.current;
    if (!wrapper) return;
    const observer = new ResizeObserver(([entry]) => {
      if (entry) setMobile(entry.contentRect.width < mobileBreakpoint);
    });
    observer.observe(wrapper);
    return () => observer.disconnect();
  }, [mobileBreakpoint]);

  // Leaving mobile layout closes the sheet, so it is not open behind the desktop sidebar.
  useEffect(() => {
    if (!mobile) setMobileOpen(false);
  }, [mobile]);

  useEffect(() => {
    if (!keyboardShortcut) return;
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key.toLowerCase() !== keyboardShortcut.toLowerCase() || !(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return;
      const target = event.target as HTMLElement | null;
      // Leave Cmd+B to text fields and editors, where it usually means bold.
      if (target?.closest("input, textarea, select, [contenteditable=''], [contenteditable='true']")) return;
      event.preventDefault();
      toggle();
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [keyboardShortcut, toggle]);

  const value = useMemo<SidebarContextValue>(
    () => ({ collapsed, setCollapsed, mobile, mobileOpen, setMobileOpen, toggle, sidebarId, shortcut: keyboardShortcut }),
    [collapsed, setCollapsed, mobile, mobileOpen, toggle, sidebarId, keyboardShortcut],
  );

  return (
    <SidebarContext.Provider value={value}>
      <div
        ref={wrapperRef}
        data-slot="sidebar-wrapper"
        data-collapsed={(collapsed && !mobile) || undefined}
        data-mobile={mobile || undefined}
        className={cx(
          "grid h-full min-h-0 w-full",
          mobile
            ? "grid-cols-[minmax(0,1fr)]"
            : cx(
                "grid-cols-[var(--sidebar-width)_minmax(0,1fr)] data-[collapsed]:grid-cols-[var(--sidebar-width-collapsed)_minmax(0,1fr)]",
                `transition-[grid-template-columns] duration-220 ${quint} motion-reduce:transition-none`,
              ),
          className,
        )}
        style={{ ...style, "--sidebar-width": width, "--sidebar-width-collapsed": collapsedWidth } as CSSProperties}
        {...props}
      >
        {children}
      </div>
    </SidebarContext.Provider>
  );
}

const surface = "bg-white text-zinc-950 dark:bg-black dark:text-white";

export interface SidebarProps extends ComponentProps<"nav"> {
  /** Accessible name of the navigation landmark and, on mobile, of the sheet. */
  "aria-label"?: string;
}

/**
 * The sidebar column, a `<nav>` landmark holding `SidebarHeader`, `SidebarContent`, and
 * `SidebarFooter`. In the mobile layout the same children render in a sheet that slides in from
 * the left edge (260ms in, 180ms out); it traps focus, closes on Escape or a backdrop press, and
 * closes when a `SidebarMenuButton` is followed.
 */
export function Sidebar({ "aria-label": label = "Sidebar", className, children, ...props }: SidebarProps) {
  const sidebar = useSidebar();
  const sheetValue = useMemo(() => ({ ...sidebar, collapsed: false }), [sidebar]);

  if (sidebar.mobile) {
    return (
      <Dialog.Root open={sidebar.mobileOpen} onOpenChange={sidebar.setMobileOpen}>
        <Dialog.Portal>
          <Dialog.Backdrop
            className={cx(
              "fixed inset-0 z-50 bg-black/40 dark:bg-black/70",
              "transition-opacity duration-260 ease-out motion-reduce:transition-none",
              "data-[starting-style]:opacity-0 data-[ending-style]:opacity-0 data-[ending-style]:duration-180",
            )}
          />
          <Dialog.Popup
            id={sidebar.sidebarId}
            aria-label={label}
            className={cx(
              "fixed inset-y-0 left-0 z-50 flex w-[min(18rem,calc(100vw-3rem))] flex-col outline-none",
              surface,
              "border-r border-zinc-950/10 shadow-[0_12px_32px_-8px_rgb(0_0_0/0.25)] dark:border-white/15 dark:shadow-[0_16px_48px_-12px_rgb(0_0_0/1)]",
              `transition-[translate,opacity] duration-260 ${quint} motion-reduce:transition-none`,
              "data-[starting-style]:-translate-x-full",
              // Exit is quicker and only partly slides, so the sheet gets out of the way.
              "data-[ending-style]:-translate-x-1/2 data-[ending-style]:opacity-0 data-[ending-style]:duration-180 data-[ending-style]:ease-out",
              "motion-reduce:data-[starting-style]:translate-x-0 motion-reduce:data-[ending-style]:translate-x-0",
            )}
          >
            <SidebarContext.Provider value={sheetValue}>
              <nav aria-label={label} className={cx("flex min-h-0 flex-1 flex-col", className)} {...props}>
                {children}
              </nav>
            </SidebarContext.Provider>
          </Dialog.Popup>
        </Dialog.Portal>
      </Dialog.Root>
    );
  }

  return (
    <nav
      id={sidebar.sidebarId}
      aria-label={label}
      data-slot="sidebar"
      data-collapsed={sidebar.collapsed || undefined}
      className={cx(
        "group/sidebar flex min-h-0 min-w-0 flex-col overflow-hidden border-r border-zinc-950/10 dark:border-white/10",
        surface,
        className,
      )}
      {...props}
    >
      {children}
    </nav>
  );
}

/** Top of the sidebar, usually a workspace switcher. Stays put while the content scrolls. */
export function SidebarHeader({ className, ...props }: ComponentProps<"div">) {
  return <div className={cx("flex shrink-0 flex-col gap-1 p-2", className)} {...props} />;
}

/** Bottom of the sidebar, usually the signed-in account. Separated by a hairline. */
export function SidebarFooter({ className, ...props }: ComponentProps<"div">) {
  return (
    <div className={cx("flex shrink-0 flex-col gap-1 border-t border-zinc-950/[0.07] p-2 dark:border-white/[0.08]", className)} {...props} />
  );
}

/** The scrolling middle of the sidebar, holding groups of menus. */
export function SidebarContent({ className, ...props }: ComponentProps<"div">) {
  return (
    <div
      className={cx(
        "flex min-h-0 flex-1 flex-col gap-3 overflow-x-hidden overflow-y-auto overscroll-contain px-2 py-1 [scrollbar-width:thin]",
        className,
      )}
      {...props}
    />
  );
}

/** A hairline between sections. */
export function SidebarSeparator({ className, ...props }: ComponentProps<"hr">) {
  return <hr className={cx("mx-2 my-1 h-px shrink-0 border-0 bg-zinc-950/[0.07] dark:bg-white/[0.08]", className)} {...props} />;
}

const GroupLabelContext = createContext<string | undefined>(undefined);

/** A labelled section of the sidebar. Put a `SidebarGroupLabel` and a `SidebarMenu` inside. */
export function SidebarGroup({ className, ...props }: ComponentProps<"div">) {
  const labelId = useId();
  return (
    <GroupLabelContext.Provider value={labelId}>
      <div role="group" aria-labelledby={labelId} className={cx("flex min-w-0 flex-col", className)} {...props} />
    </GroupLabelContext.Provider>
  );
}

// In icon-only mode the label fades out and a short hairline fades in at the same height,
// so the icons below keep their position.
const labelRow = cx(
  "relative flex h-8 min-w-0 shrink-0 items-center rounded-lg px-3 text-xs font-medium whitespace-nowrap text-zinc-500",
  "before:pointer-events-none before:absolute before:inset-x-3 before:top-1/2 before:h-px before:bg-zinc-950/10 before:opacity-0 dark:before:bg-white/15",
  "before:transition-opacity before:duration-150 before:ease-out group-data-[collapsed]/sidebar:before:opacity-100 motion-reduce:before:transition-none",
);
const labelText = cx(
  "truncate transition-[opacity,visibility] duration-150 ease-out motion-reduce:transition-none",
  "group-data-[collapsed]/sidebar:invisible group-data-[collapsed]/sidebar:opacity-0",
);

/** Names a `SidebarGroup`. Replaced by a short hairline while the sidebar is icon-only. */
export function SidebarGroupLabel({ className, children, ...props }: ComponentProps<"div">) {
  const id = useContext(GroupLabelContext);
  return (
    <div id={id} className={cx(labelRow, className)} {...props}>
      <span className={labelText}>{children}</span>
    </div>
  );
}

export interface SidebarCollapsibleGroupProps extends Omit<Collapsible.Root.Props, "className" | "children"> {
  /** Text of the group's toggle. */
  label: ReactNode;
  className?: string;
  /** The group's `SidebarMenu`. */
  children?: ReactNode;
}

/**
 * A group whose label toggles its menu open and closed. The menu height animates in 220ms
 * (instant with reduced motion). While the sidebar is icon-only the group stays open, since its
 * toggle is hidden.
 */
export function SidebarCollapsibleGroup({ label, defaultOpen = true, open, onOpenChange, className, children, ...props }: SidebarCollapsibleGroupProps) {
  const { collapsed } = useSidebar();
  const [innerOpen, setInnerOpen] = useState(open ?? defaultOpen);
  const isOpen = open ?? innerOpen;

  return (
    <Collapsible.Root
      open={collapsed || isOpen}
      onOpenChange={(next, details) => {
        if (collapsed) return;
        setInnerOpen(next);
        onOpenChange?.(next, details);
      }}
      className={cx("flex min-w-0 flex-col", className)}
      {...props}
    >
      <Collapsible.Trigger
        disabled={collapsed}
        className={cx(
          labelRow,
          "group/trigger w-full cursor-pointer gap-1 text-left",
          "transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
          "hover:bg-zinc-950/[0.04] hover:text-zinc-700 dark:hover:bg-white/[0.06] dark:hover:text-zinc-300",
          "group-data-[collapsed]/sidebar:pointer-events-none",
          focusRing,
        )}
      >
        <span className={labelText}>{label}</span>
        <svg
          aria-hidden="true"
          viewBox="0 0 16 16"
          fill="none"
          className={cx(
            "size-3 shrink-0 -rotate-90 group-data-[panel-open]/trigger:rotate-0",
            `transition-[rotate,opacity,visibility] duration-200 ${quint} motion-reduce:transition-none`,
            "group-data-[collapsed]/sidebar:invisible group-data-[collapsed]/sidebar:opacity-0",
          )}
        >
          <path d="m4.5 6.25 3.5 3.5 3.5-3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </Collapsible.Trigger>
      <Collapsible.Panel
        className={cx(
          "h-(--collapsible-panel-height) overflow-hidden",
          `transition-[height,opacity] duration-220 ${quint} motion-reduce:transition-none`,
          "data-[starting-style]:h-0 data-[starting-style]:opacity-0",
          "data-[ending-style]:h-0 data-[ending-style]:opacity-0 data-[ending-style]:duration-180",
        )}
      >
        {children}
      </Collapsible.Panel>
    </Collapsible.Root>
  );
}

/** A list of `SidebarMenuItem`s. */
export function SidebarMenu({ className, ...props }: ComponentProps<"ul">) {
  return <ul className={cx("m-0 flex min-w-0 list-none flex-col gap-px p-0", className)} {...props} />;
}

/** Wraps one `SidebarMenuButton`. */
export function SidebarMenuItem({ className, ...props }: ComponentProps<"li">) {
  return <li className={cx("relative flex min-w-0", className)} {...props} />;
}

const buttonSizes = {
  /** A 32px row: icon, label, optional badge. */
  md: "h-8 gap-2.5 px-3 text-sm",
  /** A 48px row for the header and footer: a 32px tile and two lines of text. */
  lg: "h-12 gap-2.5 px-1 text-sm",
} as const;

export interface SidebarMenuButtonProps extends Omit<useRender.ComponentProps<"button">, "children"> {
  /** Destination. With `href` the button renders an `<a>`; or pass `render={<Link href="…" />}`. */
  href?: string;
  /** Marks the current page: sets `aria-current="page"` and the selected tint. */
  isActive?: boolean;
  /** Row height. `lg` suits a workspace switcher or account row. */
  size?: keyof typeof buttonSizes;
  /** Text of the tooltip shown beside the icon while the sidebar is icon-only. */
  tooltip?: ReactNode;
  /** A leading icon or tile, then the label wrapped in a `<span>` (so it can fade), then an optional `SidebarMenuBadge`. */
  children?: ReactNode;
}

/**
 * A navigation row. Hover and the current page are shown with tints only (no moving indicator).
 * While the sidebar is icon-only, the label and badge fade out, the icon stays where it was, and
 * hovering or focusing the row shows `tooltip` on the right.
 */
export function SidebarMenuButton({
  href,
  isActive = false,
  size = "md",
  tooltip,
  render,
  className,
  onClick,
  ...props
}: SidebarMenuButtonProps) {
  const sidebar = useSidebar();
  const asLink = href !== undefined;

  const element = useRender({
    defaultTagName: asLink ? "a" : "button",
    render,
    props: mergeProps<"button">(
      {
        ...(asLink ? { href } : { type: "button" }),
        "aria-current": isActive ? "page" : undefined,
        className: cx(
          "flex w-full min-w-0 items-center overflow-hidden rounded-lg text-left whitespace-nowrap no-underline outline-none select-none",
          buttonSizes[size],
          "text-zinc-600 dark:text-zinc-400",
          "transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
          "hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
          "aria-[current=page]:bg-zinc-950/[0.06] aria-[current=page]:font-medium aria-[current=page]:text-zinc-950",
          "dark:aria-[current=page]:bg-white/[0.09] dark:aria-[current=page]:text-white",
          "data-[popup-open]:bg-zinc-950/[0.04] dark:data-[popup-open]:bg-white/[0.06]",
          focusRing,
          "[&_svg]:size-4 [&_svg]:shrink-0",
          // Everything after the leading icon or tile (label, badge) is a span that fades while icon-only.
          // Opacity only: the label must stay in the accessibility tree as the row's name.
          "[&>span:not(:first-child)]:transition-opacity [&>span:not(:first-child)]:duration-150 [&>span:not(:first-child)]:ease-out",
          "motion-reduce:[&>span:not(:first-child)]:transition-none",
          "group-data-[collapsed]/sidebar:[&>span:not(:first-child)]:opacity-0",
          className,
        ),
        onClick: (event: MouseEvent<HTMLButtonElement>) => {
          onClick?.(event);
          if (sidebar.mobile && sidebar.mobileOpen && !event.defaultPrevented && asLink) sidebar.setMobileOpen(false);
        },
      },
      props,
    ),
  });

  if (!tooltip) return element;
  return (
    <Tooltip disabled={!sidebar.collapsed}>
      <TooltipTrigger render={element} delay={0} />
      <TooltipContent side="right" sideOffset={10} arrow={false}>
        {tooltip}
      </TooltipContent>
    </Tooltip>
  );
}

const badgeTones = {
  neutral: "text-zinc-500",
  info: "text-sky-600 dark:text-sky-400",
  success: "text-emerald-600 dark:text-emerald-400",
  warning: "text-amber-600 dark:text-amber-400",
  danger: "text-red-600 dark:text-red-400",
} as const;

export interface SidebarMenuBadgeProps extends ComponentProps<"span"> {
  /** Colors the count when it carries meaning, for example `warning` for approvals waiting on someone. */
  tone?: keyof typeof badgeTones;
}

/**
 * A count at the end of a row, set in mono with tabular figures. Plain text rather than a pill,
 * so a long menu does not turn into a column of badges. Include context for screen readers when
 * the number alone is unclear, for example with a visually hidden "waiting".
 */
export function SidebarMenuBadge({ tone = "neutral", className, ...props }: SidebarMenuBadgeProps) {
  return <span className={cx("ml-auto pl-2 font-mono text-xs font-normal tabular-nums", badgeTones[tone], className)} {...props} />;
}

export interface SidebarTriggerProps extends ComponentProps<"button"> {
  /** Accessible name. */
  "aria-label"?: string;
}

/**
 * Collapses and expands the sidebar on desktop, and opens the sheet on mobile. Announces its state
 * with `aria-expanded` and the keyboard shortcut with `aria-keyshortcuts`.
 */
export function SidebarTrigger({ "aria-label": label = "Toggle sidebar", className, onClick, children, ...props }: SidebarTriggerProps) {
  const sidebar = useSidebar();
  const expanded = sidebar.mobile ? sidebar.mobileOpen : !sidebar.collapsed;
  const shortcut = sidebar.shortcut ? sidebar.shortcut.toUpperCase() : null;
  return (
    <button
      type="button"
      aria-label={label}
      aria-expanded={expanded}
      aria-controls={sidebar.mobile && !sidebar.mobileOpen ? undefined : sidebar.sidebarId}
      aria-keyshortcuts={shortcut ? `Meta+${shortcut} Control+${shortcut}` : undefined}
      className={cx(
        "inline-flex size-8 shrink-0 items-center justify-center rounded-lg text-zinc-500",
        "transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none",
        "hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white",
        "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
        className,
      )}
      onClick={(event) => {
        onClick?.(event);
        if (!event.defaultPrevented) sidebar.toggle();
      }}
      {...props}
    >
      {children ?? (
        <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4">
          <rect x="2.25" y="2.75" width="11.5" height="10.5" rx="2" stroke="currentColor" strokeWidth="1.5" />
          <path d="M6.25 3v10" stroke="currentColor" strokeWidth="1.5" />
        </svg>
      )}
    </button>
  );
}

/** The main area beside the sidebar. Render your page header and content inside. */
export function SidebarInset({ className, ...props }: ComponentProps<"div">) {
  return <div className={cx("flex min-h-0 min-w-0 flex-col", className)} {...props} />;
}