import * as React from "react" import { ChevronDownIcon, XIcon, type LucideIcon } from "lucide-react" import { cn } from "../lib/utils" import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from "../ui/context-menu" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger, } from "../ui/dropdown-menu" import { Kbd } from "../ui/kbd" import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip" export type PageTabTone = "male" | "female" | "neutral" export interface PageTabItem { readonly id: string readonly label: string /** Иконка вместо буквы (обычно у корневой вкладки-списка). */ readonly icon?: LucideIcon readonly letter?: string readonly tone?: PageTabTone /** Красная точка и её причина — показывается в подсказке («Аллергия на пенициллин», «Новые ответы: 2»). */ readonly alert?: string /** Нельзя закрыть и перетащить. */ readonly pinned?: boolean } const toneClass: Record = { male: "bg-male/15 text-male", female: "bg-female/15 text-female", neutral: "bg-muted text-muted-foreground", } /** Сколько открытых карточек показывать максимум — в шапке раздела и в меню слева. */ export const MAX_VISIBLE_TABS = 4 const CHIP_CLASS = "group/tab relative flex h-8 max-w-56 shrink-0 cursor-pointer items-center gap-2 rounded-lg px-2.5 text-sm font-medium outline-none select-none" const MORE_CLASS = "flex h-8 shrink-0 items-center gap-1 rounded-lg px-2.5 text-sm font-medium text-muted-foreground transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 data-[state=open]:bg-muted data-[state=open]:text-foreground" // Должны совпадать с разметкой: gap-1 между чипами, разделитель mx-1 w-px после закреплённых. const GAP = 4 const SEPARATOR = 9 /** * Разделить вкладки на видимые и «ещё»: закреплённые видны всегда и в лимит не входят, * из остальных — первые `max`. Активная всегда на виду: если она дальше, занимает последнее место. */ export function splitTabs( tabs: readonly T[], activeId: string | null | undefined, max = MAX_VISIBLE_TABS, ): { visible: T[]; hidden: T[] } { const rest = tabs.filter((t) => !t.pinned) if (rest.length <= max) return { visible: [...tabs], hidden: [] } let shown = rest.slice(0, max) const active = rest.find((t) => t.id === activeId) if (active && !shown.includes(active)) shown = [...shown.slice(0, max - 1), active] const ids = new Set(shown.map((t) => t.id)) return { visible: tabs.filter((t) => t.pinned || ids.has(t.id)), hidden: rest.filter((t) => !ids.has(t.id)), } } /** * Вкладки страницы — чипы в шапке раздела: иконка или буква, цвет пола, * закрытие (крестик / средняя кнопка), перетаскивание, контекстное меню. * Карточек видно столько, сколько влезает по ширине, но не больше `maxVisible`; остальные — в меню «ещё N». * Чисто презентационный: состояние и навигация — снаружи. */ export function PageTabs({ tabs, activeId, onSelect, onClose, onMove, renderMenu, actions, hotkeyHints = false, maxVisible = MAX_VISIBLE_TABS, className, }: { tabs: readonly PageTabItem[] activeId: string | null onSelect: (id: string) => void onClose?: (id: string) => void onMove?: (fromId: string, toId: string) => void /** Содержимое контекстного меню вкладки (пункты ContextMenuItem). */ renderMenu?: (tab: PageTabItem) => React.ReactNode actions?: React.ReactNode /** Показывать в подсказке Alt+N. */ hotkeyHints?: boolean /** Сколько незакреплённых вкладок показывать максимум, даже если места больше. */ maxVisible?: number className?: string }) { const [dragId, setDragId] = React.useState(null) const scrollerRef = React.useRef(null) const measureRef = React.useRef(null) const [fit, setFit] = React.useState(maxVisible) const { visible, hidden } = splitTabs(tabs, activeId, fit) const hiddenTotal = tabs.filter((t) => !t.pinned).length // Сколько карточек влезает: ширины берём из невидимого ряда-двойника, пересчёт — при любом изменении ширины. React.useLayoutEffect(() => { const scroller = scrollerRef.current const measure = measureRef.current if (!scroller || !measure) return const compute = () => { const width = new Map() for (const el of measure.querySelectorAll("[data-measure-id]")) { width.set(el.dataset.measureId!, el.getBoundingClientRect().width) } const moreWidth = measure.querySelector("[data-measure-more]")?.getBoundingClientRect().width ?? 0 // Небольшой запас: у «ещё N» в жизни другая цифра и точка тревоги — ширина гуляет на пару пикселей. const available = scroller.clientWidth - 6 const total = (n: number) => { const split = splitTabs(tabs, activeId, n) const items = split.visible.map((t) => width.get(t.id) ?? 0) const separators = split.visible.filter((t, i) => t.pinned && i < split.visible.length - 1).length const count = items.length + separators + (split.hidden.length ? 1 : 0) return ( items.reduce((a, b) => a + b, 0) + separators * SEPARATOR + (split.hidden.length ? moreWidth : 0) + GAP * (count - 1) ) } let n = Math.min(maxVisible, tabs.filter((t) => !t.pinned).length) // Активная видна всегда, поэтому меньше одной не опускаемся. while (n > 1 && total(n) > available) n-- setFit(n) } compute() const observer = new ResizeObserver(compute) observer.observe(scroller) return () => observer.disconnect() }, [tabs, activeId, maxVisible]) // Активная вкладка всегда видна, даже если их много. React.useEffect(() => { scrollerRef.current ?.querySelector('[data-active="true"]') ?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" }) }, [activeId, tabs.length]) return (
{/* Невидимый двойник ряда — только чтобы померить ширину каждой карточки */}
{tabs.map((tab) => (
))} ещё {hiddenTotal}
{visible.map((tab, i) => { // Номер для Alt+N — по полному списку, а не по видимым. const index = tabs.indexOf(tab) const active = tab.id === activeId const closable = Boolean(onClose) && !tab.pinned const chip = (
onSelect(tab.id)} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault() onSelect(tab.id) } }} onAuxClick={(e) => { if (e.button === 1 && closable) { e.preventDefault() onClose?.(tab.id) } }} onMouseDown={(e) => e.button === 1 && e.preventDefault()} onDragStart={(e) => { setDragId(tab.id) e.dataTransfer.effectAllowed = "move" }} onDragOver={(e) => { if (onMove && dragId && dragId !== tab.id && !tab.pinned) { e.preventDefault() onMove(dragId, tab.id) } }} onDragEnd={() => setDragId(null)} className={cn( CHIP_CLASS, "transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-ring/60", active ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-muted hover:text-foreground", dragId === tab.id && "opacity-50", )} > onClose?.(tab.id)} hotkey={hotkeyHints && index < 8 ? `Alt ${index + 1}` : undefined} />
) return ( {renderMenu ? ( {chip} {renderMenu(tab)} ) : ( chip )} {tab.pinned && i < visible.length - 1 && } ) })} {hidden.length > 0 && }
{actions &&
{actions}
}
) } /** Содержимое чипа: иконка или буква, подпись, крестик. Общее для настоящего ряда и для замера ширины. */ function TabFace({ tab, active, closable, onClose, hotkey, }: { tab: PageTabItem active: boolean closable: boolean /** Без него — замер: крестик рисуется пустышкой той же ширины. */ onClose?: () => void hotkey?: string }) { return ( <> {tab.icon ? ( ) : ( {tab.letter ?? tab.label[0]} {tab.alert && } )} {onClose ? ( {tab.label}
{tab.label} {hotkey && {hotkey}}
{tab.alert && (
{tab.alert}
)}
) : ( {tab.label} )} {closable && (onClose ? ( ) : ( ))} ) } /** Кнопка «ещё N» со списком скрытых вкладок: открыть или закрыть, не открывая. */ function OverflowTabs({ tabs, onSelect, onClose, }: { tabs: readonly PageTabItem[] onSelect: (id: string) => void onClose?: (id: string) => void }) { return ( Ещё открыто {tabs.map((tab) => ( onSelect(tab.id)} className="group/item gap-2.5 pr-1"> {tab.icon ? ( ) : ( {tab.letter ?? tab.label[0]} {tab.alert && } )} {tab.label} {onClose && !tab.pinned && ( )} ))} ) }