399 lines
18 KiB
TypeScript
399 lines
18 KiB
TypeScript
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 (
|
||
<aside
|
||
className={cn(
|
||
"flex h-svh shrink-0 flex-col overflow-clip border-r border-sidebar-border/80 bg-sidebar text-sidebar-foreground transition-[width] duration-200 print:hidden",
|
||
collapsed ? "w-[60px]" : "w-56",
|
||
className,
|
||
)}
|
||
>
|
||
<div className={cn("flex h-16 shrink-0 items-center", collapsed ? "justify-center" : "gap-2.5 px-5")}>
|
||
{logo(collapsed)}
|
||
{!collapsed && headerExtra}
|
||
</div>
|
||
|
||
{search && (
|
||
<div className="shrink-0 px-3 pb-2">
|
||
<SidebarTooltip label={search.tooltip} enabled={collapsed}>
|
||
<button
|
||
type="button"
|
||
onClick={search.onClick}
|
||
aria-label={collapsed ? search.tooltip : undefined}
|
||
className={cn(
|
||
"flex h-9 w-full items-center gap-2 rounded-lg border border-white/[0.08] bg-white/[0.04] text-sm text-sidebar-muted shadow-[inset_0_1px_0_rgba(255,255,255,0.03)] transition-colors hover:border-white/[0.12] hover:bg-white/[0.07] hover:text-sidebar-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-primary/60",
|
||
collapsed ? "justify-center" : "px-3",
|
||
)}
|
||
>
|
||
<SearchItemIcon className="size-4 shrink-0" />
|
||
{!collapsed && (
|
||
<>
|
||
<span className="truncate">{search.label}</span>
|
||
{search.shortcut && (
|
||
<Kbd className="ml-auto border border-white/[0.06] bg-white/[0.08] text-[10px] text-sidebar-foreground shadow-none">
|
||
{search.shortcut}
|
||
</Kbd>
|
||
)}
|
||
</>
|
||
)}
|
||
</button>
|
||
</SidebarTooltip>
|
||
</div>
|
||
)}
|
||
|
||
<ScrollArea className="min-h-0 flex-1 [&_[data-slot=scroll-area-thumb]]:bg-white/15 [&_[data-slot=scroll-area-thumb]]:group-hover/bar:bg-white/30">
|
||
<nav className={cn("px-3 py-3", collapsed ? "space-y-2" : "space-y-3.5")}>
|
||
{groups.map((group) => (
|
||
<div key={group.label} className="group/nav">
|
||
{collapsed ? (
|
||
<div className="mx-auto mb-2 h-px w-7 bg-sidebar-border/90 group-first/nav:hidden" />
|
||
) : (
|
||
<div className="mb-1.5 flex items-center gap-2 px-3">
|
||
<span className="text-[10px] leading-4 font-semibold tracking-[0.11em] text-sidebar-muted uppercase">
|
||
{group.label}
|
||
</span>
|
||
</div>
|
||
)}
|
||
<ul className="space-y-0.5">
|
||
{group.items.map((item) => (
|
||
<li key={item.to}>
|
||
<SidebarLink item={item} collapsed={collapsed} />
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</div>
|
||
))}
|
||
</nav>
|
||
</ScrollArea>
|
||
|
||
<div className="shrink-0 border-t border-sidebar-border bg-black/[0.04] px-3 py-2.5 shadow-[0_-8px_20px_rgba(0,0,0,0.06)]">
|
||
<div className={cn("flex items-center gap-1", collapsed && "flex-col")}>
|
||
{user ? <UserMenu user={user} collapsed={collapsed} menu={userMenu} /> : <div className="flex-1" />}
|
||
<SidebarIconButton label={collapsed ? "Развернуть меню" : "Свернуть меню"} onClick={onToggle}>
|
||
{collapsed ? <PanelLeftOpenIcon /> : <PanelLeftCloseIcon />}
|
||
</SidebarIconButton>
|
||
</div>
|
||
</div>
|
||
</aside>
|
||
)
|
||
}
|
||
|
||
function SidebarTooltip({ label, enabled, children }: { label: string; enabled: boolean; children: React.ReactElement }) {
|
||
if (!enabled) return children
|
||
return (
|
||
<Tooltip>
|
||
<TooltipTrigger asChild>{children}</TooltipTrigger>
|
||
<TooltipContent side="right">{label}</TooltipContent>
|
||
</Tooltip>
|
||
)
|
||
}
|
||
|
||
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 (
|
||
<SidebarTooltip label={`${item.label} · скоро`} enabled={collapsed}>
|
||
<span className={cn(base, "cursor-not-allowed opacity-40")}>
|
||
<Icon className="size-[18px] shrink-0" />
|
||
{!collapsed && item.label}
|
||
</span>
|
||
</SidebarTooltip>
|
||
)
|
||
}
|
||
|
||
return (
|
||
<>
|
||
<SidebarTooltip label={label} enabled={collapsed}>
|
||
<ShellLink
|
||
href={item.to}
|
||
aria-label={collapsed ? label : undefined}
|
||
aria-current={active ? "page" : undefined}
|
||
className={cn(
|
||
base,
|
||
"group/link",
|
||
active
|
||
? "bg-sidebar-accent text-white ring-1 ring-inset ring-white/[0.05]"
|
||
: "text-sidebar-foreground/80 hover:bg-white/[0.05] hover:text-white",
|
||
)}
|
||
>
|
||
{active && <span className="absolute top-1.5 bottom-1.5 left-0 w-[3px] rounded-r-full bg-sidebar-primary" />}
|
||
{/* При наведении иконка окрашивается и чуть увеличивается (без анимации, если в системе «уменьшить движение»). */}
|
||
<Icon
|
||
className={cn(
|
||
"size-[18px] shrink-0 transition-colors group-hover/link:text-sidebar-primary motion-safe:group-hover/link:animate-nav-icon",
|
||
active && "text-sidebar-primary",
|
||
)}
|
||
/>
|
||
{!collapsed && <span className="truncate">{item.label}</span>}
|
||
{count > 0 ? (
|
||
<span
|
||
className={cn(
|
||
"grid place-items-center rounded-full font-semibold tabular-nums",
|
||
item.badgeTone === "warning" ? "bg-warning text-sidebar" : "bg-coral text-white",
|
||
collapsed
|
||
? "absolute top-0.5 right-1 min-w-4 px-1 text-3xs leading-4 ring-2 ring-sidebar"
|
||
: "ml-auto min-w-5 px-1.5 text-2xs leading-5 ring-1 ring-white/10",
|
||
)}
|
||
>
|
||
{count > 999 ? "999+" : count}
|
||
</span>
|
||
) : tabs.length > 0 ? (
|
||
collapsed ? (
|
||
<span className="absolute top-1 right-1.5 size-2 rounded-full bg-sidebar-primary ring-2 ring-sidebar" />
|
||
) : (
|
||
<span className="ml-auto rounded-md bg-white/10 px-1.5 text-2xs leading-5 font-semibold text-sidebar-foreground">
|
||
{tabs.length}
|
||
</span>
|
||
)
|
||
) : null}
|
||
</ShellLink>
|
||
</SidebarTooltip>
|
||
|
||
{/* Открытые карточки раздела — «зеркало» вкладок прямо в меню */}
|
||
{!collapsed && tabs.length > 0 && (
|
||
<ul className="mt-0.5 ml-[21px] space-y-px border-l border-sidebar-border/80 py-0.5 pl-2.5">
|
||
{visible.map((tab) => {
|
||
const here = isHere(tab)
|
||
return (
|
||
<li
|
||
key={tab.id}
|
||
className={cn(
|
||
"group/item flex h-7.5 items-center rounded-md text-sm transition-colors",
|
||
here
|
||
? "bg-white/[0.07] text-white ring-1 ring-inset ring-white/[0.04]"
|
||
: "text-sidebar-muted hover:bg-white/[0.04] hover:text-sidebar-foreground",
|
||
)}
|
||
>
|
||
<button
|
||
type="button"
|
||
onClick={() => navigate(tab.href)}
|
||
title={tab.alert ? `${tab.label} · ${tab.alert}` : tab.label}
|
||
className="flex h-full min-w-0 flex-1 items-center gap-2 pl-2 text-left outline-none focus-visible:text-white"
|
||
>
|
||
<span className={cn("size-1.5 shrink-0 rounded-full", toneDot(tab.tone, "bg-sidebar-muted"))} />
|
||
<span className="truncate">{tab.label}</span>
|
||
</button>
|
||
<span className="relative grid size-6 shrink-0 place-items-center">
|
||
{tab.alert && (
|
||
<span title={tab.alert} className="size-1.5 rounded-full bg-coral transition-opacity group-hover/item:opacity-0" />
|
||
)}
|
||
<button
|
||
type="button"
|
||
aria-label={`Закрыть ${tab.label}`}
|
||
onClick={() => closeTab(item.tabsSection!, tab.id)}
|
||
className="absolute inset-0.5 grid place-items-center rounded text-sidebar-muted opacity-0 transition group-hover/item:opacity-100 hover:bg-white/10 hover:text-white focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-sidebar-primary/60"
|
||
>
|
||
<XIcon className="size-3.5" />
|
||
</button>
|
||
</span>
|
||
</li>
|
||
)
|
||
})}
|
||
{hidden.length > 0 && (
|
||
<li>
|
||
<DropdownMenu>
|
||
<DropdownMenuTrigger asChild>
|
||
<button
|
||
type="button"
|
||
className="flex h-7 w-full items-center gap-1.5 rounded-md px-2 text-2xs text-sidebar-muted transition hover:bg-white/[0.04] hover:text-sidebar-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-sidebar-primary/60 data-[state=open]:bg-white/[0.04] data-[state=open]:text-sidebar-foreground"
|
||
>
|
||
ещё {hidden.length}
|
||
{hidden.some((t) => t.alert) && <span className="size-1.5 rounded-full bg-coral" />}
|
||
<ChevronRightIcon className="ml-auto size-3" />
|
||
</button>
|
||
</DropdownMenuTrigger>
|
||
<DropdownMenuContent side="right" align="start" className="w-60">
|
||
<DropdownMenuLabel className="text-xs text-muted-foreground">Ещё открыто</DropdownMenuLabel>
|
||
{hidden.map((tab) => (
|
||
<DropdownMenuItem key={tab.id} onSelect={() => navigate(tab.href)} className="group/item gap-2 pr-1">
|
||
<span className={cn("size-1.5 shrink-0 rounded-full", toneDot(tab.tone, "bg-muted-foreground"))} />
|
||
<span className="min-w-0 flex-1 truncate">{tab.label}</span>
|
||
{tab.alert && <span title={tab.alert} className="size-1.5 rounded-full bg-coral" />}
|
||
<button
|
||
type="button"
|
||
aria-label={`Закрыть ${tab.label}`}
|
||
// Только click: pointerdown должен дойти до пункта меню, иначе Radix на pointerup
|
||
// «докликивает» пункт сам и открывает карточку вместо закрытия.
|
||
onClick={(e) => {
|
||
e.preventDefault()
|
||
e.stopPropagation()
|
||
closeTab(item.tabsSection!, tab.id)
|
||
}}
|
||
className="grid size-6 place-items-center rounded-md text-muted-foreground opacity-0 transition group-hover/item:opacity-100 group-data-[highlighted]/item:opacity-100 hover:bg-foreground/10 hover:text-foreground"
|
||
>
|
||
<XIcon className="size-3.5" />
|
||
</button>
|
||
</DropdownMenuItem>
|
||
))}
|
||
</DropdownMenuContent>
|
||
</DropdownMenu>
|
||
</li>
|
||
)}
|
||
</ul>
|
||
)}
|
||
</>
|
||
)
|
||
}
|
||
|
||
function UserMenu({ user, collapsed, menu }: { user: SidebarUser; collapsed: boolean; menu?: React.ReactNode }) {
|
||
const trigger = (
|
||
<button
|
||
type="button"
|
||
aria-label={collapsed ? user.name : undefined}
|
||
className={cn(
|
||
"flex min-w-0 items-center gap-2.5 rounded-lg text-left transition-colors hover:bg-white/[0.06] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-primary/60",
|
||
collapsed ? "size-9 justify-center p-0" : "flex-1 p-1.5",
|
||
)}
|
||
>
|
||
<Avatar className="size-8 rounded-lg">
|
||
<AvatarFallback className="rounded-lg bg-sidebar-primary/20 text-xs font-semibold text-sidebar-primary">
|
||
{user.initials}
|
||
</AvatarFallback>
|
||
</Avatar>
|
||
{!collapsed && (
|
||
<div className="min-w-0 flex-1 leading-tight">
|
||
<div className="truncate text-sm font-semibold text-white">{user.name}</div>
|
||
{user.subtitle && <div className="truncate text-xs text-sidebar-muted">{user.subtitle}</div>}
|
||
</div>
|
||
)}
|
||
</button>
|
||
)
|
||
if (!menu) return trigger
|
||
|
||
return (
|
||
<DropdownMenu>
|
||
<DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger>
|
||
<DropdownMenuContent side="right" align="end" className="w-64">
|
||
{menu}
|
||
</DropdownMenuContent>
|
||
</DropdownMenu>
|
||
)
|
||
}
|
||
|
||
function SidebarIconButton({ label, onClick, children }: { label: string; onClick: () => void; children: React.ReactNode }) {
|
||
return (
|
||
<Tooltip>
|
||
<TooltipTrigger asChild>
|
||
<button
|
||
type="button"
|
||
aria-label={label}
|
||
onClick={onClick}
|
||
className="grid size-8 shrink-0 place-items-center rounded-lg text-sidebar-muted transition-colors hover:bg-white/[0.07] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-primary/60 [&_svg]:size-4"
|
||
>
|
||
{children}
|
||
</button>
|
||
</TooltipTrigger>
|
||
<TooltipContent side="right">{label}</TooltipContent>
|
||
</Tooltip>
|
||
)
|
||
}
|