{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"sidebar","type":"registry:block","title":"Sidebar","description":"The app sidebar, ready to use: workspace switcher, search, counts, groups and account. Drag its edge to resize it or fold it into a rail where no icon moves.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/avatar.json?as=dependency","https://hairlineui.com/r/dropdown-menu.json?as=dependency","https://hairlineui.com/r/number-roll.json?as=dependency","https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/sidebar.tsx","type":"registry:component","content":"// Hairline UI · sidebar · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { ChevronRight, ChevronsUpDown, Search } from \"lucide-react\";\nimport { Avatar } from \"./avatar\";\nimport { DropdownMenu, type MenuEntry } from \"./dropdown-menu\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\nimport { SCRIM } from \"./modal\";\nimport {\n  EASE_OUT,\n  createSpring,\n  projectInertia,\n  releaseVelocity,\n  rubberBand,\n  samplePointer,\n  softenVelocity,\n  type PointerSample,\n  type Spring,\n} from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * SIDEBAR: the app's navigation, and the frame around the page\n *\n *   fold     the panel folds into an icon rail on one spring.\n *            Icons never move: labels fade as the edge passes,\n *            section names turn into short rules, and each count\n *            travels onto its icon's corner\n *   drag     the edge is a handle: drag to resize, keep going\n *            and the fold follows your hand; let go and the\n *            throw decides, rail or open\n *   peek     in the rail, the hover fill grows out of the rail\n *            into the label (and the children, for a group)\n *   glide    the current page's fill glides to the new row\n *   drawer   below 768px of its own width the panel is a\n *            drawer: swipe in from the edge, drag it shut\n *\n * One layout for the whole app: <Sidebar …>{page}</Sidebar>.\n * ───────────────────────────────────────────────────────── */\n\nexport type SidebarIcon = React.ComponentType<{ className?: string; strokeWidth?: number; \"aria-hidden\"?: boolean | \"true\" | \"false\" }>;\n\nexport interface SidebarItem {\n  id: string;\n  label: string;\n  /** A lucide icon (or any component taking className). */\n  icon?: SidebarIcon;\n  /** A colour tile instead of an icon, for projects, teams and channels. */\n  color?: string;\n  /** Rendered as a link (linkAs) when set, else as a button. */\n  href?: string;\n  /** A count; 0 hides it. In the rail it rides on the icon's corner. */\n  badge?: number;\n  /** An unread dot on the icon. */\n  dot?: boolean;\n  /** One level of children; the row becomes a group that opens and closes. */\n  items?: SidebarItem[];\n}\n\nexport interface SidebarSection {\n  id: string;\n  label?: string;\n  items: SidebarItem[];\n}\n\nexport interface SidebarWorkspace {\n  id: string;\n  name: string;\n  /** A second line under the name: a plan, a member count. */\n  detail?: string;\n  /** A logo image; otherwise initials on a tile. */\n  logo?: string;\n  /** The tile's colour. Defaults to --chart-1…5 in turn. */\n  color?: string;\n}\n\nexport interface SidebarUser {\n  name: string;\n  detail?: string;\n  avatar?: string;\n}\n\nexport interface SidebarProps {\n  sections: SidebarSection[];\n  /** Rows above the account, e.g. Support and Settings. */\n  footer?: SidebarItem[];\n  /** The current page's item id. */\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (id: string, item: SidebarItem) => void;\n  collapsed?: boolean;\n  defaultCollapsed?: boolean;\n  onCollapsedChange?: (collapsed: boolean) => void;\n  /** The open width, px. */\n  width?: number;\n  defaultWidth?: number;\n  onWidthChange?: (width: number) => void;\n  minWidth?: number;\n  maxWidth?: number;\n  /** Drag the edge to resize and fold. */\n  resizable?: boolean;\n  workspaces?: SidebarWorkspace[];\n  workspace?: string;\n  defaultWorkspace?: string;\n  onWorkspaceChange?: (id: string) => void;\n  /** Extra entries under the workspace list, e.g. \"Create workspace\". */\n  workspaceActions?: MenuEntry[];\n  user?: SidebarUser;\n  /** The account menu, opened from the user row. */\n  userMenu?: MenuEntry[];\n  /** Shows a search row; open your command palette here. */\n  onSearch?: () => void;\n  searchLabel?: string;\n  /** The hint on the search row. Display only: your palette owns the shortcut. */\n  searchShortcut?: string;\n  /** A card above the footer (an upgrade, an announcement). Hidden in the rail. */\n  notice?: React.ReactNode;\n  /** The link component for items with href, e.g. Next.js Link. */\n  linkAs?: React.ElementType;\n  /** Below this width of its own, the sidebar becomes a drawer. */\n  drawerBelow?: number;\n  /** ⌘B / Ctrl+B toggles the sidebar (not while typing). */\n  shortcut?: boolean;\n  /** Accessible name of the navigation. */\n  label?: string;\n  className?: string;\n  /** The page beside the sidebar. */\n  children?: React.ReactNode;\n}\n\nconst RAIL = 60;\nconst FOLD = { stiffness: 520, damping: 46 };\nconst SLIDE = { stiffness: 340, damping: 34 };\nconst EMPTY: SidebarItem[] = [];\nconst NO_ENTRIES: MenuEntry[] = [];\n\n/** 1 when open, 0 in the rail; written to --p on the panel every frame of the fold. */\nconst LABEL: React.CSSProperties = { opacity: \"clamp(0, calc(var(--p, 1) * 1.5 - 0.35), 1)\" };\nconst LABEL_FAST: React.CSSProperties = { opacity: \"clamp(0, calc(var(--p, 1) * 3 - 2), 1)\" };\nconst RULE: React.CSSProperties = { opacity: \"calc(1 - clamp(0, calc(var(--p, 1) * 1.5 - 0.35), 1))\" };\nconst BADGE: React.CSSProperties = {\n  transform: \"translateY(calc((1 - var(--p, 1)) * -9px)) scale(calc(0.74 + 0.26 * var(--p, 1)))\",\n  transformOrigin: \"right center\",\n  background: \"color-mix(in oklab, var(--primary) calc((1 - var(--p, 1)) * 100%), var(--ui-sb-badge))\",\n  color: \"color-mix(in oklab, var(--primary-foreground) calc((1 - var(--p, 1)) * 100%), var(--ui-sb-badge-fg))\",\n  boxShadow: \"0 0 0 calc((1 - var(--p, 1)) * 2px) var(--ui-sb-bg)\",\n};\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\nconst clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));\nconst initialsOf = (name: string) => {\n  const parts = name.trim().split(/\\s+/).filter(Boolean);\n  return ((parts[0]?.[0] ?? \"\") + (parts.length > 1 ? parts[parts.length - 1][0] : \"\")).toUpperCase();\n};\n/** Whether a className already sets the height (h-dvh, size-full, md:h-screen…; min-h-* works beside it); then the default h-full must stay out of its way. */\nconst SIZED = /(^|[\\s:])(h|size)-/;\nconst isEditable = (el: EventTarget | null) =>\n  el instanceof HTMLElement && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName) || !!el.closest(\"[contenteditable='true']\"));\n\n/* ── context, for SidebarTrigger and the page ─────────────── */\n\ninterface SidebarState {\n  /** The desktop panel is folded into the rail. */\n  collapsed: boolean;\n  /** The sidebar is a drawer (narrow layout). */\n  drawer: boolean;\n  /** The drawer is out. */\n  drawerOpen: boolean;\n  /** Fold or unfold on wide layouts, open or close the drawer on narrow ones. */\n  toggle: () => void;\n  setDrawerOpen: (open: boolean) => void;\n  /** A callback ref for the trigger, so focus can return to it when the drawer closes. */\n  setTrigger: (el: HTMLButtonElement | null) => void;\n}\nconst SidebarContext = React.createContext<SidebarState | null>(null);\n\nexport function useSidebar() {\n  const state = React.useContext(SidebarContext);\n  if (!state) throw new Error(\"useSidebar must be used inside <Sidebar>.\");\n  return state;\n}\n\n/** The panel glyph: its pane slides shut as the sidebar folds. */\nfunction PanelGlyph({ open, reduced }: { open: boolean; reduced: boolean }) {\n  const t = reduced ? \"none\" : `transform 380ms ${EASE_OUT}, opacity 240ms ${EASE_OUT}`;\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth={1.5} strokeLinecap=\"round\" className=\"size-4\" aria-hidden=\"true\">\n      <rect x=\"1.75\" y=\"2.75\" width=\"12.5\" height=\"10.5\" rx=\"2.5\" />\n      <rect x=\"3\" y=\"4\" width=\"3.25\" height=\"8\" rx=\"1\" fill=\"currentColor\" stroke=\"none\" style={{ opacity: open ? 0.28 : 0, transform: open ? \"none\" : \"scaleX(0.2)\", transformOrigin: \"3px 8px\", transition: t }} />\n      <path d=\"M6.75 3v10\" style={{ transform: open ? \"none\" : \"translateX(-2.25px)\", transition: t }} />\n    </svg>\n  );\n}\n\n/** The button that opens the drawer on phones and folds the panel on wide screens. Put it in your page header. */\nexport function SidebarTrigger({ className = \"\", ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) {\n  const { collapsed, drawer, drawerOpen, toggle, setTrigger } = useSidebar();\n  const reduced = useReducedMotion();\n  const open = drawer ? drawerOpen : !collapsed;\n  return (\n    <button\n      ref={setTrigger}\n      type=\"button\"\n      aria-label={open ? \"Close sidebar\" : \"Open sidebar\"}\n      aria-expanded={open}\n      aria-keyshortcuts=\"Meta+B Control+B\"\n      onClick={toggle}\n      className={`inline-flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-[10px] text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 ${className}`}\n      {...props}\n    >\n      <PanelGlyph open={open} reduced={reduced} />\n    </button>\n  );\n}\n\n/* ── small parts ──────────────────────────────────────────── */\n\nfunction WorkspaceMark({ workspace, index }: { workspace: SidebarWorkspace; index: number }) {\n  const tint = workspace.color ?? `var(--chart-${(index % 5) + 1}, var(--primary))`;\n  return (\n    <span\n      key={workspace.id}\n      className=\"relative flex size-7 shrink-0 items-center justify-center overflow-hidden rounded-[8px] text-[11.5px] font-semibold text-primary-foreground motion-safe:animate-[ui-empty-in_320ms_cubic-bezier(0.16,1,0.3,1)_backwards]\"\n      style={{ background: tint, color: `oklch(from ${tint} clamp(0.2, (0.66 - l) * 100, 0.97) calc(c * 0.6) h)` }}\n    >\n      {workspace.logo ? (\n        // eslint-disable-next-line @next/next/no-img-element\n        <img src={workspace.logo} alt=\"\" className=\"size-full object-cover\" />\n      ) : (\n        initialsOf(workspace.name)\n      )}\n    </span>\n  );\n}\n\nfunction ItemIcon({ item }: { item: SidebarItem }) {\n  const Icon = item.icon;\n  return (\n    <span className=\"relative flex size-4 shrink-0 items-center justify-center\">\n      {Icon ? (\n        <Icon className=\"size-4\" strokeWidth={1.75} aria-hidden=\"true\" />\n      ) : (\n        <span className=\"size-2.5 rounded-[3px]\" style={{ background: item.color ?? \"var(--muted-foreground)\" }} />\n      )}\n      {item.dot && <span aria-hidden=\"true\" className=\"absolute -right-0.5 -top-0.5 size-[7px] rounded-full bg-primary shadow-[0_0_0_2px_var(--ui-sb-bg)]\" />}\n    </span>\n  );\n}\n\nfunction Badge({ value }: { value: number }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute right-1.5 top-1/2 -mt-[9px] flex h-[18px] min-w-[18px] items-center justify-center rounded-full px-[5px] text-[11px] font-medium leading-none tabular-nums\"\n      style={BADGE}\n    >\n      <NumberRoll value={value} duration={700} />\n    </span>\n  );\n}\n\n/** A branch from the group's icon into a child row. */\nfunction Branch({ first, last }: { first: boolean; last: boolean }) {\n  return (\n    <svg aria-hidden=\"true\" className=\"pointer-events-none absolute left-0 top-0 h-full w-10 overflow-visible text-[color-mix(in_oklab,var(--foreground)_16%,var(--border))]\" preserveAspectRatio=\"none\" viewBox=\"0 0 40 32\">\n      {!last && <path d={first ? \"M22 -8V32\" : \"M22 0V32\"} stroke=\"currentColor\" strokeWidth={1} vectorEffect=\"non-scaling-stroke\" />}\n      <path d={first ? \"M22 -8V10Q22 16 28 16H32\" : \"M22 0V10Q22 16 28 16H32\"} fill=\"none\" stroke=\"currentColor\" strokeWidth={1} vectorEffect=\"non-scaling-stroke\" />\n    </svg>\n  );\n}\n\n/* ── the sidebar ──────────────────────────────────────────── */\n\ntype Peek = { item: SidebarItem; top: number };\n\nexport function Sidebar({\n  sections,\n  footer = EMPTY,\n  value: valueProp,\n  defaultValue,\n  onValueChange,\n  collapsed: collapsedProp,\n  defaultCollapsed = false,\n  onCollapsedChange,\n  width: widthProp,\n  defaultWidth = 256,\n  onWidthChange,\n  minWidth = 220,\n  maxWidth = 360,\n  resizable = true,\n  workspaces,\n  workspace: workspaceProp,\n  defaultWorkspace,\n  onWorkspaceChange,\n  workspaceActions = NO_ENTRIES,\n  user,\n  userMenu,\n  onSearch,\n  searchLabel = \"Search\",\n  searchShortcut = \"⌘K\",\n  notice,\n  linkAs: LinkAs = \"a\",\n  drawerBelow = 768,\n  shortcut = true,\n  label = \"Main\",\n  className = \"\",\n  children,\n}: SidebarProps) {\n  const reduced = useReducedMotion();\n  const navId = React.useId();\n\n  const [ownCollapsed, setOwnCollapsed] = React.useState(defaultCollapsed);\n  const collapsed = collapsedProp ?? ownCollapsed;\n  const [ownWidth, setOwnWidth] = React.useState(defaultWidth);\n  const openWidth = clamp(widthProp ?? ownWidth, minWidth, maxWidth);\n  const firstId = sections[0]?.items[0]?.id ?? \"\";\n  const [ownValue, setOwnValue] = React.useState(defaultValue ?? firstId);\n  const value = valueProp ?? ownValue;\n  const [ownWorkspace, setOwnWorkspace] = React.useState(defaultWorkspace ?? workspaces?.[0]?.id);\n  const workspaceId = workspaceProp ?? ownWorkspace;\n  const workspaceIndex = Math.max(0, workspaces?.findIndex((w) => w.id === workspaceId) ?? 0);\n  const workspace = workspaces?.[workspaceIndex];\n\n  // Which group holds which child, for keeping the current page visible when its group is shut.\n  const parentOf = React.useMemo(() => {\n    const map = new Map<string, string>();\n    for (const list of [...sections.map((s) => s.items), footer]) for (const item of list) for (const child of item.items ?? EMPTY) map.set(child.id, item.id);\n    return map;\n  }, [sections, footer]);\n  const [expanded, setExpanded] = React.useState<Set<string>>(() => new Set(parentOf.has(value) ? [parentOf.get(value)!] : []));\n\n  const [drawer, setDrawer] = React.useState(false);\n  const [measured, setMeasured] = React.useState(false);\n  const [drawerOpen, setDrawerOpenState] = React.useState(false);\n  const [wsMenu, setWsMenu] = React.useState(false);\n  const [peek, setPeek] = React.useState<Peek | null>(null);\n  const [peekOpen, setPeekOpen] = React.useState(false);\n  const [peekGlide, setPeekGlide] = React.useState(false);\n  const [resizing, setResizing] = React.useState(false);\n  const [scrollEdge, setScrollEdge] = React.useState<{ top: boolean; bottom: boolean }>({ top: true, bottom: true });\n\n  const rail = collapsed && !drawer;\n  const parentId = parentOf.get(value);\n  const shownActive = parentId && (rail || !expanded.has(parentId)) ? parentId : value;\n\n  const root = React.useRef<HTMLDivElement>(null);\n  const aside = React.useRef<HTMLElement>(null);\n  const panel = React.useRef<HTMLDivElement>(null);\n  const scrim = React.useRef<HTMLDivElement>(null);\n  const navContent = React.useRef<HTMLDivElement>(null);\n  const ghost = React.useRef<HTMLDivElement>(null);\n  const triggerRef = React.useRef<HTMLButtonElement>(null);\n  const foldSpring = React.useRef<Spring | null>(null);\n  const slideSpring = React.useRef<Spring | null>(null);\n  const geometry = React.useRef({ drawer: false, drawerWidth: 280, minWidth });\n  const resize = React.useRef<{ id: number; x: number; w: number; moved: boolean; samples: PointerSample[] } | null>(null);\n  const swipe = React.useRef<{ id: number; x: number; y: number; q: number; axis: \"x\" | \"y\" | null; samples: PointerSample[] } | null>(null);\n  const peekTimer = React.useRef(0);\n  const [initial] = React.useState(() => ({ width: collapsed ? RAIL : openWidth, p: collapsed ? 0 : 1 }));\n\n  const setCollapsed = React.useCallback(\n    (next: boolean) => {\n      if (collapsedProp === undefined) setOwnCollapsed(next);\n      setPeekOpen(false);\n      onCollapsedChange?.(next);\n    },\n    [collapsedProp, onCollapsedChange],\n  );\n  const commitWidth = (next: number) => {\n    if (widthProp === undefined) setOwnWidth(next);\n    onWidthChange?.(next);\n  };\n  const setDrawerOpen = React.useCallback((next: boolean) => setDrawerOpenState(next), []);\n  const toggle = React.useCallback(() => {\n    if (geometry.current.drawer) setDrawerOpenState((o) => !o);\n    else setCollapsed(!collapsed);\n  }, [collapsed, setCollapsed]);\n\n  /* springs: the fold (panel width) and the drawer (0 shut … 1 out) */\n  React.useLayoutEffect(() => {\n    const paintFold = () => {\n      const el = aside.current;\n      if (!el || geometry.current.drawer) return;\n      const w = fold.get();\n      el.style.width = `${w}px`;\n      el.style.setProperty(\"--p\", clamp((w - RAIL) / (geometry.current.minWidth - RAIL), 0, 1).toFixed(4));\n    };\n    const paintSlide = () => {\n      const el = aside.current;\n      if (!el || !geometry.current.drawer) return;\n      const q = slide.get();\n      el.style.transform = `translate3d(${(Math.min(q, 1) - 1) * (geometry.current.drawerWidth + 16) + Math.max(0, q - 1) * geometry.current.drawerWidth}px,0,0)`;\n      if (scrim.current) scrim.current.style.opacity = String(clamp(q, 0, 1));\n    };\n    const fold = createSpring(initial.width, FOLD, paintFold, 0.1);\n    const slide = createSpring(0, SLIDE, paintSlide, 0.0005);\n    foldSpring.current = fold;\n    slideSpring.current = slide;\n    return () => {\n      fold.stop();\n      slide.stop();\n    };\n  }, [initial]);\n\n  React.useLayoutEffect(() => {\n    geometry.current.minWidth = minWidth;\n  }, [minWidth]);\n\n  // Drawer or panel, from the layout's own width (so it works in any frame, not only full-screen).\n  React.useLayoutEffect(() => {\n    const el = root.current;\n    if (!el) return;\n    const observer = new ResizeObserver(([entry]) => {\n      const w = entry.contentRect.width;\n      geometry.current.drawerWidth = Math.min(openWidth, w - 56);\n      setDrawer(w < drawerBelow);\n      setMeasured(true);\n    });\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [drawerBelow, openWidth]);\n\n  // Entering or leaving drawer mode rewrites the panel's geometry once.\n  const latest = React.useRef({ collapsed, openWidth });\n  React.useLayoutEffect(() => {\n    latest.current = { collapsed, openWidth };\n  }, [collapsed, openWidth]);\n  React.useLayoutEffect(() => {\n    const el = aside.current;\n    if (!el || !measured) return;\n    geometry.current.drawer = drawer;\n    if (drawer) {\n      el.style.width = `${geometry.current.drawerWidth}px`;\n      el.style.setProperty(\"--p\", \"1\");\n      slideSpring.current?.jump(0);\n    } else {\n      el.style.transform = \"\";\n      foldSpring.current?.jump(latest.current.collapsed ? RAIL : latest.current.openWidth);\n    }\n  }, [drawer, measured]);\n\n  // The fold follows collapsed and the open width.\n  React.useLayoutEffect(() => {\n    const fold = foldSpring.current;\n    if (!fold || drawer || resize.current?.moved) return;\n    const target = collapsed ? RAIL : openWidth;\n    if (reduced) fold.jump(target);\n    else fold.set(target);\n  }, [collapsed, openWidth, drawer, reduced]);\n\n  // The drawer follows drawerOpen; focus goes in with it and back to the trigger after.\n  React.useEffect(() => {\n    const slide = slideSpring.current;\n    if (!slide || !drawer) return;\n    if (swipe.current?.axis !== \"x\") {\n      if (reduced) slide.jump(drawerOpen ? 1 : 0);\n      else slide.set(drawerOpen ? 1 : 0);\n    }\n    if (drawerOpen) panel.current?.focus({ preventScroll: true });\n    else if (panel.current?.contains(document.activeElement)) triggerRef.current?.focus({ preventScroll: true });\n  }, [drawerOpen, drawer, reduced]);\n\n  // ⌘B / Ctrl+B, but never while someone is typing (it's bold in an editor).\n  const toggleRef = React.useRef(toggle);\n  React.useLayoutEffect(() => {\n    toggleRef.current = toggle;\n  }, [toggle]);\n  React.useEffect(() => {\n    if (!shortcut) return;\n    const onKey = (e: KeyboardEvent) => {\n      if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey || e.key.toLowerCase() !== \"b\" || isEditable(e.target)) return;\n      e.preventDefault();\n      toggleRef.current();\n    };\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  }, [shortcut]);\n\n  // The current page's fill glides from the old row to the new one.\n  const lastActive = React.useRef(shownActive);\n  React.useLayoutEffect(() => {\n    const from = lastActive.current;\n    lastActive.current = shownActive;\n    const content = navContent.current;\n    const layer = ghost.current;\n    if (!content || !layer || from === shownActive || reduced) return;\n    const a = content.querySelector<HTMLElement>(`[data-row-id=\"${CSS.escape(from)}\"]`);\n    const b = content.querySelector<HTMLElement>(`[data-row-id=\"${CSS.escape(shownActive)}\"]`);\n    if (!a || !b || !a.offsetHeight || !b.offsetHeight) return;\n    const box = content.getBoundingClientRect();\n    const ra = a.getBoundingClientRect();\n    const rb = b.getBoundingClientRect();\n    layer.animate(\n      [\n        { opacity: 1, transform: `translate3d(${ra.left - box.left}px,${ra.top - box.top}px,0)`, width: `${ra.width}px`, height: `${ra.height}px` },\n        { opacity: 1, transform: `translate3d(${rb.left - box.left}px,${rb.top - box.top}px,0)`, width: `${rb.width}px`, height: `${rb.height}px` },\n      ],\n      { duration: 340, easing: \"cubic-bezier(0.16,1,0.3,1)\" },\n    );\n  }, [shownActive, reduced]);\n\n  // Fades at the top and bottom of the list only where there's more to scroll.\n  const onNavScroll = (e: React.UIEvent<HTMLElement>) => {\n    const el = e.currentTarget;\n    const top = el.scrollTop < 2;\n    const bottom = el.scrollTop + el.clientHeight > el.scrollHeight - 2;\n    setScrollEdge((s) => (s.top === top && s.bottom === bottom ? s : { top, bottom }));\n  };\n  React.useEffect(() => {\n    const el = navContent.current?.parentElement;\n    if (!el) return;\n    const observer = new ResizeObserver(() => {\n      const top = el.scrollTop < 2;\n      const bottom = el.scrollTop + el.clientHeight > el.scrollHeight - 2;\n      setScrollEdge((s) => (s.top === top && s.bottom === bottom ? s : { top, bottom }));\n    });\n    observer.observe(el);\n    if (navContent.current) observer.observe(navContent.current);\n    return () => observer.disconnect();\n  }, []);\n\n  /* choosing */\n  const choose = (item: SidebarItem) => {\n    if (valueProp === undefined) setOwnValue(item.id);\n    onValueChange?.(item.id, item);\n    if (drawer) setDrawerOpenState(false);\n    setPeekOpen(false);\n  };\n  const toggleGroup = (id: string) =>\n    setExpanded((set) => {\n      const next = new Set(set);\n      if (next.has(id)) next.delete(id);\n      else next.add(id);\n      return next;\n    });\n  const chooseWorkspace = (id: string) => {\n    if (workspaceProp === undefined) setOwnWorkspace(id);\n    onWorkspaceChange?.(id);\n  };\n\n  /* the peek, in the rail */\n  const showPeek = (item: SidebarItem, row: HTMLElement) => {\n    if (!rail || resize.current?.moved) return;\n    window.clearTimeout(peekTimer.current);\n    const box = root.current?.getBoundingClientRect();\n    const r = row.getBoundingClientRect();\n    if (!box) return;\n    setPeekGlide(peekOpen);\n    setPeek({ item, top: r.top - box.top });\n    setPeekOpen(true);\n  };\n  const hidePeek = (delay = 140) => {\n    window.clearTimeout(peekTimer.current);\n    peekTimer.current = window.setTimeout(() => setPeekOpen(false), delay);\n  };\n  React.useEffect(() => () => window.clearTimeout(peekTimer.current), []);\n  const peekShown = rail && peekOpen;\n\n  /* resizing: the edge is a handle, the fold follows the hand */\n  const onEdgeDown = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (e.button !== 0 || drawer || !foldSpring.current) return;\n    e.currentTarget.setPointerCapture(e.pointerId);\n    resize.current = { id: e.pointerId, x: e.clientX, w: foldSpring.current.get(), moved: false, samples: [] };\n  };\n  const onEdgeMove = (e: React.PointerEvent<HTMLDivElement>) => {\n    const g = resize.current;\n    const fold = foldSpring.current;\n    if (!g || !fold || e.pointerId !== g.id) return;\n    if (!g.moved) {\n      if (Math.abs(e.clientX - g.x) < 3) return;\n      // Start from here, so the first frame doesn't jump by the slop.\n      g.moved = true;\n      g.x = e.clientX;\n      g.w = fold.get();\n      setResizing(true);\n      setPeekOpen(false);\n      return;\n    }\n    const raw = g.w + (e.clientX - g.x);\n    const w = raw > maxWidth ? maxWidth + rubberBand(raw - maxWidth, 140) : raw < RAIL ? RAIL - rubberBand(RAIL - raw, 60) : raw;\n    samplePointer(g.samples, raw, e.timeStamp);\n    fold.jump(w);\n  };\n  const onEdgeUp = (e: React.PointerEvent<HTMLDivElement>) => {\n    const g = resize.current;\n    const fold = foldSpring.current;\n    resize.current = null;\n    if (!g || !fold || !g.moved) return;\n    setResizing(false);\n    const w = fold.get();\n    const v = releaseVelocity(g.samples, e.timeStamp);\n    const shut = projectInertia(w, v, 0.12) < (RAIL + minWidth) / 2;\n    const target = shut ? RAIL : clamp(Math.round(w), minWidth, maxWidth);\n    if (!reduced) fold.push(softenVelocity(v * 1000, target - w));\n    if (reduced) fold.jump(target);\n    else fold.set(target);\n    if (shut !== collapsed) setCollapsed(shut);\n    if (!shut && target !== openWidth) commitWidth(target);\n  };\n  const onEdgeKey = (e: React.KeyboardEvent<HTMLDivElement>) => {\n    if (e.key === \"Enter\" || e.key === \" \") {\n      e.preventDefault();\n      setCollapsed(!collapsed);\n    } else if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\") {\n      e.preventDefault();\n      const step = e.key === \"ArrowRight\" ? 16 : -16;\n      if (collapsed) {\n        if (step > 0) setCollapsed(false);\n        return;\n      }\n      if (step < 0 && openWidth <= minWidth) return setCollapsed(true);\n      commitWidth(clamp(openWidth + step, minWidth, maxWidth));\n    }\n  };\n\n  /* the drawer: swipe in from the edge, drag it shut */\n  const startSwipe = (e: React.PointerEvent<HTMLElement>, fromEdge: boolean) => {\n    if (!drawer || e.pointerType === \"mouse\" || !slideSpring.current) return;\n    swipe.current = { id: e.pointerId, x: e.clientX, y: e.clientY, q: slideSpring.current.get(), axis: fromEdge ? \"x\" : null, samples: [] };\n    if (fromEdge) e.currentTarget.setPointerCapture(e.pointerId);\n  };\n  const moveSwipe = (e: React.PointerEvent<HTMLElement>) => {\n    const g = swipe.current;\n    const slide = slideSpring.current;\n    if (!g || !slide || e.pointerId !== g.id) return;\n    const dx = e.clientX - g.x;\n    const dy = e.clientY - g.y;\n    if (!g.axis) {\n      if (Math.max(Math.abs(dx), Math.abs(dy)) < 8) return;\n      g.axis = Math.abs(dx) > Math.abs(dy) ? \"x\" : \"y\";\n      if (g.axis === \"y\") return;\n      e.currentTarget.setPointerCapture(e.pointerId);\n      g.x = e.clientX; // start from here: no jump by the slop\n      return;\n    }\n    if (g.axis !== \"x\") return;\n    const dw = geometry.current.drawerWidth;\n    const q = g.q + (e.clientX - g.x) / dw;\n    samplePointer(g.samples, e.clientX, e.timeStamp);\n    slide.jump(q > 1 ? 1 + rubberBand((q - 1) * dw, 80) / dw : Math.max(0, q));\n  };\n  const endSwipe = (e: React.PointerEvent<HTMLElement>) => {\n    const g = swipe.current;\n    const slide = slideSpring.current;\n    swipe.current = null;\n    if (!g || !slide || g.axis !== \"x\") return;\n    const dw = geometry.current.drawerWidth;\n    const q = slide.get();\n    const v = releaseVelocity(g.samples, e.timeStamp);\n    const open = projectInertia((q - 1) * dw, v, 0.12) > -dw / 2;\n    if (!reduced) slide.push(softenVelocity((v * 1000) / dw, (open ? 1 : 0) - q));\n    slide.set(open ? 1 : 0);\n    setDrawerOpenState(open);\n  };\n\n  /* keyboard: arrows move through the rows */\n  const onNavKey = (e: React.KeyboardEvent<HTMLElement>) => {\n    if (![\"ArrowDown\", \"ArrowUp\", \"Home\", \"End\"].includes(e.key)) return;\n    const rows = [...(aside.current?.querySelectorAll<HTMLElement>(\"[data-nav-row]\") ?? [])].filter((el) => !el.closest(\"[inert]\"));\n    const i = rows.indexOf(document.activeElement as HTMLElement);\n    if (i < 0) return;\n    e.preventDefault();\n    const next = e.key === \"Home\" ? 0 : e.key === \"End\" ? rows.length - 1 : clamp(i + (e.key === \"ArrowDown\" ? 1 : -1), 0, rows.length - 1);\n    rows[next]?.focus();\n  };\n\n  /* rows */\n  const renderRow = (item: SidebarItem, depth: 0 | 1, first = false, last = false) => {\n    const group = !!item.items?.length;\n    const open = group && expanded.has(item.id) && !rail;\n    const active = shownActive === item.id;\n    const current = value === item.id;\n    const rowClass = `group/row relative z-[1] flex w-full cursor-pointer items-center gap-2.5 rounded-[10px] text-left outline-none transition-[background-color,color] duration-150 focus-visible:ring-2 focus-visible:ring-ring/50 ${\n      depth ? \"h-8 pl-10 pr-2 text-[13px]\" : \"h-9 pl-[14px] pr-2 text-[13.5px]\"\n    } ${\n      active\n        ? \"bg-accent text-foreground [transition-delay:300ms] [transition-duration:0ms] motion-reduce:[transition-delay:0ms]\"\n        : \"text-muted-foreground hover:bg-[color-mix(in_oklab,var(--accent)_65%,transparent)] hover:text-foreground\"\n    }`;\n    const inner = (\n      <>\n        {depth === 0 && <ItemIcon item={item} />}\n        <span className=\"min-w-0 flex-1 overflow-clip whitespace-nowrap [mask-image:linear-gradient(to_right,black_calc(100%-16px),transparent)]\" style={depth ? undefined : LABEL}>\n          {item.label}\n        </span>\n        {group && (\n          <ChevronRight\n            aria-hidden=\"true\"\n            className=\"size-3.5 shrink-0 text-muted-foreground transition-transform duration-300 ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none\"\n            style={{ ...LABEL_FAST, transform: open ? \"rotate(90deg)\" : \"none\" }}\n          />\n        )}\n        {!group && !!item.badge && <span className=\"w-7 shrink-0\" />}\n        {!group && !!item.badge && <Badge value={item.badge} />}\n        {depth === 0 && rail && <span className=\"sr-only\">{item.badge ? `, ${item.badge}` : \"\"}</span>}\n      </>\n    );\n    const common = {\n      \"data-nav-row\": \"\",\n      \"data-row-id\": item.id,\n      className: rowClass,\n      onPointerEnter: (e: React.PointerEvent<HTMLElement>) => e.pointerType === \"mouse\" && depth === 0 && showPeek(item, e.currentTarget),\n      onPointerLeave: (e: React.PointerEvent<HTMLElement>) => e.pointerType === \"mouse\" && rail && hidePeek(),\n      onFocus: (e: React.FocusEvent<HTMLElement>) => depth === 0 && e.currentTarget.matches(\":focus-visible\") && showPeek(item, e.currentTarget),\n      onBlur: () => rail && hidePeek(60),\n    };\n    const row = group ? (\n      <button\n        type=\"button\"\n        {...common}\n        aria-expanded={rail ? undefined : open}\n        aria-controls={rail ? undefined : `${navId}-${item.id}`}\n        onClick={(e) => {\n          // In the rail a pointer peeks; a keyboard opens the panel on the group, where its rows can be reached.\n          if (rail && e.detail > 0) return showPeek(item, e.currentTarget);\n          if (rail) {\n            setCollapsed(false);\n            return setExpanded((set) => new Set(set).add(item.id));\n          }\n          toggleGroup(item.id);\n        }}\n      >\n        {inner}\n      </button>\n    ) : item.href ? (\n      <LinkAs href={item.href} {...common} aria-current={current ? \"page\" : undefined} onClick={() => choose(item)}>\n        {inner}\n      </LinkAs>\n    ) : (\n      <button type=\"button\" {...common} aria-current={current ? \"page\" : undefined} onClick={() => choose(item)}>\n        {inner}\n      </button>\n    );\n    return (\n      <li key={item.id} className=\"relative\">\n        {depth === 1 && <Branch first={first} last={last} />}\n        {row}\n        {group && (\n          <div\n            id={`${navId}-${item.id}`}\n            inert={!open}\n            className=\"grid transition-[grid-template-rows,opacity] duration-[420ms] ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none\"\n            style={{ gridTemplateRows: open ? \"1fr\" : \"0fr\", opacity: open ? 1 : 0 }}\n          >\n            <ul className=\"min-h-0 overflow-clip\">{item.items!.map((child, i, all) => renderRow(child, 1, i === 0, i === all.length - 1))}</ul>\n          </div>\n        )}\n      </li>\n    );\n  };\n\n  /* the parts of the panel */\n  const toggleButton = (\n    <button\n      type=\"button\"\n      onClick={toggle}\n      aria-label={drawer ? \"Close sidebar\" : rail ? \"Expand sidebar\" : \"Collapse sidebar\"}\n      aria-keyshortcuts=\"Meta+B Control+B\"\n      className=\"flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-[9px] text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50\"\n    >\n      <PanelGlyph open={!rail} reduced={reduced} />\n    </button>\n  );\n\n  const header = workspace ? (\n    <div className=\"relative flex h-14 shrink-0 items-center px-2\">\n      <div className=\"min-w-0 flex-1 [&>span]:flex [&>span]:w-full\">\n        <DropdownMenu\n          open={wsMenu}\n          onOpenChange={(open) => {\n            if (rail && open) return setCollapsed(false);\n            setWsMenu(open);\n          }}\n          label=\"Workspaces\"\n          minWidth={232}\n          items={[\n            { type: \"label\", label: \"Workspaces\" },\n            ...(workspaces ?? []).map<MenuEntry>((w) => ({ type: \"checkbox\", id: w.id, label: w.name, checked: w.id === workspaceId, onCheckedChange: () => chooseWorkspace(w.id) })),\n            ...(workspaceActions.length ? [{ type: \"separator\" } as MenuEntry, ...workspaceActions] : []),\n          ]}\n          trigger={\n            <button\n              type=\"button\"\n              aria-label={rail ? `Expand sidebar (${workspace.name})` : `Workspace: ${workspace.name}`}\n              className={`flex h-11 w-full min-w-0 cursor-pointer items-center gap-2.5 rounded-[10px] pl-2 pr-10 text-left outline-none transition-colors duration-150 hover:bg-[color-mix(in_oklab,var(--accent)_65%,transparent)] focus-visible:ring-2 focus-visible:ring-ring/50 ${rail ? \"group/ws\" : \"\"}`}\n            >\n              <span className=\"relative flex size-7 shrink-0 items-center justify-center\">\n                <span className={`transition-opacity duration-200 ${rail ? \"group-hover/ws:opacity-0 group-focus-visible/ws:opacity-0\" : \"\"}`}>\n                  <WorkspaceMark key={workspace.id} workspace={workspace} index={workspaceIndex} />\n                </span>\n                <span className={`absolute inset-0 flex items-center justify-center text-foreground opacity-0 transition-opacity duration-200 ${rail ? \"group-hover/ws:opacity-100 group-focus-visible/ws:opacity-100\" : \"\"}`}>\n                  <PanelGlyph open={false} reduced />\n                </span>\n              </span>\n              <span className=\"min-w-0 flex-1 overflow-clip whitespace-nowrap leading-tight\" style={LABEL}>\n                <TextMorph className=\"block text-[13.5px] font-medium text-foreground\">{workspace.name}</TextMorph>\n                {workspace.detail && <span className=\"block truncate text-[11.5px] text-muted-foreground\">{workspace.detail}</span>}\n              </span>\n              <ChevronsUpDown aria-hidden=\"true\" className=\"size-3.5 shrink-0 text-muted-foreground\" style={LABEL_FAST} />\n            </button>\n          }\n        />\n      </div>\n      <div className={`absolute right-2.5 top-1/2 -translate-y-1/2 ${rail ? \"pointer-events-none\" : \"\"}`} style={LABEL_FAST}>\n        {toggleButton}\n      </div>\n    </div>\n  ) : (\n    <div className=\"flex h-14 shrink-0 items-center pl-[14px]\">{toggleButton}</div>\n  );\n\n  const search = onSearch && (\n    <div className=\"shrink-0 px-2 pb-2\">\n      <button\n        type=\"button\"\n        onClick={onSearch}\n        aria-keyshortcuts={searchShortcut === \"⌘K\" ? \"Meta+K Control+K\" : undefined}\n        data-nav-row=\"\"\n        onPointerEnter={(e) => e.pointerType === \"mouse\" && rail && showPeek({ id: \"__search\", label: searchLabel, icon: Search }, e.currentTarget)}\n        onPointerLeave={(e) => e.pointerType === \"mouse\" && rail && hidePeek()}\n        className=\"relative flex h-9 w-full cursor-pointer items-center gap-2.5 overflow-clip rounded-[10px] bg-background pl-[14px] text-[13.5px] text-muted-foreground shadow-[inset_0_0_0_1px_var(--border)] outline-none transition-colors duration-150 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50\"\n      >\n        <Search className=\"size-4 shrink-0\" strokeWidth={1.75} aria-hidden=\"true\" />\n        <span className=\"whitespace-nowrap\" style={LABEL}>\n          {searchLabel}\n        </span>\n        {searchShortcut && (\n          <kbd className=\"absolute right-2 rounded-[5px] px-1.5 py-0.5 font-sans text-[11px] text-muted-foreground shadow-[inset_0_0_0_1px_var(--border)]\" style={LABEL_FAST}>\n            {searchShortcut}\n          </kbd>\n        )}\n      </button>\n    </div>\n  );\n\n  const account = user && (\n    <div className=\"shrink-0 border-t border-border px-2 py-2\">\n      {userMenu?.length ? (\n        <div className=\"[&>span]:flex [&>span]:w-full\">\n          <DropdownMenu\n            side=\"top\"\n            label=\"Account\"\n            minWidth={220}\n            items={userMenu}\n            trigger={\n              <button\n                type=\"button\"\n                aria-label={`Account: ${user.name}`}\n                className=\"flex h-11 w-full min-w-0 cursor-pointer items-center gap-2.5 rounded-[10px] pl-2 pr-2 text-left outline-none transition-colors duration-150 hover:bg-[color-mix(in_oklab,var(--accent)_65%,transparent)] focus-visible:ring-2 focus-visible:ring-ring/50\"\n              >\n                <Avatar name={user.name} src={user.avatar} size=\"sm\" />\n                <span className=\"min-w-0 flex-1 overflow-clip whitespace-nowrap leading-tight\" style={LABEL}>\n                  <span className=\"block text-[13px] font-medium text-foreground\">{user.name}</span>\n                  {user.detail && <span className=\"block truncate text-[11.5px] text-muted-foreground\">{user.detail}</span>}\n                </span>\n                <ChevronsUpDown aria-hidden=\"true\" className=\"size-3.5 shrink-0 text-muted-foreground\" style={LABEL_FAST} />\n              </button>\n            }\n          />\n        </div>\n      ) : (\n        <div className=\"flex h-11 items-center gap-2.5 pl-2\">\n          <Avatar name={user.name} src={user.avatar} size=\"sm\" />\n          <span className=\"min-w-0 flex-1 overflow-clip whitespace-nowrap leading-tight\" style={LABEL}>\n            <span className=\"block text-[13px] font-medium text-foreground\">{user.name}</span>\n            {user.detail && <span className=\"block truncate text-[11.5px] text-muted-foreground\">{user.detail}</span>}\n          </span>\n        </div>\n      )}\n    </div>\n  );\n\n  const peekItem = peek?.item;\n  const PeekIcon = peekItem?.icon;\n\n  const setTrigger = React.useCallback((el: HTMLButtonElement | null) => {\n    triggerRef.current = el;\n  }, []);\n  const state = React.useMemo<SidebarState>(() => ({ collapsed, drawer, drawerOpen, toggle, setDrawerOpen, setTrigger }), [collapsed, drawer, drawerOpen, toggle, setDrawerOpen, setTrigger]);\n\n  return (\n    <SidebarContext.Provider value={state}>\n      <div\n        ref={root}\n        className={`@container relative flex w-full min-w-0 overflow-clip bg-background text-foreground ${SIZED.test(className) ? \"\" : \"h-full\"} ${resizing ? \"cursor-ew-resize select-none\" : \"\"} ${className}`}\n        style={{ \"--ui-sb-bg\": \"var(--sidebar, color-mix(in oklab, var(--muted) 42%, var(--background)))\", \"--ui-sb-badge\": \"color-mix(in oklab, var(--foreground) 8%, transparent)\", \"--ui-sb-badge-fg\": \"var(--muted-foreground)\" } as React.CSSProperties}\n        onKeyDown={(e) => {\n          if (e.key !== \"Escape\") return;\n          if (drawer && drawerOpen) setDrawerOpenState(false);\n          if (peekOpen) setPeekOpen(false);\n        }}\n      >\n        <aside\n          ref={aside}\n          data-collapsed={rail ? \"\" : undefined}\n          inert={drawer && !drawerOpen}\n          className={`flex h-full shrink-0 flex-col bg-[var(--ui-sb-bg)] text-foreground ${\n            drawer ? \"absolute inset-y-0 left-0 z-30 rounded-r-[20px] shadow-[0_0_0_1px_var(--border)] will-change-transform\" : \"relative z-[2] border-r border-border\"\n          } ${measured ? \"\" : \"@max-3xl:hidden\"}`}\n          style={{ width: initial.width, \"--p\": initial.p } as React.CSSProperties}\n        >\n          <div\n            ref={panel}\n            tabIndex={-1}\n            role={drawer ? \"dialog\" : undefined}\n            aria-modal={drawer && drawerOpen ? true : undefined}\n            aria-label={drawer ? `${label} navigation` : undefined}\n            className=\"flex h-full min-h-0 w-full flex-col overflow-clip outline-none [touch-action:pan-y]\"\n            onPointerDown={(e) => startSwipe(e, false)}\n            onPointerMove={moveSwipe}\n            onPointerUp={endSwipe}\n            onPointerCancel={endSwipe}\n          >\n            {header}\n            {search}\n            <nav\n              aria-label={label}\n              onScroll={onNavScroll}\n              onKeyDown={onNavKey}\n              className=\"relative min-h-0 flex-1 overflow-y-auto overflow-x-clip px-2 pb-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n              style={{\n                maskImage: `linear-gradient(to bottom, ${scrollEdge.top ? \"black\" : \"transparent\"}, black 20px, black calc(100% - 20px), ${scrollEdge.bottom ? \"black\" : \"transparent\"})`,\n              }}\n            >\n              <div ref={navContent} className=\"relative\">\n                <div ref={ghost} aria-hidden=\"true\" className=\"pointer-events-none absolute left-0 top-0 rounded-[10px] bg-accent opacity-0\" />\n                {sections.map((section, i) => (\n                  <div key={section.id} className={i ? \"pt-3\" : \"\"}>\n                    {section.label && (\n                      <div className=\"relative flex h-7 items-end pb-1.5 pl-[14px] text-[11.5px] font-medium text-muted-foreground\">\n                        <span className=\"whitespace-nowrap\" style={LABEL}>\n                          {section.label}\n                        </span>\n                        <span aria-hidden=\"true\" className=\"absolute bottom-[11px] left-[14px] h-px w-4 bg-border\" style={RULE} />\n                      </div>\n                    )}\n                    <ul className=\"flex flex-col gap-px\">{section.items.map((item) => renderRow(item, 0))}</ul>\n                  </div>\n                ))}\n              </div>\n            </nav>\n            {notice && (\n              <div\n                inert={rail}\n                className=\"grid shrink-0 transition-[grid-template-rows] duration-[420ms] ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none\"\n                style={{ gridTemplateRows: rail ? \"0fr\" : \"1fr\" }}\n              >\n                <div className=\"min-h-0 overflow-clip\">\n                  <div className=\"w-full min-w-[204px] px-2 pb-2\" style={LABEL}>\n                    {notice}\n                  </div>\n                </div>\n              </div>\n            )}\n            {footer.length > 0 && (\n              <ul className=\"flex shrink-0 flex-col gap-px px-2 pb-2\" onKeyDown={onNavKey}>\n                {footer.map((item) => renderRow(item, 0))}\n              </ul>\n            )}\n            {account}\n          </div>\n\n          {resizable && !drawer && (\n            <div\n              role=\"separator\"\n              aria-orientation=\"vertical\"\n              aria-label=\"Resize sidebar\"\n              aria-valuemin={RAIL}\n              aria-valuemax={maxWidth}\n              aria-valuenow={collapsed ? RAIL : openWidth}\n              tabIndex={0}\n              onPointerDown={onEdgeDown}\n              onPointerMove={onEdgeMove}\n              onPointerUp={onEdgeUp}\n              onPointerCancel={onEdgeUp}\n              onDoubleClick={() => setCollapsed(!collapsed)}\n              onKeyDown={onEdgeKey}\n              className=\"group/edge absolute inset-y-0 -right-[5px] z-10 w-[9px] cursor-ew-resize touch-none outline-none\"\n            >\n              <span\n                className={`absolute inset-y-0 left-1/2 w-[2px] -translate-x-1/2 bg-[color-mix(in_oklab,var(--foreground)_22%,transparent)] transition-opacity duration-200 group-hover/edge:opacity-100 group-focus-visible/edge:opacity-100 ${resizing ? \"opacity-100\" : \"opacity-0\"}`}\n              />\n            </div>\n          )}\n        </aside>\n\n        {/* The peek: the rail's hover fill growing out into the label. */}\n        {rail && peekItem && (\n          <div\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute left-2 top-0 z-40\"\n            style={{\n              transform: `translateY(${peek!.top}px)`,\n              // Closing folds the label back into the rail first, then the fill fades.\n              transition: reduced ? \"none\" : `${peekGlide ? `transform 300ms ${EASE_OUT}, ` : \"\"}opacity ${peekShown ? \"0ms\" : `160ms ${EASE_OUT} 220ms`}`,\n              opacity: peekShown ? 1 : 0,\n            }}\n          >\n            <div\n              className=\"pointer-events-auto rounded-[10px] text-foreground shadow-[0_0_0_1px_var(--border)]\"\n              // The accent laid over the sidebar's own colour: themes often make --accent translucent, and the rail must not show through.\n              style={{ pointerEvents: peekShown ? \"auto\" : \"none\", background: \"linear-gradient(var(--accent), var(--accent)), linear-gradient(var(--ui-sb-bg), var(--ui-sb-bg)), var(--background)\" }}\n              onPointerEnter={() => window.clearTimeout(peekTimer.current)}\n              onPointerLeave={() => hidePeek()}\n            >\n              <button\n                type=\"button\"\n                tabIndex={-1}\n                onClick={() => {\n                  if (peekItem.id === \"__search\") return onSearch?.();\n                  if (!peekItem.items?.length) choose(peekItem);\n                }}\n                className=\"flex h-9 w-full cursor-pointer items-center pl-[14px] pr-1 text-[13.5px]\"\n              >\n                <span className=\"relative flex size-4 shrink-0 items-center justify-center\">\n                  {PeekIcon ? <PeekIcon className=\"size-4\" strokeWidth={1.75} aria-hidden=\"true\" /> : <span className=\"size-2.5 rounded-[3px]\" style={{ background: peekItem.color ?? \"var(--muted-foreground)\" }} />}\n                </span>\n                <span\n                  className=\"grid transition-[grid-template-columns] duration-[340ms] ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none\"\n                  style={{ gridTemplateColumns: peekShown ? \"1fr\" : \"0fr\" }}\n                >\n                  <span className=\"flex min-w-0 items-center overflow-clip\">\n                    <span className=\"flex items-center gap-2 whitespace-nowrap pl-2.5 pr-2.5\">\n                      <TextMorph>{peekItem.label}</TextMorph>\n                      {!!peekItem.badge && (\n                        <span className=\"flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-background px-[5px] text-[11px] font-medium tabular-nums text-muted-foreground\">\n                          <NumberRoll value={peekItem.badge} />\n                        </span>\n                      )}\n                    </span>\n                  </span>\n                </span>\n              </button>\n              {!!peekItem.items?.length && (\n                <div\n                  className=\"grid transition-[grid-template-rows] duration-[380ms] ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none\"\n                  style={{ gridTemplateRows: peekShown ? \"1fr\" : \"0fr\" }}\n                >\n                  <ul className=\"min-h-0 overflow-clip px-1 pb-1\">\n                    {peekItem.items.map((child) => (\n                      <li key={child.id}>\n                        <button\n                          type=\"button\"\n                          tabIndex={-1}\n                          onClick={() => choose(child)}\n                          className={`flex h-8 w-full cursor-pointer items-center justify-between gap-3 whitespace-nowrap rounded-[8px] pl-[34px] pr-2 text-left text-[13px] transition-colors duration-150 ${\n                            value === child.id ? \"bg-background text-foreground\" : \"text-muted-foreground hover:bg-[color-mix(in_oklab,var(--background)_60%,transparent)] hover:text-foreground\"\n                          }`}\n                        >\n                          {child.label}\n                          {!!child.badge && <span className=\"text-[11px] tabular-nums text-muted-foreground\">{child.badge}</span>}\n                        </button>\n                      </li>\n                    ))}\n                  </ul>\n                </div>\n              )}\n            </div>\n          </div>\n        )}\n\n        {drawer && (\n          <>\n            <div ref={scrim} aria-hidden=\"true\" className={`${SCRIM} z-20`} style={{ opacity: 0, pointerEvents: drawerOpen ? \"auto\" : \"none\" }} onClick={() => setDrawerOpenState(false)} />\n            {!drawerOpen && <div aria-hidden=\"true\" className=\"absolute inset-y-0 left-0 z-10 w-4 touch-none\" onPointerDown={(e) => startSwipe(e, true)} onPointerMove={moveSwipe} onPointerUp={endSwipe} onPointerCancel={endSwipe} />}\n          </>\n        )}\n\n        <div inert={drawer && drawerOpen} className=\"relative flex min-h-0 min-w-0 flex-1 flex-col\">\n          {children}\n        </div>\n      </div>\n    </SidebarContext.Provider>\n  );\n}\n\nexport default Sidebar;\n"},{"path":"registry/modal.ts","type":"registry:component","content":"// Hairline UI · sidebar · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\n\n/* ─────────────────────────────────────────────────────────\n * MODAL: the native <dialog> under Dialog and Sheet\n *\n *   open     showModal() (focus trap, inert page, top layer) and\n *            the next frame turns `shown` on for the entry motion\n *   close    Escape and the scrim ask to close; the surface plays\n *            its exit, then dialog.close() and focus goes back to\n *            whatever opened it\n *   scroll   wheel and touch scrolling outside a scrollable part\n *            of the panel are stopped at the dialog, so the page\n *            behind never moves (the page's own styles are never\n *            touched: no layout shift, no restyle of <html>)\n * ───────────────────────────────────────────────────────── */\n\nexport function useModal(open: boolean, onClose: () => void, exit = 220) {\n  const dialog = React.useRef<HTMLDialogElement>(null);\n  const [mounted, setMounted] = React.useState(open);\n  const [shown, setShown] = React.useState(false);\n  const opener = React.useRef<HTMLElement | null>(null);\n  const close = React.useRef(onClose);\n  React.useEffect(() => {\n    close.current = onClose;\n  });\n  if (open && !mounted) setMounted(true);\n\n  React.useEffect(() => {\n    const el = dialog.current;\n    if (!el) return;\n    if (open) {\n      opener.current = document.activeElement as HTMLElement | null;\n      if (!el.open) el.showModal();\n      // Start on the panel, not its first control: no keyboard popping up on phones, no\n      // slider bubble or tooltip showing uninvited.\n      el.querySelector<HTMLElement>(\"[data-modal-panel]\")?.focus({ preventScroll: true });\n      let inner = 0;\n      const outer = requestAnimationFrame(() => {\n        inner = requestAnimationFrame(() => setShown(true));\n      });\n      return () => {\n        cancelAnimationFrame(outer);\n        cancelAnimationFrame(inner);\n      };\n    }\n    const timer = window.setTimeout(() => {\n      if (el.open) el.close();\n      setMounted(false);\n      setShown(false);\n      opener.current?.focus?.({ preventScroll: true });\n    }, exit);\n    return () => window.clearTimeout(timer);\n  }, [open, mounted, exit]);\n\n  React.useEffect(() => {\n    const el = dialog.current;\n    if (!el || !mounted) return;\n    const onCancel = (e: Event) => {\n      e.preventDefault();\n      close.current();\n    };\n    // Stop scrolling from leaking to the page unless it happens inside something that scrolls.\n    const guard = (e: Event) => {\n      let node = e.target as HTMLElement | null;\n      while (node && node !== el) {\n        const style = getComputedStyle(node);\n        if (/(auto|scroll)/.test(style.overflowY) && node.scrollHeight > node.clientHeight) return;\n        node = node.parentElement;\n      }\n      e.preventDefault();\n    };\n    el.addEventListener(\"cancel\", onCancel);\n    el.addEventListener(\"wheel\", guard, { passive: false });\n    el.addEventListener(\"touchmove\", guard, { passive: false });\n    return () => {\n      el.removeEventListener(\"cancel\", onCancel);\n      el.removeEventListener(\"wheel\", guard);\n      el.removeEventListener(\"touchmove\", guard);\n    };\n  }, [mounted]);\n\n  return { dialog, mounted: mounted || open, shown: open && shown };\n}\n\n/** Class for the full-window <dialog> both surfaces sit in. */\nexport const MODAL_ROOT =\n  // overflow: clip, never hidden: hidden can still be scrolled, and focusing something inside\n  // the off-screen panel scrolled the dialog mid-slide (the sheet's jerk on opening).\n  \"fixed inset-0 m-0 h-dvh max-h-none w-screen max-w-none overflow-clip bg-transparent p-0 text-foreground outline-none backdrop:bg-transparent\";\n\n/** The dim behind the surface: the page fades back under a veil of the background colour, no blur. */\nexport const SCRIM = \"absolute inset-0 bg-[color-mix(in_oklab,var(--background)_62%,transparent)]\";\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · sidebar · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{"@keyframes ui-empty-in":{"from":{"opacity":"0","transform":"translateY(4px)","filter":"blur(4px)"},"to":{"opacity":"1","transform":"none","filter":"none"}}},"docs":"Docs and live preview: https://hairlineui.com/ui/sidebar. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}