Skip to content
ilinxa/pro-ui

App Sidebar

alphav0.5.1

App-shell sidebar with a full-label mobile drawer, labels for every string, ancestor-overridable CSS variables, RTL, and a headless state hook.

Category: NavigationUpdated: 2026-10-24Created: 2026-05-22Author: ilinxa

Context

App-shell navigation for SaaS dashboards, social products, and developer tools. Single source of truth for the collapsible-sidebar pattern: built-in collapse + mobile drawer (Sheet) + tooltips-on-collapsed + sections + separators + permissions + localStorage persist + CSS-variable theme surface. Replaces the per-app reinvention of these 30 affordances. Migration origin: kasder's SocialSidebar.tsx.

Installation

Initialize shadcn (once per project)Seeds lib/utils.ts and components.json. Skip if you've already used any shadcn component.
pnpm dlx shadcn@latest init
Install the component
pnpm dlx shadcn@latest add @ilinxa/app-sidebar

Add -fixtures for dummy data:

pnpm dlx shadcn@latest add @ilinxa/app-sidebar-fixtures

CLI can't resolve @ilinxa? The namespace is listed in the official shadcn registry directory, so current CLIs need no configuration. If yours can't resolve it (older or pinned versions, self-hosted mirrors), register it manually in components.json:

"registries": {
  "@ilinxa": "https://ui.ilinxa.com/r/{name}.json"
}

Preview

activeVariant:

Full kasder recipe — brand · items · primary action · user footer

Active path: /social/home
Toggle collapse (top-right at lg+) to see brand/labels hide, badges flip to corner, tooltip shows on hover, footer dropdown align flips to center. Below lg the sidebar opens as a drawer — tap the hamburger above.

Flat list (no chrome)

Sections + separators + collapsible groups

Active path: /projects

v0.3.0 — renderItem slot (wraps defaultRender in TooltipWrapper)

Hover any row — the consumer-supplied TooltipWrapper wraps the library's default link. Inspect the DOM: each row is a SINGLE <li> (no double-nesting).
Active path: /social/home

v0.2.0 — multi-context: topSlot + {slug} templates + ownerOnly + minMembers + bypassFiltering

context: biz-acme · slug: acme

Active context: biz-acme

Active path: /bconsole/acme/dashboard

Items in this context: 6

  • Switch context in the popover — items + default path swap
  • Business contexts use {slug} in hrefs (Acme vs Globex)
  • Analytics / Settings / Billing hide unless isOwner
  • Team hidden unless currentMaxMembers ≥ 2
  • bypassFiltering reveals everything (still respects hidden:true)
  • collapse sidebar threads isCollapsed into BOTH<AppSidebar> AND the slotted <AccountSwitcher> — switcher trigger flips to icon-only along with the rest of the sidebar

v0.2.0 — headless useFilteredNavSections (no <AppSidebar>)

  • [dashboard]Dashboardhref: /bconsole/{slug}/dashboard
  • [posts]Postshref: /bconsole/{slug}/posts
  • [team]Teamhref: /bconsole/{slug}/team

Renders consumer-owned UI; library helper just does the filter math.

v0.5.0 — controlled isCollapsed (storageKey does not fight the prop)

isCollapsed (rendered): false

last requested via onCollapsedChange: —

The toggle requests !isCollapsed. With isCollapsed set, storageKey still persists section state but never reads or writes collapsed.

v0.5.0 — RTL (dir="rtl" ancestor, Arabic labels, side="start")

Sidebar docks on the inline start (right). Border, active bar, tooltips and collapse icons mirror; the arrow keys swap.

Path: /social/home

v0.5.0 — labels (tr) · badge names · formatBadgeCount · withheld (null) · brand tone

Collapse the rail: each badged row keeps an accessible name such as "Mesajlar, 1284 yeni"; the visible count is formatted by Intl.NumberFormat("tr").

  • Ana sayfa — numeric badge, tone destructive, activeTone brand (changes while the row is active)
  • Mesajlar — large count, formatted
  • Bildirimler — dot badge (name ends ", yeni")
  • Gelen kutusu — badge: { value: null } renders nothing; name stays the plain label

v0.5.0 — theming via ancestor CSS variables (no props)

The wrapper declares --ilinxa-sidebar-bg, --ilinxa-sidebar-border, --ilinxa-nav-active-bg/-fg, --ilinxa-nav-badge-corner-size and --ilinxa-sidebar-row-h. The sidebar sets none of them inline, so the ancestor wins. Values are design tokens.

v0.5.0 — drawer: full labels, topSlot as a function, drawerClassName / drawerStyle

The rail is icon-only, yet the drawer shows the brand label, full labels, inline-end badges and the full user footer.

Demo source

demo.tsxtsx
"use client"; import {  BarChart3,  Bell,  Bookmark,  Briefcase,  Building2,  Crown,  FileText,  Globe,  Home,  LogOut,  PlusSquare,  Settings,  User as UserIcon,  Users,} from "lucide-react";import { useMemo, useRef, useState } from "react";import { AccountSwitcher } from "../account-switcher/account-switcher";import type { SwitcherItem } from "../account-switcher/types";import { AppSidebar } from "./app-sidebar";import { useFilteredNavSections } from "./hooks/use-filtered-nav-sections";import { useAppSidebarMode } from "./contexts/sidebar-nav-context";import { AppSidebarTrigger } from "./parts/sidebar-nav-trigger";import { TooltipWrapper } from "./parts/tooltip-wrapper";import {  SIDEBAR_LABELS_AR,  SIDEBAR_LABELS_TR,  SIDEBAR_NAV_DUMMY_BADGES,  SIDEBAR_NAV_DUMMY_ITEMS,  SIDEBAR_NAV_DUMMY_RTL,  SIDEBAR_NAV_DUMMY_SECTIONED,} from "./dummy-data";import type {  NavEntry,  AppSidebarHandle,  AppSidebarProps,} from "./types"; const KSquareLogo = () => (  <span className="flex h-8 w-8 items-center justify-center rounded-md bg-(--ilinxa-nav-active-bg,var(--primary)) text-(--ilinxa-nav-active-fg,var(--primary-foreground)) text-sm font-bold">    K  </span>); export default function AppSidebarDemo() {  const [path, setPath] = useState("/social/home");  const [sectionedPath, setSectionedPath] = useState("/projects");  const [recipePath, setRecipePath] = useState("/social/home");  const [variant, setVariant] =    useState<NonNullable<AppSidebarProps["activeVariant"]>>("fill");  const kasderRecipeRef = useRef<AppSidebarHandle>(null);  const flatListRef = useRef<AppSidebarHandle>(null);  const sectionedRef = useRef<AppSidebarHandle>(null);   const interceptClick =    (setter: (p: string) => void) =>    ({ item, event }: { item: { href?: string }; event: React.MouseEvent }) => {      if (item.href) {        event.preventDefault();        setter(item.href);      }    };   return (    <div className="flex flex-col gap-6">      {/* Live activeVariant switcher */}      <div className="flex flex-wrap items-center gap-2">        <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">          activeVariant:        </span>        {(          ["fill", "left-bar", "right-bar", "outline", "subtle"] as const        ).map((v) => (          <button            key={v}            type="button"            onClick={() => setVariant(v)}            className={`rounded-md px-2.5 py-1 text-xs font-medium transition-colors ${              variant === v                ? "bg-primary text-primary-foreground"                : "bg-muted text-muted-foreground hover:bg-muted/80"            }`}          >            {v}          </button>        ))}      </div>       {/* Full kasder recipe — brand + items + primary action + footer */}      <div>        <p className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">          Full kasder recipe — brand · items · primary action · user footer        </p>        <div className="flex min-h-72 overflow-hidden rounded-lg border border-border bg-background lg:h-136">          <AppSidebar            ref={kasderRecipeRef}            items={SIDEBAR_NAV_DUMMY_ITEMS}            currentPath={recipePath}            onItemClick={interceptClick(setRecipePath)}            activeVariant={variant}            brand={{ logo: <KSquareLogo />, label: "Kasder", href: "/" }}            primaryAction={{              icon: PlusSquare,              label: "Post",              onClick: () => alert("Open post composer"),            }}            footer={{              user: {                name: "Alex Morgan",                handle: "@alexmorgan",                status: "online",              },              menuItems: [                { kind: "item", icon: UserIcon, label: "Profile", onClick: () => alert("profile") },                { kind: "item", icon: Settings, label: "Settings", onClick: () => alert("settings") },                { kind: "item", icon: Briefcase, label: "Business", onClick: () => alert("business") },                { kind: "separator" },                { kind: "item", icon: LogOut, label: "Log out", variant: "destructive", onClick: () => alert("logout") },              ],            }}            aria-label="Full recipe"          />          <div className="flex flex-1 flex-col items-start gap-3 p-4 sm:items-center sm:justify-center sm:p-6">            <AppSidebarTrigger              controls={kasderRecipeRef}              aria-label="Open navigation"              className="lg:hidden"            />            <p className="text-sm text-muted-foreground sm:text-center">              Active path: <span className="font-mono">{recipePath}</span>              <br />              <span className="text-xs">                Toggle collapse (top-right at <code>lg</code>+) to see                brand/labels hide, badges flip to corner, tooltip shows on                hover, footer dropdown align flips to center. Below{" "}                <code>lg</code> the sidebar opens as a drawer — tap the                hamburger above.              </span>            </p>          </div>        </div>      </div>       {/* Flat list */}      <div>        <p className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">          Flat list (no chrome)        </p>        <div className="flex min-h-56 overflow-hidden rounded-lg border border-border bg-background lg:h-96">          <AppSidebar            ref={flatListRef}            items={SIDEBAR_NAV_DUMMY_ITEMS}            currentPath={path}            onItemClick={interceptClick(setPath)}            activeVariant={variant}            aria-label="Flat nav demo"          />          <div className="flex flex-1 flex-col items-start gap-3 p-4 sm:items-center sm:justify-center sm:p-6">            <AppSidebarTrigger              controls={flatListRef}              aria-label="Open flat nav"              className="lg:hidden"            />            <p className="text-sm text-muted-foreground sm:text-center">              Active path: <span className="font-mono">{path}</span>            </p>          </div>        </div>      </div>       {/* Sectioned variant */}      <div>        <p className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">          Sections + separators + collapsible groups        </p>        <div className="flex min-h-56 overflow-hidden rounded-lg border border-border bg-background lg:h-96">          <AppSidebar            ref={sectionedRef}            items={SIDEBAR_NAV_DUMMY_SECTIONED}            currentPath={sectionedPath}            onItemClick={interceptClick(setSectionedPath)}            activeVariant={variant}            aria-label="Sectioned nav demo"          />          <div className="flex flex-1 flex-col items-start gap-3 p-4 sm:items-center sm:justify-center sm:p-6">            <AppSidebarTrigger              controls={sectionedRef}              aria-label="Open sectioned nav"              className="lg:hidden"            />            <p className="text-sm text-muted-foreground sm:text-center">              Active path: <span className="font-mono">{sectionedPath}</span>            </p>          </div>        </div>      </div>       <V03RenderItemSlotDemo variant={variant} />      <V02MultiContextDemo />      <V02HeadlessFilterDemo />      <V05ControlledDemo />      <V05RtlDemo />      <V05LabelsBadgesDemo />      <V05ThemingDemo />      <V05DrawerDemo />    </div>  );} // ─────────────────────────────────────────────────────────────────────────// v0.3.0 — renderItem slot demo (C1 + C6 regression anchor)//// Demonstrates the load-bearing pattern: wrap the library's defaultRender// in a consumer-supplied affordance. Pre-v0.3.0, returning `defaultRender`// produced double-nested <li><li>...</li></li>. The C1 ownership inversion// fix means the <li> is always owned by the library — consumer's renderItem// return value goes inside that one <li>.// ───────────────────────────────────────────────────────────────────────── function V03RenderItemSlotDemo({  variant,}: {  variant: NonNullable<AppSidebarProps["activeVariant"]>;}) {  const [renderItemPath, setRenderItemPath] = useState("/social/home");  const renderItemRef = useRef<AppSidebarHandle>(null);  return (    <div>      <p className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">        v0.3.0 — renderItem slot (wraps defaultRender in TooltipWrapper)      </p>      <div className="flex min-h-56 overflow-hidden rounded-lg border border-border bg-background lg:h-96">        <AppSidebar          ref={renderItemRef}          items={SIDEBAR_NAV_DUMMY_ITEMS}          currentPath={renderItemPath}          onItemClick={({ item, event }) => {            if (item.href) {              event.preventDefault();              setRenderItemPath(item.href);            }          }}          activeVariant={variant}          renderItem={({ defaultRender, item, isCollapsed }) => (            <TooltipWrapper              content={                <div className="flex flex-col gap-0.5">                  <span className="font-medium">{item.label}</span>                  <span className="text-[10px] text-muted-foreground">                    Slot-wrapped via renderItem                  </span>                </div>              }              side="right"              // collapsed rail already shows defaultRender's own tooltip —              // disable this one so the two don't stack              disabled={isCollapsed}            >              {defaultRender}            </TooltipWrapper>          )}          aria-label="renderItem slot demo"        />        <div className="flex flex-1 flex-col items-start gap-3 p-4 sm:items-center sm:justify-center sm:p-6">          <AppSidebarTrigger            controls={renderItemRef}            aria-label="Open renderItem demo"            className="lg:hidden"          />          <p className="text-sm text-muted-foreground sm:text-center">            Hover any row — the consumer-supplied TooltipWrapper wraps the            library&apos;s default link. Inspect the DOM: each row is a            SINGLE <code>&lt;li&gt;</code> (no double-nesting).            <br />            Active path: <span className="font-mono">{renderItemPath}</span>          </p>        </div>      </div>    </div>  );} // ─────────────────────────────────────────────────────────────────────────// v0.2.0 — Multi-context demo (topSlot + {slug} + ownerOnly + minMembers + bypass)//// Demonstrates the *real* v0.2 power: switching contexts in the topSlot// account-switcher changes BOTH the nav-item catalog AND the {slug} value// fed into href substitution. Each context has its own item set — matches// the source app-shell pattern (analysis §8.2 NavContext discriminant).// ───────────────────────────────────────────────────────────────────────── type V02ContextKey = "personal" | "biz-acme" | "biz-globex" | "platform"; const V02_SWITCHER_ITEMS: ReadonlyArray<SwitcherItem> = [  { key: "personal", label: "Personal", icon: UserIcon, href: "/home" },  { key: "biz-acme", label: "Acme Corp", icon: Building2, href: "/bconsole/acme" },  { key: "biz-globex", label: "Globex Industries", icon: Building2, href: "/bconsole/globex" },  { key: "platform", label: "Platform", icon: Globe, href: "/pconsole/overview" },]; // Per-context nav catalogs. Switching contexts swaps the entire item set;// {slug} substitution applies only when the context provides a slug.const V02_NAV_BY_CONTEXT: Record<V02ContextKey, ReadonlyArray<NavEntry>> = {  personal: [    { id: "home", label: "Home", icon: Home, href: "/home" },    { id: "profile", label: "Profile", icon: UserIcon, href: "/profile" },    { id: "notifications", label: "Notifications", icon: Bell, href: "/notifications", badge: 3 },    { id: "saved", label: "Saved items", icon: Bookmark, href: "/saved" },  ],  "biz-acme": [    { id: "dashboard", label: "Dashboard", icon: Briefcase, href: "/bconsole/{slug}/dashboard" },    { id: "posts", label: "Posts", icon: FileText, href: "/bconsole/{slug}/posts" },    { id: "team", label: "Team", icon: Users, href: "/bconsole/{slug}/team", minMembers: 2 },    { id: "analytics", label: "Analytics", icon: BarChart3, href: "/bconsole/{slug}/analytics", ownerOnly: true },    { id: "settings", label: "Settings", icon: Settings, href: "/bconsole/{slug}/settings", ownerOnly: true },    { id: "billing", label: "Billing", icon: Crown, href: "/bconsole/{slug}/billing", ownerOnly: true },  ],  "biz-globex": [    { id: "dashboard", label: "Dashboard", icon: Briefcase, href: "/bconsole/{slug}/dashboard" },    { id: "posts", label: "Posts", icon: FileText, href: "/bconsole/{slug}/posts" },    { id: "team", label: "Team", icon: Users, href: "/bconsole/{slug}/team", minMembers: 2 },    { id: "analytics", label: "Analytics", icon: BarChart3, href: "/bconsole/{slug}/analytics", ownerOnly: true },    { id: "settings", label: "Settings", icon: Settings, href: "/bconsole/{slug}/settings", ownerOnly: true },    { id: "billing", label: "Billing", icon: Crown, href: "/bconsole/{slug}/billing", ownerOnly: true },  ],  platform: [    { id: "overview", label: "Overview", icon: Globe, href: "/pconsole/overview" },    { id: "users", label: "All users", icon: Users, href: "/pconsole/users", ownerOnly: true },    { id: "audit", label: "Audit log", icon: FileText, href: "/pconsole/audit", ownerOnly: true },    { id: "platform-settings", label: "Platform settings", icon: Settings, href: "/pconsole/settings", ownerOnly: true },  ],}; const V02_DEFAULT_PATH_BY_CONTEXT: Record<V02ContextKey, string> = {  personal: "/home",  "biz-acme": "/bconsole/acme/dashboard",  "biz-globex": "/bconsole/globex/dashboard",  platform: "/pconsole/overview",}; function V02MultiContextDemo() {  const [activeContextKey, setActiveContextKey] = useState<V02ContextKey>("biz-acme");  const [isOwner, setIsOwner] = useState(true);  const [maxMembers, setMaxMembers] = useState(5);  const [bypass, setBypass] = useState(false);  const [currentPath, setCurrentPath] = useState(V02_DEFAULT_PATH_BY_CONTEXT["biz-acme"]);  // Lift collapsed state so it threads to BOTH <AppSidebar> AND the slotted  // <AccountSwitcher> — the canonical collapse-aware composition recipe.  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);  const v02SidebarRef = useRef<AppSidebarHandle>(null);   // Items + slug derive purely from the current context.  const items = V02_NAV_BY_CONTEXT[activeContextKey];   const slug = activeContextKey.startsWith("biz-")    ? activeContextKey.slice(4)    : undefined;   const templateValues = useMemo(    () => (slug ? { slug } : undefined),    [slug],  );   const handleContextSwitch = (item: SwitcherItem) => {    const next = item.key as V02ContextKey;    setActiveContextKey(next);    setCurrentPath(V02_DEFAULT_PATH_BY_CONTEXT[next]);  };   return (    <div>      <p className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">        v0.2.0 — multi-context: topSlot + &#123;slug&#125; templates + ownerOnly + minMembers + bypassFiltering      </p>      <div className="mb-3 flex flex-wrap items-center gap-4 rounded-md border border-border bg-card p-3 text-xs">        <label className="flex items-center gap-2">          <input            type="checkbox"            checked={isOwner}            onChange={(e) => setIsOwner(e.target.checked)}          />          isOwner        </label>        <label className="flex items-center gap-2">          currentMaxMembers:          <input            type="number"            min={0}            max={50}            value={maxMembers}            onChange={(e) => setMaxMembers(Number(e.target.value) || 0)}            className="w-16 rounded border border-border bg-background px-2 py-0.5"          />        </label>        <label className="flex items-center gap-2">          <input            type="checkbox"            checked={bypass}            onChange={(e) => setBypass(e.target.checked)}          />          bypassFiltering        </label>        <label className="flex items-center gap-2">          <input            type="checkbox"            checked={sidebarCollapsed}            onChange={(e) => setSidebarCollapsed(e.target.checked)}          />          collapse sidebar        </label>        <span className="ml-auto font-mono text-muted-foreground">          context: <code>{activeContextKey}</code>          {slug ? (            <>              {" "}· slug: <code>{slug}</code>            </>          ) : null}        </span>      </div>      <div className="flex min-h-72 overflow-hidden rounded-lg border border-border bg-background lg:h-136">        <AppSidebar          ref={v02SidebarRef}          items={items}          currentPath={currentPath}          isCollapsed={sidebarCollapsed}          onCollapsedChange={({ collapsed }) => setSidebarCollapsed(collapsed)}          onItemClick={({ item, event }) => {            if (item.href) {              event.preventDefault();              setCurrentPath(item.href);            }          }}          topSlot={            <AccountSwitcher              items={V02_SWITCHER_ITEMS}              activeKey={activeContextKey}              onSelect={handleContextSwitch}              isCollapsed={sidebarCollapsed}            />          }          hrefTemplateValues={templateValues}          isOwner={isOwner}          currentMaxMembers={maxMembers}          bypassFiltering={bypass}          aria-label="v0.2 multi-context demo"        />        <div className="flex flex-1 flex-col gap-2 p-4 text-sm text-muted-foreground sm:p-6">          <AppSidebarTrigger            controls={v02SidebarRef}            aria-label="Open v0.2 multi-context nav"            className="self-start lg:hidden"          />          <p>Active context: <code className="font-mono">{activeContextKey}</code></p>          <p>Active path: <code className="font-mono break-all">{currentPath}</code></p>          <p className="text-xs">Items in this context: <code>{items.length}</code></p>          <ul className="ml-4 list-disc space-y-1 text-xs">            <li>Switch context in the popover — items + default path swap</li>            <li>Business contexts use <code>&#123;slug&#125;</code> in hrefs (Acme vs Globex)</li>            <li><code>Analytics</code> / <code>Settings</code> / <code>Billing</code> hide unless <code>isOwner</code></li>            <li><code>Team</code> hidden unless <code>currentMaxMembers ≥ 2</code></li>            <li><code>bypassFiltering</code> reveals everything (still respects <code>hidden:true</code>)</li>            <li>              <code>collapse sidebar</code> threads <code>isCollapsed</code> into BOTH              <code>&lt;AppSidebar&gt;</code> AND the slotted{" "}              <code>&lt;AccountSwitcher&gt;</code> — switcher trigger flips to              icon-only along with the rest of the sidebar            </li>          </ul>        </div>      </div>    </div>  );} // ─────────────────────────────────────────────────────────────────────────// v0.2.0 — Headless useFilteredNavSections (standalone, no <AppSidebar>)// ───────────────────────────────────────────────────────────────────────── function V02HeadlessFilterDemo() {  const [isOwner, setIsOwner] = useState(false);  const filtered = useFilteredNavSections({    sections: V02_NAV_BY_CONTEXT["biz-acme"],    isOwner,    currentMaxMembers: 10,  });  return (    <div>      <p className="mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">        v0.2.0 — headless useFilteredNavSections (no &lt;AppSidebar&gt;)      </p>      <div className="flex flex-col gap-3 rounded-lg border border-border bg-card p-4 text-sm">        <label className="flex items-center gap-2 text-xs">          <input            type="checkbox"            checked={isOwner}            onChange={(e) => setIsOwner(e.target.checked)}          />          isOwner (toggle to flip Settings + Billing visibility)        </label>        <ul className="flex flex-col gap-1">          {filtered.map((entry, index) =>            entry.kind === "section" ? null : entry.kind === "separator" ? (              <li key={entry.id ?? `sep-${index}`} className="my-1 h-px bg-border" />            ) : (              <li                key={entry.id}                className="flex flex-col gap-0.5 sm:flex-row sm:flex-wrap sm:items-center sm:gap-2"              >                <span className="flex items-center gap-2">                  <span className="font-mono text-xs text-muted-foreground">[{entry.id}]</span>                  <span>{entry.label}</span>                </span>                <span className="min-w-0 text-xs text-muted-foreground sm:ml-auto">                  href:{" "}                  <code className="break-all">{entry.href}</code>                </span>              </li>            ),          )}        </ul>        <p className="text-xs text-muted-foreground">          Renders consumer-owned UI; library helper just does the filter math.        </p>      </div>    </div>  );} // ─────────────────────────────────────────────────────────────────────────// v0.5.0 demos// ───────────────────────────────────────────────────────────────────────── const V05_FRAME =  "flex min-h-72 overflow-hidden rounded-lg border border-border bg-background lg:h-112";const V05_HEADING =  "mb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground"; function V05Pane({ children }: { children: React.ReactNode }) {  return (    <div className="flex flex-1 flex-col gap-2 p-4 text-sm text-muted-foreground sm:p-6">      {children}    </div>  );} function interceptHref(setter: (p: string) => void) {  return ({ item, event }: { item: { href?: string }; event: React.MouseEvent }) => {    if (item.href) {      event.preventDefault();      setter(item.href);    }  };} // Controlled collapse — the parent owns `isCollapsed`. `storageKey` is set to// prove storage no longer reads/writes `collapsed` while the prop is defined.function V05ControlledDemo() {  const [collapsed, setCollapsed] = useState(false);  const [accept, setAccept] = useState(true);  const [requested, setRequested] = useState<boolean | null>(null);  const [path, setPath] = useState("/social/home");  return (    <div>      <p className={V05_HEADING}>        v0.5.0 — controlled isCollapsed (storageKey does not fight the prop)      </p>      <div className={V05_FRAME}>        <AppSidebar          items={SIDEBAR_NAV_DUMMY_ITEMS}          currentPath={path}          onItemClick={interceptHref(setPath)}          isCollapsed={collapsed}          onCollapsedChange={({ collapsed: next }) => {            setRequested(next);            if (accept) setCollapsed(next);          }}          storageKey="app-sidebar-demo-controlled"          aria-label="Controlled collapse demo"        />        <V05Pane>          <label className="flex items-center gap-2 text-xs">            <input              type="checkbox"              checked={accept}              onChange={(e) => setAccept(e.target.checked)}            />            parent accepts the request (untick: the rail must not move)          </label>          <p>            isCollapsed (rendered):{" "}            <code className="font-mono">{String(collapsed)}</code>          </p>          <p>            last requested via onCollapsedChange:{" "}            <code className="font-mono">              {requested === null ? "—" : String(requested)}            </code>          </p>          <p className="text-xs">            The toggle requests <code>!isCollapsed</code>. With{" "}            <code>isCollapsed</code> set, <code>storageKey</code> still persists            section state but never reads or writes <code>collapsed</code>.          </p>        </V05Pane>      </div>    </div>  );} // RTL — `dir="rtl"` on an ancestor; side="start" (default) docks on the right.function V05RtlDemo() {  const [path, setPath] = useState("/social/home");  return (    <div>      <p className={V05_HEADING}>        v0.5.0 — RTL (dir=&quot;rtl&quot; ancestor, Arabic labels, side=&quot;start&quot;)      </p>      <div dir="rtl" className={V05_FRAME}>        <AppSidebar          items={SIDEBAR_NAV_DUMMY_RTL}          currentPath={path}          onItemClick={interceptHref(setPath)}          labels={SIDEBAR_LABELS_AR}          brand={{ logo: <KSquareLogo />, label: "كاسدر", href: "/" }}          footer={{            user: { name: "أليكس مورغان", handle: "@alex", status: "online" },            menuItems: [              { kind: "item", icon: UserIcon, label: "الملف الشخصي" },              { kind: "item", icon: LogOut, label: "تسجيل الخروج", variant: "destructive" },            ],          }}          aria-label="RTL demo"        />        <V05Pane>          <p>            Sidebar docks on the inline start (right). Border, active bar,            tooltips and collapse icons mirror; the arrow keys swap.          </p>          <p>            Path: <span className="font-mono" dir="ltr">{path}</span>          </p>        </V05Pane>      </div>    </div>  );} // Turkish labels, badges (number / dot / withheld), formatBadgeCount, brand tone.function V05LabelsBadgesDemo() {  const [path, setPath] = useState("/social/home");  const [collapsed, setCollapsed] = useState(false);  const formatTr = useMemo(() => {    const nf = new Intl.NumberFormat("tr");    return (value: number, max: number) =>      value > max ? `${nf.format(max)}+` : nf.format(value);  }, []);  return (    <div>      <p className={V05_HEADING}>        v0.5.0 — labels (tr) · badge names · formatBadgeCount · withheld (null) · brand tone      </p>      <div className={V05_FRAME}>        <AppSidebar          items={SIDEBAR_NAV_DUMMY_BADGES}          currentPath={path}          onItemClick={interceptHref(setPath)}          isCollapsed={collapsed}          onCollapsedChange={({ collapsed: next }) => setCollapsed(next)}          labels={SIDEBAR_LABELS_TR}          formatBadgeCount={formatTr}          footer={{            user: { name: "Ayşe Yılmaz", status: "online" },            menuItems: [{ kind: "item", icon: Settings, label: "Ayarlar" }],          }}          aria-label="Labels and badges demo"        />        <V05Pane>          <p>            Collapse the rail: each badged row keeps an accessible name such as{" "}            <code>&quot;Mesajlar, 1284 yeni&quot;</code>; the visible count is            formatted by <code>Intl.NumberFormat(&quot;tr&quot;)</code>.          </p>          <ul className="ml-4 list-disc space-y-1 text-xs">            <li>Ana sayfa — numeric badge, <code>tone</code> destructive, <code>activeTone</code> brand (changes while the row is active)</li>            <li>Mesajlar — large count, formatted</li>            <li>Bildirimler — dot badge (name ends &quot;, yeni&quot;)</li>            <li>Gelen kutusu — <code>badge: &#123; value: null &#125;</code> renders nothing; name stays the plain label</li>          </ul>        </V05Pane>      </div>    </div>  );} // Theming — ancestor CSS variables win over built-in defaults. Tokens only.function V05ThemingDemo() {  const [path, setPath] = useState("/social/home");  const themed = {    "--ilinxa-sidebar-bg": "var(--muted)",    "--ilinxa-sidebar-border": "var(--ring)",    "--ilinxa-nav-active-bg": "var(--accent)",    "--ilinxa-nav-active-fg": "var(--accent-foreground)",    "--ilinxa-nav-badge-corner-size": "1.25rem",    "--ilinxa-sidebar-row-h": "3rem",  } as React.CSSProperties;  return (    <div>      <p className={V05_HEADING}>        v0.5.0 — theming via ancestor CSS variables (no props)      </p>      <div style={themed} className={V05_FRAME}>        <AppSidebar          items={SIDEBAR_NAV_DUMMY_ITEMS}          currentPath={path}          onItemClick={interceptHref(setPath)}          aria-label="Theming demo"        />        <V05Pane>          <p>            The wrapper declares <code>--ilinxa-sidebar-bg</code>,{" "}            <code>--ilinxa-sidebar-border</code>,{" "}            <code>--ilinxa-nav-active-bg</code>/<code>-fg</code>,{" "}            <code>--ilinxa-nav-badge-corner-size</code> and{" "}            <code>--ilinxa-sidebar-row-h</code>. The sidebar sets none of them            inline, so the ancestor wins. Values are design tokens.          </p>        </V05Pane>      </div>    </div>  );} function ModeChip() {  const mode = useAppSidebarMode();  return (    <div className="px-3 py-2 text-xs text-muted-foreground">      topSlot mode: <code className="font-mono">{mode ?? "none"}</code>    </div>  );} // Drawer — rail is collapsed; the drawer (portalled) shows full labels.function V05DrawerDemo() {  const ref = useRef<AppSidebarHandle>(null);  const [path, setPath] = useState("/social/home");  return (    <div>      <p className={V05_HEADING}>        v0.5.0 — drawer: full labels, topSlot as a function, drawerClassName / drawerStyle      </p>      <div className={V05_FRAME}>        <AppSidebar          ref={ref}          items={SIDEBAR_NAV_DUMMY_ITEMS}          currentPath={path}          onItemClick={interceptHref(setPath)}          defaultCollapsed          topSlot={({ mode }) =>            mode === "mobile" ? (              <ModeChip />            ) : null          }          brand={{ logo: <KSquareLogo />, label: "Kasder", href: "/" }}          primaryAction={{ icon: PlusSquare, label: "Post" }}          footer={{            user: { name: "Alex Morgan", handle: "@alexmorgan", status: "online" },            menuItems: [{ kind: "item", icon: Settings, label: "Settings" }],          }}          drawerClassName="border-primary"          drawerStyle={{ "--ilinxa-sidebar-drawer-w": "20rem" } as React.CSSProperties}          aria-label="Drawer demo"        />        <V05Pane>          <button            type="button"            onClick={() => ref.current?.openMobile()}            className="self-start rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground"          >            Open drawer (ref.openMobile)          </button>          <p className="text-xs">            The rail is icon-only, yet the drawer shows the brand label, full            labels, inline-end badges and the full user footer.          </p>        </V05Pane>      </div>    </div>  );} 

Usage

Status

v0.5.0 ships the full AppSidebarProps surface: items, sections, collapse (controlled, uncontrolled or lifted), a mobile drawer that shows full labels, slots and render props, permission gates, and a localStorage opt-in. v0.5.0 adds labels, badge accessible names, formatBadgeCount, CSS-variable theming that ancestors can override (and that reaches the drawer), RTL, side="start" | "end", a brand badge tone and a corrected controlled-collapse toggle.

When to use

Reach for AppSidebar for any app shell that needs a collapsible navigation column with a mobile drawer fallback. It replaces the per-app reinvention of collapse, sections, badges, tooltips on the collapsed rail, permission gating, persistence, reduced motion and WAI-ARIA.

Basic example

Define the link adapter at module scope: a component declared inline in render has a new identity on every render, which remounts every row.

import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  AppSidebar,
  type NavItem,
  type NavLinkProps,
} from "@/components/app-sidebar";

const items: NavItem[] = [
  { id: "home", label: "Home", href: "/" },
  { id: "inbox", label: "Inbox", href: "/inbox", badge: 12 },
];

// Module scope: stable identity across renders.
function AppLink({ href, children, ...rest }: NavLinkProps) {
  return (
    <Link href={href} {...rest}>
      {children}
    </Link>
  );
}

export function AppShell({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  return (
    <div className="flex min-h-screen">
      <AppSidebar items={items} currentPath={pathname} linkComponent={AppLink} />
      <main className="flex-1">{children}</main>
    </div>
  );
}

Key props

  • items — flat NavItem[] or mixed NavEntry[] (items / sections / separators)
  • currentPath + optional isActive predicate drive active-row detection (no router coupling)
  • linkComponent— your router's link primitive (default <a href>)
  • storageKey — opt-in localStorage persistence of collapse and section state
  • activeVariant — "fill" (default) / "left-bar" / "right-bar" / "outline" / "subtle"

Controlled collapse + cookie (no flash)

The server reads a cookie and passes isCollapsed, so the first paint already has the right width. onCollapsedChange writes the cookie. With isCollapsed defined, storageKey no longer reads or writes collapsed (section state still persists), and the toggle requests !isCollapsed — the rendered width changes only when your prop does.

// app/layout.tsx (server)
import { cookies } from "next/headers";
import { Shell } from "./shell";

export default async function Layout({ children }: { children: React.ReactNode }) {
  const collapsed = (await cookies()).get("sidebar-collapsed")?.value === "1";
  return <Shell initialCollapsed={collapsed}>{children}</Shell>;
}

// app/shell.tsx (client)
"use client";
import { useState } from "react";
import { AppSidebar } from "@/components/app-sidebar";
import { items, AppLink } from "./nav"; // AppLink lives at module scope

export function Shell({
  initialCollapsed,
  children,
}: {
  initialCollapsed: boolean;
  children: React.ReactNode;
}) {
  const [collapsed, setCollapsed] = useState(initialCollapsed);
  return (
    <div className="flex min-h-screen">
      <AppSidebar
        items={items}
        currentPath="/"
        linkComponent={AppLink}
        isCollapsed={collapsed}
        onCollapsedChange={({ collapsed: next }) => {
          setCollapsed(next);
          document.cookie = "sidebar-collapsed=" + (next ? "1" : "0") + "; path=/; max-age=31536000";
        }}
        storageKey="app-sidebar" // sections persist; collapsed is left alone
      />
      <main className="flex-1">{children}</main>
    </div>
  );
}

The same rule applies to isMobileOpen / onMobileOpenChange.

RTL

Put dir="rtl" on any ancestor (or pass the dir prop). side="start" is the default, so the sidebar docks on the right in RTL and on the left in LTR; "end" is the opposite, and "left" / "right" stay physical. Border, active bar, tooltips and collapse icons mirror, the arrow keys swap, and the drawer opens from the same logical side (override with mobileDrawerSide).

<div dir="rtl">
  <AppSidebar
    items={items}
    currentPath={pathname}
    linkComponent={AppLink}
    labels={arabicLabels}
  />
</div>

Labels (i18n)

labels is an AppSidebarLabelsInput merged over DEFAULT_APP_SIDEBAR_LABELS; a key passed as undefined keeps its default. emptyState merges per reason. Labels travel in context, so AppSidebarTrigger inside the subtree reads them too; a trigger OUTSIDE the sidebar (with controls) cannot — pass its aria-label. Existing aria-label, skipLinkLabel and trigger aria-label props still override.

import type { AppSidebarLabels } from "@/components/app-sidebar";

const tr: AppSidebarLabels = {
  navigation: "Ana gezinme",
  expandSidebar: "Kenar çubuğunu genişlet",
  collapseSidebar: "Kenar çubuğunu daralt",
  openNavigation: "Gezinmeyi aç",
  closeNavigation: "Gezinmeyi kapat",
  skipToContent: "İçeriğe geç",
  loading: "Gezinme öğeleri yükleniyor",
  userMenu: (name) => name + " — menüyü aç",
  itemWithBadge: (label, value) => label + ", " + value + " yeni",
  itemWithIndicator: (label) => label + ", yeni",
  emptyState: {
    "no-items": { title: "Öğe yok", body: "Gezinmeyi doldurmak için items verin." },
    "all-filtered-by-permission": { title: "Görünür öğe yok" },
    "all-hidden": { title: "Tüm öğeler gizli" },
    "all-filtered-by-loading": { title: "Öğe yok" },
  },
};

<AppSidebar items={items} currentPath={pathname} labels={tr} />

Badges: accessible names, formatting, withheld counts

  • A row whose badge is a number or string is named labels.itemWithBadge(label, value) — collapsed and expanded alike (the collapsed rail has no visible text, so the badge must be in the name). Dot and pulse badges use labels.itemWithIndicator(label).
  • formatBadgeCount(value, max) formats the visible count. Default: "{max}+" above max, otherwise String(value).
  • badge: null or { value: null } means the count is withheld (privacy / permissions): nothing renders and the accessible name is the plain label. A zero also renders nothing unless showZero.
  • Badge tone accepts "default" / "accent" / "destructive" / "muted" / "brand"; activeTone replaces it while the row is active.
  • Presence dots use --success (online), --warning (away), --destructive (busy) and --muted-foreground (offline). The registry item declares fallbacks for --success, --warning and --brand; your theme values win.
const nf = new Intl.NumberFormat("tr");
// Module scope or useMemo — keep the reference stable.
const formatTr = (value: number, max: number) =>
  value > max ? nf.format(max) + "+" : nf.format(value);

const items: NavItem[] = [
  {
    id: "chat",
    label: "Mesajlar",
    href: "/chat",
    badge: { value: 4, tone: "destructive", activeTone: "brand" },
  },
  { id: "inbox", label: "Gelen kutusu", href: "/inbox", badge: { value: null } }, // withheld
];

<AppSidebar items={items} currentPath={pathname} formatBadgeCount={formatTr} />

Theming with CSS variables

The sidebar sets a variable inline only for a prop you passed (collapsedWidth, expandedWidth, transitionDuration) or put in style / drawerStyle. Every read carries its default as a var(--x, default) fallback, so a declaration on any ancestor wins over the default, and an inline value wins over the ancestor. The drawer is portalled out of the tree; it copies the effective --ilinxa-* values from the in-tree wrapper when it opens. The full list is exported as APP_SIDEBAR_CSS_VARS.

VariableDefault
--ilinxa-sidebar-w-collapsed5rem
--ilinxa-sidebar-w-expanded16rem
--ilinxa-sidebar-transition-duration300ms
--ilinxa-sidebar-drawer-w18rem
--ilinxa-sidebar-bgvar(--card)
--ilinxa-sidebar-fgvar(--foreground)
--ilinxa-nav-row-radiusvar(--radius-lg)
--ilinxa-nav-hover-bgvar(--muted)
--ilinxa-sidebar-bordervar(--border)
--ilinxa-sidebar-row-h2.75rem
--ilinxa-sidebar-row-gap0.25rem
--ilinxa-sidebar-px0.75rem
--ilinxa-nav-active-bgvar(--primary)
--ilinxa-nav-active-fgvar(--primary-foreground)
--ilinxa-nav-active-bar-w3px
--ilinxa-nav-badge-size1.25rem
--ilinxa-nav-badge-corner-size1rem
--ilinxa-nav-badge-halovar(--card)
--ilinxa-nav-indent-step0 (expanded rail only)

Mapping onto the shadcn sidebar tokens, with the prototype-parity corner badge size:

/* globals.css — or a wrapper's style prop */
.app-shell {
  --ilinxa-sidebar-bg: var(--sidebar);
  --ilinxa-sidebar-border: var(--sidebar-border);
  --ilinxa-nav-active-bg: var(--sidebar-primary);
  --ilinxa-nav-active-fg: var(--sidebar-primary-foreground);
  --ilinxa-nav-badge-corner-size: 1.25rem;
}

Drawer

Below mobileBreakpoint the sidebar becomes a Sheet. The drawer always renders full labels: brand label, inline-end badges, the full user footer and primary action, and render props receive isCollapsed: false even when the desktop rail is collapsed. Style it with drawerClassName and drawerStyle. topSlot may be a function of { mode, isCollapsed }; inside any slot, useAppSidebarMode() returns "desktop" | "mobile" (or null outside the sidebar). The handle's openMobile() opens the drawer on any viewport (handy for demos); on a desktop viewport an item click does not auto-close it — auto-close is a mobile-viewport behaviour.

import { AppSidebar, useAppSidebarMode } from "@/components/app-sidebar";

function ModeBadge() {
  const mode = useAppSidebarMode(); // "desktop" | "mobile" | null
  return <span>{mode}</span>;
}

<AppSidebar
  items={items}
  currentPath={pathname}
  topSlot={({ isCollapsed }) => (
    <AccountSwitcher
      items={switcherItems}
      activeKey={activeKey}
      onSelect={onSelect}
      isCollapsed={isCollapsed} // always false inside the drawer
    />
  )}
  drawerClassName="border-primary"
  drawerStyle={{ "--ilinxa-sidebar-drawer-w": "20rem" } as React.CSSProperties}
/>

Multi-tenant additions

  • topSlot — slot above the brand row for an AccountSwitcher, governance bar or banner. Renders nothing when omitted.
  • hrefTemplateValues — substitutes {key} placeholders in every NavItem.href ({ slug: 'acme' } turns /biz/{slug}/team into /biz/acme/team). resolveHref(item, values) wins when both are given; keep it a stable callback.
  • NavItem.ownerOnly + isOwner, and NavItem.minMembers + currentMaxMembers — both gates must pass alongside permission.
  • bypassFiltering skips all three gates at section and item level; hidden: true is still respected. keepEmptySections keeps a section whose items were all filtered out.
  • type NavContext — type-only discriminated union for your URL-to-context derivation.

Headless: useAppSidebarState and useFilteredNavSections

useAppSidebarState lifts the sidebar state so other components (a header trigger, a command palette) can read and drive it; pass the result as state. It forwards the same gate options as the component: isOwner (default false), currentMaxMembers (default Infinity), bypassFiltering and keepEmptySections. useFilteredNavSections({ sections, permissions?, isOwner?, currentMaxMembers?, bypassFiltering? }) is the pure filter helper, usable without <AppSidebar>.

const state = useAppSidebarState({
  items,
  currentPath: pathname,
  storageKey: "app-sidebar",
  isOwner,
  currentMaxMembers: plan.seats,
  bypassFiltering: false,
  keepEmptySections: false,
});

<AppSidebar items={items} currentPath={pathname} state={state} isOwner={isOwner} currentMaxMembers={plan.seats} />

Collapse-aware composition

A slotted <AccountSwitcher> is not viewport-aware on its own. Either lift the collapsed state and pass it to both, or use the function form of topSlot shown above, which receives the right value in the rail and in the drawer. Full recipe in account-switcher-procomp-guide.md §4.6.

Features

  • Collapsible (uncontrolled / controlled / headless-via-hook) — v0.5: a controlled toggle requests `!isCollapsed` from the rendered value, and `storageKey` never reads/writes `collapsed` while controlled (server-cookie pattern; no first-paint flip)
  • v0.5 — `labels` covers every rendered string (nav name, toggle, trigger, drawer close, skip link, loading, user menu, empty states) incl. badge-aware accessible names `itemWithBadge(label, value)` / `itemWithIndicator(label)` for collapsed AND expanded rows
  • v0.5 — drawer always renders full labels (nested context: collapsed=false, mode=mobile); `topSlot` may be a function of `{ mode, isCollapsed }`; `useAppSidebarMode()`; `drawerClassName` / `drawerStyle`
  • v0.5 — CSS variables are ancestor-overridable (defaults live at the read site, inline only for passed props) and reach the portalled drawer; `APP_SIDEBAR_CSS_VARS` lists them; row height / gap / padding / indent variables wired
  • v0.5 — RTL: `side` / `mobileDrawerSide` accept `start` / `end` (default `start`), `dir` prop or computed direction, logical classes, mirrored arrow keys / tooltips / icons
  • v0.5 — presence dots and a `brand` badge tone (+ `activeTone`) on semantic tokens shipped via `cssVars.theme`; `formatBadgeCount`; `null` badge = withheld (renders nothing); keyboard handler ignores editable targets
  • Mobile-drawer mode via shadcn Sheet (CSS-gated render path; no SSR flash)
  • <AppSidebarTrigger> companion — inside the subtree it resolves the sidebar from context; outside, pass `controls={ref}` (and its `aria-label`, since it cannot read `labels`)
  • Items discriminated union: NavItem | NavSection | NavSeparator
  • v0.2 — topSlot above brand zone for AccountSwitcher / context widgets
  • v0.2 — {key} href template substitution + resolveHref callback escape hatch
  • v0.2 — ownerOnly + minMembers gates (three-gate intersection: permission ∩ ownerOnly ∩ minMembers)
  • v0.2 — bypassFiltering at BOTH section + item levels for personal-context / debug views
  • v0.2 — exported NavContext discriminated union (type-only)
  • v0.2 — exported useFilteredNavSections hook (works standalone, not coupled to <AppSidebar>)
  • v0.3 — renderItem slot wraps consumer-supplied content in a single <li> (fixes v0.2.x double-nest bug)
  • v0.3 — onMobileOpenChange.reason discriminator correctly fires trigger / item-click / outside-click / escape / imperative
  • v0.3 — openMobile / closeMobile / toggleMobile accept optional reason? param
  • v0.3 — NavUserMenuItem.onClick widened to Event | React.MouseEvent (exported as NavUserMenuItemSelectEvent)
  • v0.3.2 (2026-08-11) — F-cross-13 path-b sweep: zero asChild on shadcn primitives (NavUser trigger IS the DropdownMenuTrigger; href menu rows nest the anchor inside the item; NavPrimaryAction href path uses buttonVariants on the link); collapsed-rail tooltip reimplemented locally — delay honored cross-backend, no Radix-only delayDuration. Zero public-API change.
  • Active-route detection: currentPath + isActive predicate + per-item match
  • linkComponent abstraction (router-agnostic — Next.js, React Router, TanStack)
  • 13 slots (named + render-prop, incl. v0.2 topSlot) + 4 prefab parts (NavBadge, NavBrand, NavPrimaryAction, NavUser)
  • 5 active-state variants (fill / left-bar / right-bar / outline / subtle)
  • CSS-variable theme surface (--ilinxa-sidebar-*) for any-scope theming
  • Section auto-expand when active item inside + auto-scroll into view
  • Permissions membership gating + diff-based onPermissionDenied
  • localStorage opt-in persist for collapse + collapsed-sections
  • Full WAI-ARIA pattern, keyboard nav, skip-link, reduced-motion respect
  • v0.4.1 — `onItemHover` / `onItemFocus` / `onActiveItemChange` / `onMount` / `onUnmount` are wired and emit; they were declared on the props surface but connected to nothing until now. Hover/focus stay silent on disabled rows; `onActiveItemChange` fires from derived state when the host's path commits, never from the click handler
  • F-cross-13 defensive: Sheet + DropdownMenu callbacks pre-emptively widened (Tooltip primitive dropped in v0.3.2 — local implementation)

Tags

sidebarnavigationapp-shellcollapsibledrawermobileheadlesscontrolled-uncontrolledpermissionstheming

Dependencies

shadcn primitives: sheet, avatar, button, dropdown-menu
npm peer deps: lucide-react@^1.11.0