import * as React from "react"
import { ChevronRightIcon, PanelLeftCloseIcon, PanelLeftOpenIcon, SearchIcon, XIcon, type LucideIcon } from "lucide-react"
import { cn } from "../lib/utils"
import { Avatar, AvatarFallback } from "../ui/avatar"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
} from "../ui/dropdown-menu"
import { Kbd } from "../ui/kbd"
import { ScrollArea } from "../ui/scroll-area"
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
import { MAX_VISIBLE_TABS, splitTabs } from "./page-tabs"
import { useCloseSectionTab, useStoredSectionTabs, type SectionTab } from "./section-tabs"
import { ShellLink, useShell } from "./shell-provider"
export interface SidebarNavItem {
readonly to: string
readonly label: string
readonly icon: LucideIcon
/** Счётчик справа от названия (непрочитанное, ждёт действия); 0 — не показывается. */
readonly badge?: number
/** Цвет счётчика: negative — красный (по умолчанию), warning — жёлтый. */
readonly badgeTone?: "negative" | "warning"
/** Раздел ещё не готов: серый, без перехода. */
readonly disabled?: boolean
/** Раздел со вкладками (SectionTabsProvider section=…): под пунктом — открытые карточки. */
readonly tabsSection?: string
/** Когда пункт активен; по умолчанию — адрес равен `to` или начинается с `to/`. */
readonly match?: (pathname: string) => boolean
}
export interface SidebarNavGroup {
readonly label: string
readonly items: readonly SidebarNavItem[]
}
export interface SidebarSearch {
/** Подпись кнопки («Поиск», «Штрихкод»). */
readonly label: string
/** Подсказка в свёрнутом меню. */
readonly tooltip: string
readonly shortcut?: string
readonly icon?: LucideIcon
readonly onClick: () => void
}
export interface SidebarUser {
readonly name: string
readonly subtitle?: string
readonly initials: string
}
export interface AppSidebarProps {
collapsed: boolean
onToggle: () => void
/** Логотип; получает свёрнутость меню. */
logo: (collapsed: boolean) => React.ReactNode
/** Справа от логотипа в развёрнутом меню (часы, окружение). */
headerExtra?: React.ReactNode
search?: SidebarSearch
groups: readonly SidebarNavGroup[]
user?: SidebarUser
/** Пункты меню пользователя (DropdownMenuLabel, DropdownMenuItem…). */
userMenu?: React.ReactNode
className?: string
}
const toneDot = (tone: SectionTab["tone"], fallback: string) =>
tone === "female" ? "bg-female" : tone === "male" ? "bg-male" : fallback
/**
* Тёмное боковое меню: логотип, кнопка поиска, разделы группами со счётчиками,
* открытые карточки разделов со вкладками, пользователь и сворачивание. Обычно — внутри AppShell.
*/
export function AppSidebar({
collapsed,
onToggle,
logo,
headerExtra,
search,
groups,
user,
userMenu,
className,
}: AppSidebarProps) {
const SearchItemIcon = search?.icon ?? SearchIcon
return (
)
}
function SidebarTooltip({ label, enabled, children }: { label: string; enabled: boolean; children: React.ReactElement }) {
if (!enabled) return children
return (
{children}
{label}
)
}
const isUnder = (pathname: string, base: string) => pathname === base || pathname.startsWith(`${base}/`)
function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boolean }) {
const Icon = item.icon
const { pathname, navigate } = useShell()
const closeTab = useCloseSectionTab()
const active = item.match ? item.match(pathname) : isUnder(pathname, item.to)
const count = item.badge ?? 0
const openTabs = useStoredSectionTabs(item.tabsSection ?? "")
const tabs = item.tabsSection ? openTabs : []
const isHere = (tab: SectionTab) => isUnder(pathname, tab.base)
// Тот же лимит, что у вкладок в шапке раздела; открытая сейчас карточка всегда видна.
// Строка «ещё 1» занимает столько же места, сколько сама карточка, — поэтому одну лишнюю просто показываем.
const limit = tabs.length <= MAX_VISIBLE_TABS + 1 ? tabs.length : MAX_VISIBLE_TABS
const { visible, hidden } = splitTabs(tabs, tabs.find(isHere)?.id, limit)
const label = count > 0 ? `${item.label}: ${count}` : item.label
const base = cn(
"relative flex h-8.5 items-center rounded-lg text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-primary/60",
collapsed ? "justify-center" : "gap-3 px-3",
)
if (item.disabled) {
return (
{!collapsed && item.label}
)
}
return (
<>
{active && }
{/* При наведении иконка окрашивается и чуть увеличивается (без анимации, если в системе «уменьшить движение»). */}
{!collapsed && {item.label}}
{count > 0 ? (
{count > 999 ? "999+" : count}
) : tabs.length > 0 ? (
collapsed ? (
) : (
{tabs.length}
)
) : null}
{/* Открытые карточки раздела — «зеркало» вкладок прямо в меню */}
{!collapsed && tabs.length > 0 && (
{visible.map((tab) => {
const here = isHere(tab)
return (
-
{tab.alert && (
)}
)
})}
{hidden.length > 0 && (
-
Ещё открыто
{hidden.map((tab) => (
navigate(tab.href)} className="group/item gap-2 pr-1">
{tab.label}
{tab.alert && }
))}
)}
)}
>
)
}
function UserMenu({ user, collapsed, menu }: { user: SidebarUser; collapsed: boolean; menu?: React.ReactNode }) {
const trigger = (
)
if (!menu) return trigger
return (
{trigger}
{menu}
)
}
function SidebarIconButton({ label, onClick, children }: { label: string; onClick: () => void; children: React.ReactNode }) {
return (
{label}
)
}