medkit/src/kit/app-sidebar.tsx

384 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 bg-sidebar text-sidebar-foreground transition-[width] duration-200 print:hidden",
collapsed ? "w-[60px]" : "w-56",
className,
)}
>
<div className={cn("flex h-14 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-1">
<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-sidebar-border bg-white/[0.03] text-sm text-sidebar-muted transition hover:bg-white/[0.06] hover:text-sidebar-foreground",
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-0 bg-white/10 text-sidebar-foreground">{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-2", collapsed ? "space-y-1.5" : "space-y-4")}>
{groups.map((group) => (
<div key={group.label} className="group/nav">
{collapsed ? (
<div className="mx-auto mb-1.5 h-px w-6 bg-sidebar-border group-first/nav:hidden" />
) : (
<div className="mb-1 px-3 text-3xs font-semibold tracking-[0.14em] text-sidebar-muted uppercase">
{group.label}
</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 p-3">
<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-9 items-center rounded-lg text-sm font-medium transition-colors",
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,
active ? "bg-sidebar-accent text-white" : "text-sidebar-foreground/85 hover:bg-white/[0.04] hover:text-white",
)}
>
{active && <span className="absolute top-2 bottom-2 left-0 w-[3px] rounded-r-full bg-sidebar-primary" />}
<Icon className={cn("size-[18px] shrink-0", 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",
)}
>
{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 py-1 pl-2">
{visible.map((tab) => {
const here = isHere(tab)
return (
<li
key={tab.id}
className={cn(
"group/item flex h-7 items-center rounded-md text-sm transition-colors",
here ? "bg-white/[0.06] text-white" : "text-sidebar-muted hover:bg-white/[0.03] 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"
>
<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"
>
<XIcon className="size-3.5" />
</button>
</span>
</li>
)
})}
{hidden.length > 0 && (
<li>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="flex h-6 w-full items-center gap-1.5 rounded-md px-2 text-2xs text-sidebar-muted transition hover:bg-white/[0.03] hover:text-sidebar-foreground 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 p-1.5 text-left transition hover:bg-white/[0.05]",
collapsed ? "justify-center" : "flex-1",
)}
>
<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 hover:bg-white/[0.06] hover:text-white [&_svg]:size-4"
>
{children}
</button>
</TooltipTrigger>
<TooltipContent side="right">{label}</TooltipContent>
</Tooltip>
)
}