medkit/src/kit/page-tabs.tsx

386 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 { 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<PageTabTone, string> = {
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<T extends { readonly id: string; readonly pinned?: boolean }>(
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<string | null>(null)
const scrollerRef = React.useRef<HTMLDivElement>(null)
const measureRef = React.useRef<HTMLDivElement>(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<string, number>()
for (const el of measure.querySelectorAll<HTMLElement>("[data-measure-id]")) {
width.set(el.dataset.measureId!, el.getBoundingClientRect().width)
}
const moreWidth = measure.querySelector<HTMLElement>("[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<HTMLElement>('[data-active="true"]')
?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" })
}, [activeId, tabs.length])
return (
<div className={cn("relative flex h-12 shrink-0 items-center gap-2 border-b px-2", className)}>
{/* Невидимый двойник ряда — только чтобы померить ширину каждой карточки */}
<div
ref={measureRef}
aria-hidden
className="pointer-events-none invisible absolute top-0 left-0 flex h-0 gap-1 overflow-hidden"
>
{tabs.map((tab) => (
<div key={tab.id} data-measure-id={tab.id} className={CHIP_CLASS}>
<TabFace tab={tab} active={false} closable={Boolean(onClose) && !tab.pinned} />
</div>
))}
<span data-measure-more className={MORE_CLASS}>
ещё {hiddenTotal}
<span className="size-1.5 rounded-full" />
<ChevronDownIcon className="size-3.5" />
</span>
</div>
<div
ref={scrollerRef}
role="tablist"
aria-label="Вкладки"
className="scrollbar-none flex min-w-0 flex-1 items-center gap-1 overflow-x-auto"
>
{visible.map((tab, i) => {
// Номер для Alt+N — по полному списку, а не по видимым.
const index = tabs.indexOf(tab)
const active = tab.id === activeId
const closable = Boolean(onClose) && !tab.pinned
const chip = (
<div
role="tab"
tabIndex={0}
aria-selected={active}
data-active={active}
draggable={Boolean(onMove) && !tab.pinned}
onClick={() => 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",
)}
>
<TabFace
tab={tab}
active={active}
closable={closable}
onClose={() => onClose?.(tab.id)}
hotkey={hotkeyHints && index < 8 ? `Alt ${index + 1}` : undefined}
/>
</div>
)
return (
<React.Fragment key={tab.id}>
{renderMenu ? (
<ContextMenu>
<ContextMenuTrigger asChild>{chip}</ContextMenuTrigger>
<ContextMenuContent className="w-56">{renderMenu(tab)}</ContextMenuContent>
</ContextMenu>
) : (
chip
)}
{tab.pinned && i < visible.length - 1 && <span className="mx-1 h-5 w-px shrink-0 bg-border" />}
</React.Fragment>
)
})}
{hidden.length > 0 && <OverflowTabs tabs={hidden} onSelect={onSelect} onClose={onClose} />}
</div>
{actions && <div className="flex shrink-0 items-center gap-1">{actions}</div>}
</div>
)
}
/** Содержимое чипа: иконка или буква, подпись, крестик. Общее для настоящего ряда и для замера ширины. */
function TabFace({
tab,
active,
closable,
onClose,
hotkey,
}: {
tab: PageTabItem
active: boolean
closable: boolean
/** Без него — замер: крестик рисуется пустышкой той же ширины. */
onClose?: () => void
hotkey?: string
}) {
return (
<>
{tab.icon ? (
<tab.icon className={cn("size-4", active && "text-primary")} />
) : (
<span
className={cn(
"relative grid size-5 shrink-0 place-items-center rounded-md text-2xs font-semibold",
toneClass[tab.tone ?? "neutral"],
)}
>
{tab.letter ?? tab.label[0]}
{tab.alert && <span title={tab.alert} className="absolute -top-0.5 -right-0.5 size-2 rounded-full bg-coral ring-2 ring-card" />}
</span>
)}
{onClose ? (
<Tooltip delayDuration={600}>
<TooltipTrigger asChild>
<span className="truncate">{tab.label}</span>
</TooltipTrigger>
<TooltipContent side="bottom">
<div className="flex items-center gap-2">
{tab.label}
{hotkey && <Kbd>{hotkey}</Kbd>}
</div>
{tab.alert && (
<div className="mt-1 flex items-center gap-1.5 opacity-80">
<span className="size-1.5 rounded-full bg-coral" />
{tab.alert}
</div>
)}
</TooltipContent>
</Tooltip>
) : (
<span className="truncate">{tab.label}</span>
)}
{closable &&
(onClose ? (
<button
type="button"
aria-label={`Закрыть вкладку ${tab.label}`}
onClick={(e) => {
e.stopPropagation()
onClose()
}}
className={cn(
"-mr-1 grid size-5 shrink-0 place-items-center rounded-md text-current/60 transition hover:bg-foreground/10 hover:text-current",
active ? "opacity-100" : "opacity-0 group-hover/tab:opacity-100 focus-visible:opacity-100",
)}
>
<XIcon className="size-3.5" />
</button>
) : (
<span className="-mr-1 size-5 shrink-0" />
))}
</>
)
}
/** Кнопка «ещё N» со списком скрытых вкладок: открыть или закрыть, не открывая. */
function OverflowTabs({
tabs,
onSelect,
onClose,
}: {
tabs: readonly PageTabItem[]
onSelect: (id: string) => void
onClose?: (id: string) => void
}) {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className={MORE_CLASS}
>
ещё {tabs.length}
{tabs.some((t) => t.alert) && <span className="size-1.5 rounded-full bg-coral" />}
<ChevronDownIcon className="size-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-64">
<DropdownMenuLabel className="text-xs text-muted-foreground">Ещё открыто</DropdownMenuLabel>
{tabs.map((tab) => (
<DropdownMenuItem key={tab.id} onSelect={() => onSelect(tab.id)} className="group/item gap-2.5 pr-1">
{tab.icon ? (
<tab.icon />
) : (
<span
className={cn(
"relative grid size-5 shrink-0 place-items-center rounded-md text-2xs font-semibold",
toneClass[tab.tone ?? "neutral"],
)}
>
{tab.letter ?? tab.label[0]}
{tab.alert && <span title={tab.alert} className="absolute -top-0.5 -right-0.5 size-2 rounded-full bg-coral ring-2 ring-popover" />}
</span>
)}
<span className="min-w-0 flex-1 truncate">{tab.label}</span>
{onClose && !tab.pinned && (
<button
type="button"
aria-label={`Закрыть вкладку ${tab.label}`}
// Только click: pointerdown должен дойти до пункта меню, иначе Radix на pointerup
// «докликивает» пункт сам и открывает карточку вместо закрытия.
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
onClose(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>
)
}