Skip to content
Esc
↑↓navigate↵open⌘Jpreview

Sidebar for Astro

Astro sidebar parts for navigation, grouped links, and layout controls.

Installation

bunx --bun shadcn@latest add @gnostic/sidebar
npx shadcn@latest add @gnostic/sidebar
pnpm dlx shadcn@latest add @gnostic/sidebar

Component classes: Default Gnostic.

Complete the Installation guide first. Then copy the component files below.

Install component packages

bun add @data-slot/tooltip

Copy the files

src/components/ui/sidebar/index.ts
export { default as SidebarProvider } from "./sidebar-provider.astro"
export { default as Sidebar } from "./sidebar.astro"
export { default as SidebarTrigger } from "./sidebar-trigger.astro"
export { default as SidebarRail } from "./sidebar-rail.astro"
export { default as SidebarInset } from "./sidebar-inset.astro"
export { default as SidebarInput } from "./sidebar-input.astro"
export { default as SidebarHeader } from "./sidebar-header.astro"
export { default as SidebarFooter } from "./sidebar-footer.astro"
export { default as SidebarSeparator } from "./sidebar-separator.astro"
export { default as SidebarContent } from "./sidebar-content.astro"
export { default as SidebarGroup } from "./sidebar-group.astro"
export { default as SidebarGroupLabel } from "./sidebar-group-label.astro"
export { default as SidebarGroupAction } from "./sidebar-group-action.astro"
export { default as SidebarGroupContent } from "./sidebar-group-content.astro"
export { default as SidebarMenu } from "./sidebar-menu.astro"
export { default as SidebarMenuItem } from "./sidebar-menu-item.astro"
export { default as SidebarMenuButton } from "./sidebar-menu-button.astro"
export { default as SidebarMenuAction } from "./sidebar-menu-action.astro"
export { default as SidebarMenuBadge } from "./sidebar-menu-badge.astro"
export { default as SidebarMenuSkeleton } from "./sidebar-menu-skeleton.astro"
export { default as SidebarMenuSub } from "./sidebar-menu-sub.astro"
export { default as SidebarMenuSubButton } from "./sidebar-menu-sub-button.astro"
export { default as SidebarMenuSubItem } from "./sidebar-menu-sub-item.astro"
src/components/ui/sidebar/sidebar-content.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"div">

const { class: className, ...props } = Astro.props
---

<div
  data-slot="sidebar-content"
  data-sidebar="content"
  class={cn("no-scrollbar flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden", className)}
  {...props}
>
  <slot />
</div>
src/components/ui/sidebar/sidebar-footer.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"div">

const { class: className, ...props } = Astro.props
---

<div
  data-slot="sidebar-footer"
  data-sidebar="footer"
  class={cn("flex flex-col gap-2 p-2", className)}
  {...props}
>
  <slot />
</div>
src/components/ui/sidebar/sidebar-group-action.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"button"> &
  HTMLAttributes<"a"> &
  HTMLAttributes<"div"> &
  HTMLAttributes<"span"> & {
    as?: "button" | "a" | "div" | "span"
    href?: string
  }

const { as: explicitTag, class: className, type, ...props } = Astro.props

const Tag = explicitTag || ("href" in Astro.props ? "a" : "button")
const resolvedType = Tag === "button" ? type || "button" : undefined
---

<Tag
  data-slot="sidebar-group-action"
  data-sidebar="group-action"
  type={resolvedType}
  class={cn("text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0", className)}
  {...props}
>
  <slot />
</Tag>
src/components/ui/sidebar/sidebar-group-content.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"div">

const { class: className, ...props } = Astro.props
---

<div
  data-slot="sidebar-group-content"
  data-sidebar="group-content"
  class={cn("w-full text-sm", className)}
  {...props}
>
  <slot />
</div>
src/components/ui/sidebar/sidebar-group-label.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"div"> &
  HTMLAttributes<"button"> &
  HTMLAttributes<"span"> & {
    as?: "div" | "button" | "span"
  }

const { as: Tag = "div", class: className, type, ...props } = Astro.props
---

<Tag
  data-slot="sidebar-group-label"
  data-sidebar="group-label"
  type={Tag === "button" ? type || "button" : undefined}
  class={cn("text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0", className)}
  {...props}
>
  <slot />
</Tag>
src/components/ui/sidebar/sidebar-group.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"div">

const { class: className, ...props } = Astro.props
---

<div
  data-slot="sidebar-group"
  data-sidebar="group"
  class={cn("relative flex w-full min-w-0 flex-col p-2", className)}
  {...props}
>
  <slot />
</div>
src/components/ui/sidebar/sidebar-header.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"div">

const { class: className, ...props } = Astro.props
---

<div
  data-slot="sidebar-header"
  data-sidebar="header"
  class={cn("flex flex-col gap-2 p-2", className)}
  {...props}
>
  <slot />
</div>
src/components/ui/sidebar/sidebar-input.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"input">

const { class: className, ...props } = Astro.props
---

<input
  data-slot="sidebar-input"
  data-sidebar="input"
  class={cn("dark:bg-input/30 border-input focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 file:text-foreground placeholder:text-muted-foreground bg-background h-8 w-full min-w-0 rounded-md border px-2.5 py-1 text-base shadow-none transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:ring-3 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-3 md:text-sm", className)}
  {...props}
/>
src/components/ui/sidebar/sidebar-inset.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"main">

const { class: className, ...props } = Astro.props
---

<main
  data-slot="sidebar-inset"
  class={cn("bg-background relative flex w-full flex-1 flex-col md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2", className)}
  {...props}
>
  <slot />
</main>
src/components/ui/sidebar/sidebar-menu-action.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"button"> &
  HTMLAttributes<"a"> &
  HTMLAttributes<"div"> &
  HTMLAttributes<"span"> & {
    as?: "button" | "a" | "div" | "span"
    href?: string
    showOnHover?: boolean
  }

const {
  as: explicitTag,
  class: className,
  showOnHover = false,
  type,
  ...props
} = Astro.props

const Tag = explicitTag || ("href" in Astro.props ? "a" : "button")
const resolvedType = Tag === "button" ? type || "button" : undefined
---

<Tag
  data-slot="sidebar-menu-action"
  data-sidebar="menu-action"
  type={resolvedType}
  class={cn(
    "text-sidebar-foreground ring-sidebar-ring peer-hover/menu-button:text-sidebar-accent-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform group-data-[collapsible=icon]:hidden peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 after:absolute after:-inset-2 focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",
    showOnHover &&
      "peer-data-active/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 aria-expanded:opacity-100 md:opacity-0",
    className,
  )}
  {...props}
>
  <slot />
</Tag>
src/components/ui/sidebar/sidebar-menu-badge.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"div">

const { class: className, ...props } = Astro.props
---

<div
  data-slot="sidebar-menu-badge"
  data-sidebar="menu-badge"
  class={cn("text-sidebar-foreground peer-hover/menu-button:text-sidebar-accent-foreground peer-data-active/menu-button:text-sidebar-accent-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none group-data-[collapsible=icon]:hidden peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1", className)}
  {...props}
>
  <slot />
</div>
src/components/ui/sidebar/sidebar-menu-button.astro
---
import type { HTMLAttributes } from "astro/types"
import type { TooltipAlign, TooltipSide } from "@data-slot/tooltip"
import { cva, type VariantProps } from "class-variance-authority"

import { cn } from "cn"
import { Tooltip, TooltipContent, TooltipTrigger } from "../tooltip/index.ts"

const variants = cva(
  "peer/menu-button group/menu-button ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-active:font-medium [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate",
  {
    variants: {
      variant: {
        default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
        outline:
          "bg-background hover:bg-sidebar-accent hover:text-sidebar-accent-foreground shadow-[0_0_0_1px_var(--sidebar-border)] hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",
      },
      size: {
        default: "h-8 text-sm",
        sm: "h-7 text-xs",
        lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  },
)

type TooltipValue =
  | string
  | (HTMLAttributes<"div"> & {
      content?: string
      children?: string
      side?: TooltipSide
      align?: TooltipAlign
      sideOffset?: number
      alignOffset?: number
      avoidCollisions?: boolean
      collisionPadding?: number
    })

type Props = VariantProps<typeof variants> &
  HTMLAttributes<"button"> &
  HTMLAttributes<"a"> &
  HTMLAttributes<"div"> &
  HTMLAttributes<"span"> & {
    as?: "a" | "button" | "div" | "span"
    href?: string
    isActive?: boolean
    active?: boolean
    tooltip?: TooltipValue
  }

const {
  as: explicitTag,
  class: className,
  variant = "default",
  size = "default",
  isActive,
  active = false,
  tooltip,
  type,
  ...props
} = Astro.props

const Tag = explicitTag || ("href" in Astro.props ? "a" : "button")
const resolvedActive = isActive ?? active
const baseClassName = cn(variants({ variant, size }), className)
const resolvedTooltip =
  typeof tooltip === "string" ? { children: tooltip } : tooltip
const tooltipText =
  resolvedTooltip?.content ??
  (typeof resolvedTooltip?.children === "string"
    ? resolvedTooltip.children
    : undefined)
const {
  content: _tooltipContent,
  children: _tooltipChildren,
  ...tooltipProps
} = resolvedTooltip ?? {}
---

{tooltipText ? (
  <Tooltip>
    <TooltipTrigger
      as={Tag}
      data-sidebar="menu-button"
      data-size={size}
      data-active={resolvedActive ? "true" : undefined}
      aria-current={resolvedActive ? "page" : undefined}
      {...(Tag === "button" ? { type: type || "button" } : {})}
      class={baseClassName}
      {...props}
    >
      <slot />
    </TooltipTrigger>
    <TooltipContent
      data-sidebar="menu-tooltip"
      side="right"
      align="center"
      hidden
      {...tooltipProps}
    >
      {tooltipText}
    </TooltipContent>
  </Tooltip>
) : (
  <Tag
    data-slot="sidebar-menu-button"
    data-sidebar="menu-button"
    data-size={size}
    data-active={resolvedActive ? "true" : undefined}
    aria-current={resolvedActive ? "page" : undefined}
    type={Tag === "button" ? type || "button" : undefined}
    class={baseClassName}
    {...props}
  >
    <slot />
  </Tag>
)}
src/components/ui/sidebar/sidebar-menu-item.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"li">

const { class: className, ...props } = Astro.props
---

<li
  data-slot="sidebar-menu-item"
  data-sidebar="menu-item"
  class={cn("group/menu-item relative", className)}
  {...props}
>
  <slot />
</li>
src/components/ui/sidebar/sidebar-menu-skeleton.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"
import { Skeleton } from "../skeleton/index.ts"

type Props = HTMLAttributes<"div"> & {
  showIcon?: boolean
}

const { class: className, showIcon = false, ...props } = Astro.props
const width = `${Math.floor(Math.random() * 40) + 50}%`
---

<div
  data-slot="sidebar-menu-skeleton"
  data-sidebar="menu-skeleton"
  class={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
  {...props}
>
  {showIcon && (
    <Skeleton
      data-slot="sidebar-menu-skeleton-icon"
      class="size-4 rounded-md"
      data-sidebar="menu-skeleton-icon"
    />
  )}
  <Skeleton
    data-slot="sidebar-menu-skeleton-text"
    class="h-4 max-w-(--skeleton-width) flex-1"
    data-sidebar="menu-skeleton-text"
    style={`--skeleton-width: ${width};`}
  />
</div>
src/components/ui/sidebar/sidebar-menu-sub-button.astro
---
import type { HTMLAttributes } from "astro/types"
import { cva, type VariantProps } from "class-variance-authority"

import { cn } from "cn"

const variants = cva(
  "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden group-data-[collapsible=icon]:hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[size=md]:text-sm data-[size=sm]:text-xs [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
  {
    variants: {
      size: {
        sm: "text-xs",
        md: "text-sm",
      },
    },
    defaultVariants: {
      size: "md",
    },
  },
)

type Props = VariantProps<typeof variants> &
  HTMLAttributes<"button"> &
  HTMLAttributes<"a"> &
  HTMLAttributes<"span"> & {
    as?: "a" | "button" | "span"
    href?: string
    isActive?: boolean
    active?: boolean
  }

const {
  as: explicitTag,
  class: className,
  size = "md",
  isActive,
  active = false,
  type,
  ...props
} = Astro.props

const Tag = explicitTag || "a"
const resolvedActive = isActive ?? active
---

<Tag
  data-slot="sidebar-menu-sub-button"
  data-sidebar="menu-sub-button"
  data-size={size}
  data-active={resolvedActive ? "true" : undefined}
  aria-current={resolvedActive ? "page" : undefined}
  type={Tag === "button" ? type || "button" : undefined}
  class={cn(variants({ size }), className)}
  {...props}
>
  <slot />
</Tag>
src/components/ui/sidebar/sidebar-menu-sub-item.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"li">

const { class: className, ...props } = Astro.props
---

<li
  data-slot="sidebar-menu-sub-item"
  data-sidebar="menu-sub-item"
  class={cn("group/menu-sub-item relative", className)}
  {...props}
>
  <slot />
</li>
src/components/ui/sidebar/sidebar-menu-sub.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"ul">

const { class: className, ...props } = Astro.props
---

<ul
  data-slot="sidebar-menu-sub"
  data-sidebar="menu-sub"
  class={cn("border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5 group-data-[collapsible=icon]:hidden", className)}
  {...props}
>
  <slot />
</ul>
src/components/ui/sidebar/sidebar-menu.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"ul">

const { class: className, ...props } = Astro.props
---

<ul
  data-slot="sidebar-menu"
  data-sidebar="menu"
  class={cn("flex w-full min-w-0 flex-col gap-1", className)}
  {...props}
>
  <slot />
</ul>
src/components/ui/sidebar/sidebar-provider.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"

type Props = HTMLAttributes<"div"> & {
  defaultOpen?: boolean
  open?: boolean
}

const {
  class: className,
  style,
  defaultOpen = true,
  open,
  ...props
} = Astro.props

const resolvedStyle = [
  `--sidebar-width: ${SIDEBAR_WIDTH}`,
  `--sidebar-width-mobile: ${SIDEBAR_WIDTH_MOBILE}`,
  `--sidebar-width-icon: ${SIDEBAR_WIDTH_ICON}`,
  typeof style === "string" ? style : undefined,
]
  .filter(Boolean)
  .join("; ")
---

<div
  data-slot="sidebar-wrapper"
  data-default-open={defaultOpen ? "true" : "false"}
  data-open={open === undefined ? undefined : open ? "true" : "false"}
  style={resolvedStyle}
  class={cn(
    "group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
    className,
  )}
  {...props}
>
  <slot />
  <script is:inline>
    ;(() => {
      window.__gnosticSyncSidebarProvider ??= (provider, open) => {
        const state = open ? "expanded" : "collapsed"
        const sidebar = provider.querySelector(
          "[data-slot='sidebar']:not([data-mobile='true'])",
        )
        const collapsible = sidebar?.dataset.sidebarCollapsible ?? "offcanvas"

        provider.dataset.open = open ? "true" : "false"
        provider.dataset.state = state

        if (sidebar) {
          sidebar.dataset.state = collapsible === "none" ? "expanded" : state
          sidebar.dataset.collapsible =
            collapsible === "none" ? "none" : open ? "" : collapsible
        }

        provider
          .querySelectorAll("[data-sidebar='trigger'], [data-sidebar='rail']")
          .forEach((control) => {
            control.setAttribute("aria-expanded", String(open))
          })

        provider
          .querySelectorAll("[data-slot='tooltip']")
          .forEach((tooltip) => {
            if (
              state !== "collapsed" &&
              tooltip.querySelector("[data-sidebar='menu-button']")
            ) {
              tooltip.dispatchEvent(
                new CustomEvent("tooltip:set", { detail: { open: false } }),
              )
            }
          })
      }

      const provider = document.currentScript?.closest(
        "[data-slot='sidebar-wrapper']",
      )
      if (!(provider instanceof HTMLElement)) return

      const controlledOpen = provider.dataset.open
      const cookieValue = document.cookie
        .split("; ")
        .find((entry) => entry.startsWith("sidebar_state="))
        ?.slice("sidebar_state=".length)

      const isOpen =
        controlledOpen === "true" || controlledOpen === "false"
          ? controlledOpen === "true"
          : cookieValue === "true" || cookieValue === "false"
            ? cookieValue === "true"
            : provider.dataset.defaultOpen !== "false"

      provider.dataset.openMobile = "false"
      window.__gnosticSyncSidebarProvider(provider, isOpen)
    })()
  </script>
</div>

<script is:inline>
  ;(() => {
    const scrollTop = Number(sessionStorage.getItem("sidebar_scroll") || 0)

    document.querySelectorAll("[data-sidebar='content']").forEach((content) => {
      content.scrollTop = scrollTop
    })
  })()
</script>

<script is:inline>
  ;(() => {
    if (window.__gnosticSidebarInitialized) return
    window.__gnosticSidebarInitialized = true

    const SIDEBAR_COOKIE_NAME = "sidebar_state"
    const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7

    const toggleSidebar = (provider) => {
      if (!window.matchMedia("(min-width: 768px)").matches) {
        const openMobile = provider.dataset.openMobile !== "true"
        provider.dataset.openMobile = openMobile ? "true" : "false"
        provider
          .querySelector("[data-sidebar='sheet']")
          ?.dispatchEvent(
            new CustomEvent("dialog:set", { detail: { open: openMobile } }),
          )
        return
      }

      const open = provider.dataset.open === "false"
      document.cookie = `${SIDEBAR_COOKIE_NAME}=${open}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
      window.__gnosticSyncSidebarProvider?.(provider, open)
    }

    document.addEventListener("dialog:change", (event) => {
      const root = event.target
      if (!(root instanceof HTMLElement) || root.dataset.sidebar !== "sheet")
        return
      const provider = root.closest("[data-slot='sidebar-wrapper']")
      if (provider)
        provider.dataset.openMobile = String(Boolean(event.detail?.open))
    })

    document.addEventListener("tooltip:change", (event) => {
      if (!event.detail?.open) return
      const root = event.target
      if (!(root instanceof HTMLElement)) return
      if (!root.querySelector("[data-sidebar='menu-button']")) return
      const provider = root.closest("[data-slot='sidebar-wrapper']")
      const sidebar = root.closest("[data-slot='sidebar']")
      if (
        provider?.dataset.state !== "collapsed" ||
        sidebar?.dataset.collapsible !== "icon" ||
        !window.matchMedia("(min-width: 768px)").matches
      ) {
        root.dispatchEvent(
          new CustomEvent("tooltip:set", { detail: { open: false } }),
        )
      }
    })

    document.addEventListener("click", (event) => {
      const control = event.target?.closest?.(
        "[data-sidebar='trigger'], [data-sidebar='rail']",
      )
      if (!control || control.matches(":disabled, [aria-disabled='true']")) {
        return
      }

      const provider = control.closest("[data-slot='sidebar-wrapper']")
      if (!provider) return

      toggleSidebar(provider)
    })

    document.addEventListener("keydown", (event) => {
      if (event.key.toLowerCase() !== "b") return
      if (!(event.metaKey || event.ctrlKey) || event.shiftKey || event.altKey) {
        return
      }
      if (event.defaultPrevented) return

      const target = event.target
      const isTyping =
        target instanceof HTMLElement &&
        (target.isContentEditable ||
          target.matches("input, textarea, select, [role='textbox']"))
      if (isTyping) return

      const provider = document.querySelector("[data-slot='sidebar-wrapper']")
      if (!(provider instanceof HTMLElement)) return

      event.preventDefault()
      toggleSidebar(provider)
    })

    document.addEventListener(
      "scroll",
      (event) => {
        if (event.target?.dataset?.sidebar === "content") {
          sessionStorage.setItem("sidebar_scroll", event.target.scrollTop)
        }
      },
      true,
    )
  })()
</script>
src/components/ui/sidebar/sidebar-rail.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"

type Props = HTMLAttributes<"button">

const { class: className, type = "button", ...props } = Astro.props
---

<button
  data-sidebar="rail"
  data-slot="sidebar-rail"
  aria-label="Toggle Sidebar"
  tabindex={-1}
  title="Toggle Sidebar"
  type={type}
  class={cn(
    "hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2",
    "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
    "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
    "hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
    "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
    "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
    className,
  )}
  {...props}
></button>
src/components/ui/sidebar/sidebar-separator.astro
---
import type { ComponentProps } from "astro/types"

import { cn } from "cn"
import { Separator } from "../separator/index.ts"

type Props = ComponentProps<typeof Separator>

const { class: className, ...props } = Astro.props
---

<Separator
  data-slot="sidebar-separator"
  data-sidebar="separator"
  class={cn("bg-sidebar-border mx-2 w-auto", className)}
  {...props}
/>
src/components/ui/sidebar/sidebar-trigger.astro
---
import type { HTMLAttributes } from "astro/types"
import PanelLeftIcon from "@lucide/astro/icons/panel-left"

import { Button } from "../button/index.ts"

type Props = HTMLAttributes<"button"> & {
  variant?: "ghost" | "secondary"
}

const { class: className, ...props } = Astro.props
---

<Button
  data-sidebar="trigger"
  data-slot="sidebar-trigger"
  variant="ghost"
  size="icon-sm"
  class={className}
  aria-keyshortcuts="Control+B Meta+B"
  {...props}
>
  <PanelLeftIcon />
  <span class="sr-only">Toggle Sidebar</span>
  <slot />
</Button>
src/components/ui/sidebar/sidebar.astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "../sheet/index.ts"
import type { SidebarProps } from "./types.ts"

type Props = Omit<HTMLAttributes<"div">, "dir"> & SidebarProps

const {
  class: className,
  side = "left",
  variant = "sidebar",
  collapsible = "offcanvas",
  state = "expanded",
  ...props
} = Astro.props

const desktopState = collapsible === "none" ? "expanded" : state
const desktopCollapsible = desktopState === "collapsed" ? collapsible : ""
---

{collapsible === "none" ? (
  <div
    data-slot="sidebar"
    data-state="expanded"
    data-collapsible="none"
    data-variant={variant}
    data-side={side}
    data-sidebar-collapsible="none"
    class={cn(
      "bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
      className,
    )}
    {...props}
  >
    <slot />
  </div>
) : (
  <>
    <Sheet data-sidebar="sheet" defaultOpen={false}>
      <SheetContent
        side={side}
        showCloseButton={false}
        data-sidebar="sidebar"
        data-mobile="true"
        style="--sidebar-width: var(--sidebar-width-mobile);"
        class={cn(
          "bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 md:hidden",
          className,
        )}
      >
        <SheetHeader class="sr-only">
          <SheetTitle>Sidebar</SheetTitle>
          <SheetDescription>Displays the mobile sidebar.</SheetDescription>
        </SheetHeader>
        <div class="flex h-full w-full flex-col">
          <slot />
        </div>
      </SheetContent>
    </Sheet>

    <div
      data-slot="sidebar"
      data-state={desktopState}
      data-collapsible={desktopCollapsible}
      data-variant={variant}
      data-side={side}
      data-sidebar-collapsible={collapsible}
      class="group peer text-sidebar-foreground hidden md:block"
    >
      <div
        data-slot="sidebar-gap"
        class={cn(
          "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
          "group-data-[collapsible=offcanvas]:w-0",
          "group-data-[side=right]:rotate-180",
          variant === "floating" || variant === "inset"
            ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
            : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
        )}
      />
      <div
        data-slot="sidebar-container"
        data-variant={variant}
        data-side={side}
        class={cn(
          "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:-left-(--sidebar-width) data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:-right-(--sidebar-width) md:flex",
          variant === "floating" || variant === "inset"
            ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
            : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
          className,
        )}
        {...props}
      >
        <div
          data-sidebar="sidebar"
          data-slot="sidebar-inner"
          class="bg-sidebar group-data-[variant=floating]:ring-sidebar-border flex size-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:shadow-sm group-data-[variant=floating]:ring-1"
        >
          <slot />
        </div>
      </div>
    </div>
  </>
)}
src/components/ui/sidebar/types.ts
export type SidebarProps = {
    /**
     * Which side the sidebar should appear on.
     */
    side?: 'left' | 'right'
    /**
     * Visual variant for the desktop shell.
     */
    variant?: 'sidebar' | 'floating' | 'inset'
    /**
     * Collapse behavior.
     */
    collapsible?: 'offcanvas' | 'icon' | 'none'
    /**
     * Sets the initial desktop state.
     */
    state?: 'expanded' | 'collapsed'
}

Usage

---
import Home from "@lucide/astro/icons/house"

import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarInset,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarProvider,
  SidebarRail,
  SidebarTrigger,
} from "@/components/ui/sidebar"
---

<SidebarProvider>
  <Sidebar>
    <SidebarHeader />
    <SidebarContent>
      <SidebarGroup>
        <SidebarGroupLabel>Application</SidebarGroupLabel>
        <SidebarGroupContent>
          <SidebarMenu>
            <SidebarMenuItem>
              <SidebarMenuButton href="/">
                <Home />
                <span>Home</span>
              </SidebarMenuButton>
            </SidebarMenuItem>
          </SidebarMenu>
        </SidebarGroupContent>
      </SidebarGroup>
    </SidebarContent>
    <SidebarRail />
  </Sidebar>
  <SidebarInset>
    <header class="flex h-14 items-center border-b px-6">
      <SidebarTrigger />
    </header>
    <main class="flex-1 p-4">Your content</main>
  </SidebarInset>
</SidebarProvider>

Composition

Arrange the parts as shown for a sidebar layout:

SidebarProvider
├── Sidebar
│   ├── SidebarHeader
│   ├── SidebarContent
│   │   ├── SidebarGroup
│   │   │   ├── SidebarGroupLabel
│   │   │   ├── SidebarGroupAction
│   │   │   ├── SidebarGroupContent
│   │   │   └── SidebarMenu
│   │   │       ├── SidebarMenuItem
│   │   │       │   ├── SidebarMenuButton
│   │   │       │   ├── SidebarMenuAction
│   │   │       │   └── SidebarMenuBadge
│   │   │       └── SidebarMenuItem
│   │   │           ├── SidebarMenuButton
│   │   │           └── SidebarMenuSub
│   │   │               ├── SidebarMenuSubItem
│   │   │               └── SidebarMenuSubItem
│   │   └── SidebarGroup
│   │       └── SidebarMenu
│   │           ├── SidebarMenuItem
│   │           └── SidebarMenuItem
│   ├── SidebarFooter
│   └── SidebarRail
└── SidebarInset
    └── SidebarTrigger

Components

  • SidebarProvider wraps the layout, owns the collapse state, and persists desktop state in the sidebar_state cookie.
  • Sidebar renders the desktop shell and uses the shared Sheet primitive for the mobile drawer. It supports side, variant, collapsible, and dir.
  • SidebarTrigger toggles the sidebar and supports the cmd/ctrl+b keyboard shortcut.
  • SidebarRail renders the clickable rail used by shadcn’s desktop sidebar.
  • SidebarInset wraps the main content when using the inset variant.
  • SidebarHeader, SidebarFooter, and SidebarContent match the shadcn layout regions.
  • SidebarGroup, SidebarGroupLabel, SidebarGroupAction, and SidebarGroupContent build sidebar sections.
  • SidebarMenu, SidebarMenuItem, SidebarMenuButton, SidebarMenuAction, SidebarMenuBadge, SidebarMenuSkeleton, SidebarMenuSub, SidebarMenuSubItem, and SidebarMenuSubButton match the menu primitives from shadcn.
  • SidebarInput and SidebarSeparator provide the shadcn sidebar input and separator styles.

SidebarProvider

These CSS variables set the provider widths for the desktop, mobile, and collapsed sidebar:

<SidebarProvider style="--sidebar-width: 20rem; --sidebar-width-mobile: 20rem;">
  <Sidebar />
</SidebarProvider>

Props

Name Type Description
defaultOpen boolean Sets the initial desktop state. Defaults to true.
open boolean Sets the initial desktop state explicitly.

Props

Name Type Description
side "left" | "right" Which side the sidebar should appear on.
variant "sidebar" | "floating" | "inset" Visual variant for the desktop shell.
collapsible "offcanvas" | "icon" | "none" Collapse behavior.

Examples

Basic Sidebar

---
import Ellipsis from "@lucide/astro/icons/ellipsis"
import Folder from "@lucide/astro/icons/folder"
import FolderGit2 from "@lucide/astro/icons/folder-git-2"
import Plus from "@lucide/astro/icons/plus"

import {
  SidebarGroup,
  SidebarGroupAction,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuAction,
  SidebarMenuBadge,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
} from "@/components/ui/sidebar"
---

<SidebarGroup class="bg-sidebar w-72 rounded-lg border">
  <SidebarGroupLabel>Projects</SidebarGroupLabel>
  <SidebarGroupAction aria-label="Add project">
    <Plus />
  </SidebarGroupAction>
  <SidebarGroupContent>
    <SidebarMenu>
      <SidebarMenuItem>
        <SidebarMenuButton href="/projects/web" isActive>
          <Folder />
          <span>Web App</span>
        </SidebarMenuButton>
        <SidebarMenuAction showOnHover aria-label="More actions">
          <Ellipsis />
        </SidebarMenuAction>
        <SidebarMenuBadge>12</SidebarMenuBadge>
      </SidebarMenuItem>
      <SidebarMenuItem>
        <SidebarMenuButton>
          <FolderGit2 />
          <span>Internal Tools</span>
        </SidebarMenuButton>
        <SidebarMenuSub>
          <SidebarMenuSubItem>
            <SidebarMenuSubButton href="/projects/internal/design">
              Design System
            </SidebarMenuSubButton>
          </SidebarMenuSubItem>
          <SidebarMenuSubItem>
            <SidebarMenuSubButton href="/projects/internal/docs">
              Docs
            </SidebarMenuSubButton>
          </SidebarMenuSubItem>
        </SidebarMenuSub>
      </SidebarMenuItem>
    </SidebarMenu>
  </SidebarGroupContent>
</SidebarGroup>

Floating Variant

Astro Notes

  • The visual structure, classes, keyboard shortcut, cookie persistence, icon collapse mode, offcanvas mode, floating variant, inset layout, and tooltip behavior now track the shadcn reference closely in Astro.
  • SidebarMenuButton accepts the same tooltip-style shorthand as the shadcn component, including a string or tooltip-content props object.

API Reference

Read the installed source for the complete prop types.

When to use Sidebar

Use Sidebar parts to build the navigation that belongs to your application shell. Keep groups and labels tied to the site structure, and mark the current destination clearly.

Keyboard and behavior

The existing client behavior manages the sidebar state. Test the trigger, focus visibility, and the narrow-screen layout after Astro navigation. Collapsed icons need accessible names when text is hidden.

Theme and layout

Check long labels, nested links, and scroll overflow with the chosen theme. The sidebar does not define routes or access rules. Keep those in the application that owns the pages.