Open cards: fit tabs to width (max 4) with an "ещё N" menu
PageTabs shows as many card tabs as fit the bar width, at most MAX_VISIBLE_TABS (4), measured from an invisible copy of the row and recomputed on resize. The rest go into an "ещё N" dropdown where a card can be opened or closed; the active card is always visible. The sidebar uses the same split: all cards when there are up to five, otherwise four plus "ещё N" with the same menu. The close button inside menu items stops only click, not pointerdown: otherwise Radix treats pointerup as an outside press and selects the item, opening the card instead of closing it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4fee19d057
commit
d7f7b3ecdb
|
|
@ -1,8 +1,15 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
import { XIcon, type LucideIcon } from "lucide-react"
|
import { ChevronDownIcon, XIcon, type LucideIcon } from "lucide-react"
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from "@/components/ui/context-menu"
|
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from "@/components/ui/context-menu"
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu"
|
||||||
import { Kbd } from "@/components/ui/kbd"
|
import { Kbd } from "@/components/ui/kbd"
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
|
||||||
|
|
||||||
|
|
@ -27,9 +34,42 @@ const toneClass: Record<PageTabTone, string> = {
|
||||||
neutral: "bg-muted text-muted-foreground",
|
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-[13px] font-medium outline-none select-none"
|
||||||
|
const MORE_CLASS =
|
||||||
|
"flex h-8 shrink-0 items-center gap-1 rounded-lg px-2.5 text-[13px] 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({
|
export function PageTabs({
|
||||||
|
|
@ -41,6 +81,7 @@ export function PageTabs({
|
||||||
renderMenu,
|
renderMenu,
|
||||||
actions,
|
actions,
|
||||||
hotkeyHints = false,
|
hotkeyHints = false,
|
||||||
|
maxVisible = MAX_VISIBLE_TABS,
|
||||||
className,
|
className,
|
||||||
}: {
|
}: {
|
||||||
tabs: readonly PageTabItem[]
|
tabs: readonly PageTabItem[]
|
||||||
|
|
@ -53,10 +94,49 @@ export function PageTabs({
|
||||||
actions?: React.ReactNode
|
actions?: React.ReactNode
|
||||||
/** Показывать в подсказке Alt+N. */
|
/** Показывать в подсказке Alt+N. */
|
||||||
hotkeyHints?: boolean
|
hotkeyHints?: boolean
|
||||||
|
/** Сколько незакреплённых вкладок показывать максимум, даже если места больше. */
|
||||||
|
maxVisible?: number
|
||||||
className?: string
|
className?: string
|
||||||
}) {
|
}) {
|
||||||
const [dragId, setDragId] = React.useState<string | null>(null)
|
const [dragId, setDragId] = React.useState<string | null>(null)
|
||||||
const scrollerRef = React.useRef<HTMLDivElement>(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(() => {
|
React.useEffect(() => {
|
||||||
|
|
@ -66,14 +146,33 @@ export function PageTabs({
|
||||||
}, [activeId, tabs.length])
|
}, [activeId, tabs.length])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn("flex h-12 shrink-0 items-center gap-2 border-b px-2", className)}>
|
<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
|
<div
|
||||||
ref={scrollerRef}
|
ref={scrollerRef}
|
||||||
role="tablist"
|
role="tablist"
|
||||||
aria-label="Вкладки"
|
aria-label="Вкладки"
|
||||||
className="scrollbar-none flex min-w-0 flex-1 items-center gap-1 overflow-x-auto"
|
className="scrollbar-none flex min-w-0 flex-1 items-center gap-1 overflow-x-auto"
|
||||||
>
|
>
|
||||||
{tabs.map((tab, index) => {
|
{visible.map((tab, i) => {
|
||||||
|
// Номер для Alt+N — по полному списку, а не по видимым.
|
||||||
|
const index = tabs.indexOf(tab)
|
||||||
const active = tab.id === activeId
|
const active = tab.id === activeId
|
||||||
const closable = Boolean(onClose) && !tab.pinned
|
const closable = Boolean(onClose) && !tab.pinned
|
||||||
const chip = (
|
const chip = (
|
||||||
|
|
@ -109,54 +208,19 @@ export function PageTabs({
|
||||||
}}
|
}}
|
||||||
onDragEnd={() => setDragId(null)}
|
onDragEnd={() => setDragId(null)}
|
||||||
className={cn(
|
className={cn(
|
||||||
"group/tab relative flex h-8 max-w-56 shrink-0 cursor-pointer items-center gap-2 rounded-lg px-2.5 text-[13px] font-medium outline-none select-none",
|
CHIP_CLASS,
|
||||||
"transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-ring/60",
|
"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",
|
active ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-muted hover:text-foreground",
|
||||||
dragId === tab.id && "opacity-50",
|
dragId === tab.id && "opacity-50",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{tab.icon ? (
|
<TabFace
|
||||||
<tab.icon className={cn("size-4", active && "text-primary")} />
|
tab={tab}
|
||||||
) : (
|
active={active}
|
||||||
<span
|
closable={closable}
|
||||||
className={cn(
|
onClose={() => onClose?.(tab.id)}
|
||||||
"relative grid size-5 shrink-0 place-items-center rounded-md text-[11px] font-semibold",
|
hotkey={hotkeyHints && index < 8 ? `Alt ${index + 1}` : undefined}
|
||||||
toneClass[tab.tone ?? "neutral"],
|
/>
|
||||||
)}
|
|
||||||
>
|
|
||||||
{tab.letter ?? tab.label[0]}
|
|
||||||
{tab.alert && (
|
|
||||||
<span className="absolute -top-0.5 -right-0.5 size-2 rounded-full bg-coral ring-2 ring-card" />
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Tooltip delayDuration={600}>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<span className="truncate">{tab.label}</span>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent side="bottom" className="flex items-center gap-2">
|
|
||||||
{tab.label}
|
|
||||||
{hotkeyHints && index < 8 && <Kbd>Alt {index + 1}</Kbd>}
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
|
|
||||||
{closable && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
aria-label={`Закрыть вкладку ${tab.label}`}
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation()
|
|
||||||
onClose?.(tab.id)
|
|
||||||
}}
|
|
||||||
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>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -170,12 +234,144 @@ export function PageTabs({
|
||||||
) : (
|
) : (
|
||||||
chip
|
chip
|
||||||
)}
|
)}
|
||||||
{tab.pinned && index < tabs.length - 1 && <span className="mx-1 h-5 w-px shrink-0 bg-border" />}
|
{tab.pinned && i < visible.length - 1 && <span className="mx-1 h-5 w-px shrink-0 bg-border" />}
|
||||||
</React.Fragment>
|
</React.Fragment>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
|
{hidden.length > 0 && <OverflowTabs tabs={hidden} onSelect={onSelect} onClose={onClose} />}
|
||||||
</div>
|
</div>
|
||||||
{actions && <div className="flex shrink-0 items-center gap-1">{actions}</div>}
|
{actions && <div className="flex shrink-0 items-center gap-1">{actions}</div>}
|
||||||
</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-[11px] font-semibold",
|
||||||
|
toneClass[tab.tone ?? "neutral"],
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{tab.letter ?? tab.label[0]}
|
||||||
|
{tab.alert && <span 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" className="flex items-center gap-2">
|
||||||
|
{tab.label}
|
||||||
|
{hotkey && <Kbd>{hotkey}</Kbd>}
|
||||||
|
</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-[11px] font-semibold",
|
||||||
|
toneClass[tab.tone ?? "neutral"],
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{tab.letter ?? tab.label[0]}
|
||||||
|
{tab.alert && <span 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue