medkit/src/kit/filter-tabs.tsx

143 lines
5.2 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 { type LucideIcon } from "lucide-react"
import { cn } from "../lib/utils"
import { StatusDot, type StatusTone } from "./status-badge"
export interface FilterTabItem<T extends string = string> {
readonly id: T
readonly label: string
readonly icon?: LucideIcon
/** Счётчик справа от подписи; вариант с нулём приглушён. */
readonly count?: number
/** Цветная точка статуса; с `highlight` — ещё и цвет выбранного варианта. */
readonly tone?: StatusTone
readonly disabled?: boolean
}
// Подсветка выбранного варианта цветом его статуса.
const highlightClass: Record<StatusTone, string> = {
positive: "bg-success-soft text-success ring-success/25",
info: "bg-info-soft text-info ring-info/25",
warning: "bg-warning-soft text-warning ring-warning/30",
negative: "bg-coral-soft text-coral ring-coral/25",
neutral: "bg-card text-foreground ring-border",
}
/**
* Вкладки-фильтры с множественным выбором — как `ContentTabs variant="pill"`, но можно
* включить несколько вариантов сразу (статусы, типы). Пустой `value` — «Все»:
* первая кнопка `allLabel` выбрана, когда ничего не выбрано, и сбрасывает выбор;
* выбрать все варианты по одному — то же, что «Все».
* `highlight` — выбранные варианты подсвечиваются цветом своего `tone`.
*/
export function FilterTabs<T extends string>({
items,
value,
onValueChange,
allLabel = "Все",
allCount,
highlight = false,
className,
}: {
items: readonly FilterTabItem<T>[]
value: readonly T[]
onValueChange: (value: T[]) => void
/** Подпись кнопки «Все»; `false` — без неё. */
allLabel?: string | false
/** Счётчик на «Все»; по умолчанию — сумма счётчиков вариантов. */
allCount?: number
/** Подсвечивать выбранные варианты цветом статуса. */
highlight?: boolean
className?: string
}) {
const selected = new Set(value)
const total = allCount ?? (items.every((i) => i.count !== undefined) ? items.reduce((s, i) => s + (i.count ?? 0), 0) : undefined)
const toggle = (id: T) => {
const next = selected.has(id) ? value.filter((v) => v !== id) : [...value, id]
// Порядок — как у кнопок, а не как нажимали: адрес и сравнение с умолчанием стабильны.
const ordered = items.map((i) => i.id).filter((i) => next.includes(i))
// Выбраны все варианты — это и есть «Все».
onValueChange(allLabel !== false && ordered.length === items.length ? [] : ordered)
}
return (
<div
role="group"
className={cn(
// Не влезают в строку — переносятся внутри той же подложки, а не обрезаются.
"flex w-fit max-w-full flex-wrap items-center gap-1 rounded-xl bg-muted/70 p-1",
className,
)}
>
{allLabel !== false && (
<FilterTabButton active={selected.size === 0} count={total} onClick={() => onValueChange([])}>
{allLabel}
</FilterTabButton>
)}
{items.map((item) => (
<FilterTabButton
key={item.id}
active={selected.has(item.id)}
count={item.count}
tone={highlight ? item.tone : undefined}
disabled={item.disabled}
onClick={() => toggle(item.id)}
>
{item.icon && <item.icon className="size-4" />}
{item.tone && <StatusDot tone={item.tone} />}
{item.label}
</FilterTabButton>
))}
</div>
)
}
function FilterTabButton({
active,
count,
tone,
disabled,
onClick,
children,
}: {
active: boolean
count?: number
/** Тон подсветки выбранной кнопки. */
tone?: StatusTone
disabled?: boolean
onClick: () => void
children: React.ReactNode
}) {
return (
<button
type="button"
aria-pressed={active}
disabled={disabled}
onClick={onClick}
className={cn(
"flex h-8 shrink-0 items-center gap-2 rounded-lg px-3 text-sm font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-40",
active
? tone
? cn("shadow-xs ring-1 ring-inset", highlightClass[tone])
: "bg-card text-foreground shadow-xs"
: "text-muted-foreground hover:text-foreground",
count === 0 && !active && "opacity-60",
)}
>
{children}
{count !== undefined && (
<span
className={cn(
"rounded-md px-1.5 text-2xs leading-5 font-semibold tabular",
!active ? "bg-muted text-muted-foreground" : tone ? "bg-card/70" : "bg-primary/10 text-primary",
)}
>
{count}
</span>
)}
</button>
)
}