# Workspace sidebar (工作区侧边栏)

Document-first app sidebar for a notes workspace: workspace switcher, search, favorites, a collapsible page tree and a user menu, with an icon-rail mode and a document header.

- Ref: `component/workspace-sidebar` (component · sidebars)
- Page: https://uifino.com/en/components/sidebars/workspace-sidebar
- Markdown: https://uifino.com/md/components/workspace-sidebar.md
- Preview image: https://uifino.com/blocks/covers/workspace-sidebar-dark.webp

## Install

- shadcn: `npx shadcn@latest add "https://uifino.com/r/blocks/workspace-sidebar.json"`
- UIFino CLI: `npx uifino@latest add component/workspace-sidebar`

## Dependencies

`lucide-react`

## shadcn/ui components it builds on

- `avatar`, `breadcrumb`, `checkbox`, `collapsible`, `command`, `dropdown-menu`, `kbd`, `separator`, `sidebar`. The shadcn CLI installs them together with the block.

## Layout borrowed from

- https://www.notion.com: Borrowed the sidebar sections (workspace, search, favorites, page tree, user) and the indentation rhythm of the nested page tree. The document pane, copy and icons are original.

## Theme

The block reads the project's shadcn theme variables, so it follows whatever DESIGN.md the project uses and needs no options of its own.
To give the project the look of a UIFino brand or style, install its theme: `npx shadcn@latest add "https://uifino.com/r/themes/notion.json"`.

## Usage

The files under `examples/` show the block wired with content, including its loading, empty and error states where it has them.

## Files

| Path | Role | Size |
| :--- | :--- | ---: |
| components/blocks/workspace-sidebar/examples/collapsed.tsx | demo | 257 B |
| components/blocks/workspace-sidebar/examples/content.ts | demo | 6.5 KB |
| components/blocks/workspace-sidebar/examples/default.tsx | demo | 237 B |
| components/blocks/workspace-sidebar/examples/mobile-drawer.tsx | demo | 255 B |
| components/blocks/workspace-sidebar/page-tree.tsx | source | 4.4 KB |
| components/blocks/workspace-sidebar/search-dialog.tsx | source | 1.6 KB |
| components/blocks/workspace-sidebar/types.ts | source | 1.1 KB |
| components/blocks/workspace-sidebar/user-menu.tsx | source | 2.6 KB |
| components/blocks/workspace-sidebar/workspace-sidebar.tsx | source | 8.7 KB |
| components/blocks/workspace-sidebar/workspace-switcher.tsx | source | 2.8 KB |

### components/blocks/workspace-sidebar/page-tree.tsx

```tsx
"use client";

import { Briefcase, ChevronRight, FileText, House, Library, NotebookPen, Palette, UsersRound } from "lucide-react";
import type { ComponentType } from "react";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import {
  SidebarMenu,
  SidebarMenuAction,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem
} from "@/components/ui/sidebar";
import { cn } from "@/lib/utils";
import type { PageIcon, PageNode } from "./types";

export const ACTIVE_ROW = "data-[active=true]:bg-sidebar-primary/10 data-[active=true]:text-sidebar-foreground";

const ICONS: Record<PageIcon, ComponentType> = {
  home: House,
  projects: Briefcase,
  brand: Palette,
  notes: NotebookPen,
  hiring: UsersRound,
  handbook: Library,
  page: FileText
};

export function PageGlyph({ icon }: { readonly icon?: PageIcon }) {
  const Icon = ICONS[icon ?? "page"];
  return <Icon />;
}

function containsPage(node: PageNode, pageId: string): boolean {
  return node.id === pageId || (node.children ?? []).some((child) => containsPage(child, pageId));
}

interface PageTreeProps {
  readonly pages: readonly PageNode[];
  readonly activeId: string;
  readonly onSelect: (id: string) => void;
}

export function PageTree({ pages, activeId, onSelect }: PageTreeProps) {
  return (
    <SidebarMenu>
      {pages.map((page) => (
        <TopLevelPage key={page.id} page={page} activeId={activeId} onSelect={onSelect} />
      ))}
    </SidebarMenu>
  );
}

interface NodeProps {
  readonly page: PageNode;
  readonly activeId: string;
  readonly onSelect: (id: string) => void;
}

function TopLevelPage({ page, activeId, onSelect }: NodeProps) {
  const hasChildren = (page.children?.length ?? 0) > 0;

  const button = (
    <SidebarMenuButton
      asChild
      tooltip={page.title}
      isActive={page.id === activeId}
      className={cn(ACTIVE_ROW, hasChildren && "pr-8")}
    >
      <a
        href="#"
        onClick={(event) => {
          event.preventDefault();
          onSelect(page.id);
        }}
      >
        <PageGlyph icon={page.icon} />
        <span title={page.title}>{page.title}</span>
      </a>
    </SidebarMenuButton>
  );

  if (!hasChildren) return <SidebarMenuItem>{button}</SidebarMenuItem>;

  return (
    <Collapsible asChild defaultOpen={containsPage(page, activeId)} className="group/collapsible">
      <SidebarMenuItem>
        {button}
        <CollapsibleTrigger asChild>
          <SidebarMenuAction className="data-[state=open]:rotate-90">
            <ChevronRight />
            <span className="sr-only">{page.title}</span>
          </SidebarMenuAction>
        </CollapsibleTrigger>
        <CollapsibleContent>
          <SubPages pages={page.children ?? []} activeId={activeId} onSelect={onSelect} />
        </CollapsibleContent>
      </SidebarMenuItem>
    </Collapsible>
  );
}

interface SubPagesProps {
  readonly pages: readonly PageNode[];
  readonly activeId: string;
  readonly onSelect: (id: string) => void;
}

function SubPages({ pages, activeId, onSelect }: SubPagesProps) {
  return (
    <SidebarMenuSub>
      {pages.map((page) => (
        <SubPage key={page.id} page={page} activeId={activeId} onSelect={onSelect} />
      ))}
    </SidebarMenuSub>
  );
}

function SubPage({ page, activeId, onSelect }: NodeProps) {
  const hasChildren = (page.children?.length ?? 0) > 0;

  const link = (
    <SidebarMenuSubButton
      asChild
      isActive={page.id === activeId}
      className={cn(ACTIVE_ROW, hasChildren && "pr-8")}
    >
      <a
        href="#"
        onClick={(event) => {
          event.preventDefault();
          onSelect(page.id);
        }}
      >
        <span title={page.title}>{page.title}</span>
      </a>
    </SidebarMenuSubButton>
  );

  if (!hasChildren) return <SidebarMenuSubItem>{link}</SidebarMenuSubItem>;

  return (
    <Collapsible asChild defaultOpen={containsPage(page, activeId)}>
      <SidebarMenuSubItem>
        {link}
        <CollapsibleTrigger asChild>
          <SidebarMenuAction className="top-1 -right-5 data-[state=open]:rotate-90">
            <ChevronRight />
            <span className="sr-only">{page.title}</span>
          </SidebarMenuAction>
        </CollapsibleTrigger>
        <CollapsibleContent>
          <SubPages pages={page.children ?? []} activeId={activeId} onSelect={onSelect} />
        </CollapsibleContent>
      </SidebarMenuSubItem>
    </Collapsible>
  );
}
```

### components/blocks/workspace-sidebar/search-dialog.tsx

```tsx
"use client";

import { useEffect } from "react";
import { CommandDialog, CommandEmpty, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import type { PageNode, WorkspaceSidebarLabels } from "./types";

function flatten(pages: readonly PageNode[]): readonly PageNode[] {
  return pages.flatMap((page) => [page, ...flatten(page.children ?? [])]);
}

interface SearchDialogProps {
  readonly open: boolean;
  readonly onOpenChange: (open: boolean) => void;
  readonly pages: readonly PageNode[];
  readonly labels: WorkspaceSidebarLabels;
  readonly onSelect: (id: string) => void;
}

export function SearchDialog({ open, onOpenChange, pages, labels, onSelect }: SearchDialogProps) {
  useEffect(() => {
    function onKeyDown(event: KeyboardEvent) {
      if (event.key.toLowerCase() === "k" && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();
        onOpenChange(!open);
      }
    }
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [open, onOpenChange]);

  return (
    <CommandDialog open={open} onOpenChange={onOpenChange} title={labels.search} description={labels.search}>
      <CommandInput placeholder={labels.search} />
      <CommandList>
        <CommandEmpty>{labels.noResults}</CommandEmpty>
        {flatten(pages).map((page) => (
          <CommandItem
            key={page.id}
            value={page.title}
            onSelect={() => {
              onSelect(page.id);
              onOpenChange(false);
            }}
          >
            {page.title}
          </CommandItem>
        ))}
      </CommandList>
    </CommandDialog>
  );
}
```

### components/blocks/workspace-sidebar/types.ts

```ts
export type PageIcon = "home" | "projects" | "brand" | "notes" | "hiring" | "handbook" | "page";

export interface PageNode {
  readonly id: string;
  readonly title: string;
  readonly icon?: PageIcon;
  readonly children?: readonly PageNode[];
}

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

export interface WorkspaceUser {
  readonly name: string;
  readonly email: string;
  readonly initials: string;
}

export interface WorkspaceSidebarLabels {
  readonly search: string;
  readonly newPage: string;
  readonly pages: string;
  readonly favorites: string;
  readonly workspaces: string;
  readonly addWorkspace: string;
  readonly profile: string;
  readonly settings: string;
  readonly signOut: string;
  readonly untitled: string;
  readonly noResults: string;
}

export interface DocumentBody {
  readonly edited: string;
  readonly intro: string;
  readonly checklistTitle: string;
  readonly checklist: readonly { readonly id: string; readonly text: string; readonly done: boolean }[];
  readonly closing: string;
}
```

### components/blocks/workspace-sidebar/user-menu.tsx

```tsx
"use client";

import { ChevronsUpDown, LogOut, Settings, UserRound } from "lucide-react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from "@/components/ui/dropdown-menu";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "@/components/ui/sidebar";
import type { WorkspaceSidebarLabels, WorkspaceUser } from "./types";

interface UserMenuProps {
  readonly user: WorkspaceUser;
  readonly labels: WorkspaceSidebarLabels;
}

export function UserMenu({ user, labels }: UserMenuProps) {
  const { isMobile } = useSidebar();

  return (
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <SidebarMenuButton size="lg" tooltip={user.name} className="data-[state=open]:bg-sidebar-accent group-data-[collapsible=icon]:p-0!">
              <Avatar>
                <AvatarFallback className="bg-muted text-xs text-foreground ring-1 ring-sidebar-border ring-inset">{user.initials}</AvatarFallback>
              </Avatar>
              <span className="grid min-w-0 flex-1 leading-tight group-data-[collapsible=icon]:hidden">
                <span className="truncate font-medium">{user.name}</span>
                <span className="truncate text-xs text-sidebar-foreground/70">{user.email}</span>
              </span>
              <ChevronsUpDown className="ml-auto text-sidebar-foreground/60 group-data-[collapsible=icon]:hidden" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="min-w-56" side={isMobile ? "top" : "right"} align="end" sideOffset={8}>
            <DropdownMenuLabel className="font-normal">
              <span className="block truncate text-sm font-medium">{user.name}</span>
              <span className="block truncate text-xs text-muted-foreground">{user.email}</span>
            </DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuItem className="gap-2">
              <UserRound className="size-4" />
              {labels.profile}
            </DropdownMenuItem>
            <DropdownMenuItem className="gap-2">
              <Settings className="size-4" />
              {labels.settings}
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem className="gap-2">
              <LogOut className="size-4" />
              {labels.signOut}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  );
}
```

### components/blocks/workspace-sidebar/workspace-sidebar.tsx

```tsx
"use client";

import { Fragment, useEffect, useState, type CSSProperties } from "react";
import { Plus, Search, Star } from "lucide-react";
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb";
import { Checkbox } from "@/components/ui/checkbox";
import { Kbd } from "@/components/ui/kbd";
import { Separator } from "@/components/ui/separator";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupAction,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarInset,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarProvider,
  SidebarRail,
  SidebarTrigger,
  useSidebar
} from "@/components/ui/sidebar";
import { ACTIVE_ROW, PageGlyph, PageTree } from "./page-tree";
import { SearchDialog } from "./search-dialog";
import type { DocumentBody, PageNode, Workspace, WorkspaceSidebarLabels, WorkspaceUser } from "./types";
import { UserMenu } from "./user-menu";
import { WorkspaceSwitcher } from "./workspace-switcher";

const SIDEBAR_STYLE = { "--sidebar-width": "calc(var(--spacing) * 68)" } as CSSProperties;

export type { DocumentBody, PageIcon, PageNode, Workspace, WorkspaceSidebarLabels, WorkspaceUser } from "./types";

export interface WorkspaceSidebarProps {
  readonly workspaces: readonly Workspace[];
  readonly pages: readonly PageNode[];
  readonly favoriteIds: readonly string[];
  readonly user: WorkspaceUser;
  readonly document: DocumentBody;
  readonly labels: WorkspaceSidebarLabels;
  readonly activeId: string;
  readonly defaultOpen?: boolean;
  readonly defaultOpenMobile?: boolean;
  readonly onCreatePage?: (page: PageNode) => void;
}

function OpenMobileOnMount({ enabled }: { readonly enabled: boolean }) {
  const { setOpenMobile } = useSidebar();
  useEffect(() => {
    if (enabled) setOpenMobile(true);
  }, [enabled, setOpenMobile]);
  return null;
}

function findTrail(pages: readonly PageNode[], id: string): readonly PageNode[] {
  for (const page of pages) {
    if (page.id === id) return [page];
    const inner = findTrail(page.children ?? [], id);
    if (inner.length > 0) return [page, ...inner];
  }
  return [];
}

function findPage(pages: readonly PageNode[], id: string): PageNode | undefined {
  return findTrail(pages, id).at(-1);
}

export function WorkspaceSidebar({
  workspaces,
  pages: initialPages,
  favoriteIds,
  user,
  document,
  labels,
  activeId: initialActiveId,
  defaultOpen = true,
  defaultOpenMobile = false,
  onCreatePage
}: WorkspaceSidebarProps) {
  const [pages, setPages] = useState(initialPages);
  const [searchOpen, setSearchOpen] = useState(false);
  const [activeId, setActiveId] = useState(initialActiveId);

  function createPage() {
    const page: PageNode = { id: `untitled-${pages.length}`, title: labels.untitled };
    setPages((prev) => [...prev, page]);
    setActiveId(page.id);
    onCreatePage?.(page);
  }

  const trail = findTrail(pages, activeId);
  const current = trail.at(-1);
  const favorites = favoriteIds.flatMap((id) => {
    const page = findPage(pages, id);
    return page ? [page] : [];
  });
  const [checked, setChecked] = useState<Record<string, boolean>>(() =>
    Object.fromEntries(document.checklist.map((item) => [item.id, item.done]))
  );

  return (
    <SidebarProvider defaultOpen={defaultOpen} className="@container" style={SIDEBAR_STYLE}>
      <OpenMobileOnMount enabled={defaultOpenMobile} />
      <SearchDialog open={searchOpen} onOpenChange={setSearchOpen} pages={pages} labels={labels} onSelect={setActiveId} />
      <Sidebar collapsible="icon">
        <SidebarHeader>
          <WorkspaceSwitcher workspaces={workspaces} labels={labels} />
          <SidebarMenu>
            <SidebarMenuItem>
              <SidebarMenuButton tooltip={labels.search} className="text-sidebar-foreground/70" onClick={() => setSearchOpen(true)}>
                <Search />
                <span className="flex-1">{labels.search}</span>
                <Kbd className="bg-background text-foreground">⌘K</Kbd>
              </SidebarMenuButton>
            </SidebarMenuItem>
          </SidebarMenu>
        </SidebarHeader>
        <SidebarContent>
          <SidebarGroup className="group-data-[collapsible=icon]:hidden">
            <SidebarGroupLabel className="gap-1.5">
              <Star className="size-3" />
              {labels.favorites}
            </SidebarGroupLabel>
            <SidebarGroupContent>
              <SidebarMenu>
                {favorites.map((page) => (
                  <SidebarMenuItem key={page.id}>
                    <SidebarMenuButton
                      asChild
                      tooltip={page.title}
                      isActive={page.id === activeId}
                      className={ACTIVE_ROW}
                    >
                      <a
                        href="#"
                        onClick={(event) => {
                          event.preventDefault();
                          setActiveId(page.id);
                        }}
                      >
                        <PageGlyph icon={page.icon} />
                        <span title={page.title}>{page.title}</span>
                      </a>
                    </SidebarMenuButton>
                  </SidebarMenuItem>
                ))}
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
          <SidebarGroup>
            <SidebarGroupLabel>{labels.pages}</SidebarGroupLabel>
            <SidebarGroupAction title={labels.newPage} onClick={createPage}>
              <Plus />
              <span className="sr-only">{labels.newPage}</span>
            </SidebarGroupAction>
            <SidebarGroupContent>
              <PageTree pages={pages} activeId={activeId} onSelect={setActiveId} />
            </SidebarGroupContent>
          </SidebarGroup>
        </SidebarContent>
        <SidebarFooter>
          <UserMenu user={user} labels={labels} />
        </SidebarFooter>
        <SidebarRail />
      </Sidebar>
      <SidebarInset className="min-w-0">
        <header className="flex h-12 shrink-0 items-center gap-2 border-b px-4">
          <SidebarTrigger className="-ml-1" />
          <Separator orientation="vertical" className="mr-1 h-4" />
          <Breadcrumb className="min-w-0">
            <BreadcrumbList className="flex-nowrap">
              {trail.map((page, index) => {
                const last = index === trail.length - 1;
                if (last) {
                  return (
                    <BreadcrumbItem key={page.id} className="min-w-0">
                      <BreadcrumbPage className="truncate">{page.title}</BreadcrumbPage>
                    </BreadcrumbItem>
                  );
                }
                return (
                  <Fragment key={page.id}>
                    <BreadcrumbItem className="hidden @2xl:inline-flex">
                      <BreadcrumbLink
                        href="#"
                        className="truncate"
                        onClick={(event) => {
                          event.preventDefault();
                          setActiveId(page.id);
                        }}
                      >
                        {page.title}
                      </BreadcrumbLink>
                    </BreadcrumbItem>
                    <BreadcrumbSeparator className="hidden @2xl:block" />
                  </Fragment>
                );
              })}
            </BreadcrumbList>
          </Breadcrumb>
        </header>
        <article className="mx-auto w-full max-w-2xl px-6 py-10 @3xl:py-16">
          <h1 className="font-heading text-3xl font-semibold tracking-tight text-balance @3xl:text-4xl">{current?.title}</h1>
          <p className="mt-2 text-sm text-muted-foreground">{document.edited}</p>
          <p className="mt-8 leading-7 text-pretty">{document.intro}</p>
          <h2 className="mt-8 font-heading text-xl font-semibold">{document.checklistTitle}</h2>
          <ul className="mt-3 flex flex-col gap-2">
            {document.checklist.map((item) => (
              <li key={item.id} className="flex items-start gap-3 text-sm leading-6">
                <Checkbox
                  id={item.id}
                  className="mt-1"
                  checked={checked[item.id] ?? false}
                  onCheckedChange={(value) => setChecked((prev) => ({ ...prev, [item.id]: value === true }))}
                />
                <label htmlFor={item.id} className={checked[item.id] ? "text-muted-foreground line-through" : undefined}>
                  {item.text}
                </label>
              </li>
            ))}
          </ul>
          <p className="mt-8 leading-7 text-pretty text-muted-foreground">{document.closing}</p>
        </article>
      </SidebarInset>
    </SidebarProvider>
  );
}
```

### components/blocks/workspace-sidebar/workspace-switcher.tsx

```tsx
"use client";

import { useState } from "react";
import { Check, ChevronsUpDown, Plus } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from "@/components/ui/dropdown-menu";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "@/components/ui/sidebar";
import type { Workspace, WorkspaceSidebarLabels } from "./types";

interface WorkspaceSwitcherProps {
  readonly workspaces: readonly Workspace[];
  readonly labels: WorkspaceSidebarLabels;
}

export function WorkspaceSwitcher({ workspaces, labels }: WorkspaceSwitcherProps) {
  const { isMobile } = useSidebar();
  const [activeId, setActiveId] = useState(workspaces[0]?.id);
  const active = workspaces.find((workspace) => workspace.id === activeId) ?? workspaces[0];
  if (!active) return null;

  return (
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <SidebarMenuButton size="lg" tooltip={active.name} className="data-[state=open]:bg-sidebar-accent group-data-[collapsible=icon]:p-0!">
              <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-primary font-heading text-base text-primary-foreground">
                {active.name.charAt(0)}
              </span>
              <span className="grid min-w-0 flex-1 leading-tight">
                <span className="truncate font-medium">{active.name}</span>
                <span className="truncate text-xs text-sidebar-foreground/70">{active.plan}</span>
              </span>
              <ChevronsUpDown className="ml-auto text-sidebar-foreground/60" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="min-w-60" side={isMobile ? "bottom" : "right"} align="start" sideOffset={8}>
            <DropdownMenuLabel className="text-xs text-muted-foreground">{labels.workspaces}</DropdownMenuLabel>
            {workspaces.map((workspace) => (
              <DropdownMenuItem key={workspace.id} onSelect={() => setActiveId(workspace.id)} className="gap-2">
                <span className="flex size-6 shrink-0 items-center justify-center rounded-md border font-heading text-xs">
                  {workspace.name.charAt(0)}
                </span>
                <span className="min-w-0 flex-1 truncate">{workspace.name}</span>
                {workspace.id === active.id ? <Check className="size-4" /> : null}
              </DropdownMenuItem>
            ))}
            <DropdownMenuSeparator />
            <DropdownMenuItem className="gap-2">
              <Plus className="size-4" />
              {labels.addWorkspace}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  );
}
```

Not inlined (4 files, 7.3 KB). Full sources: https://uifino.com/r/blocks/workspace-sidebar.json
