142 lines
5.1 KiB
TypeScript
142 lines
5.1 KiB
TypeScript
import * as React from "react"
|
||
import { ArrowDownIcon, ArrowUpIcon, ChevronsUpDownIcon } from "lucide-react"
|
||
|
||
import { cn } from "../lib/utils"
|
||
|
||
export type SortDirection = "asc" | "desc"
|
||
|
||
export interface SortState {
|
||
readonly id: string
|
||
readonly direction: SortDirection
|
||
}
|
||
|
||
export interface DataColumn<T> {
|
||
readonly id: string
|
||
readonly header: React.ReactNode
|
||
readonly cell: (row: T, index: number) => React.ReactNode
|
||
/** Компаратор — колонка становится сортируемой. */
|
||
readonly sort?: (a: T, b: T) => number
|
||
readonly className?: string
|
||
readonly headerClassName?: string
|
||
}
|
||
|
||
/** Отсортировать строки по словарю компараторов {columnId: compare}. */
|
||
export function sortBy<T>(
|
||
rows: readonly T[],
|
||
comparators: Readonly<Record<string, ((a: T, b: T) => number) | undefined>>,
|
||
sort: SortState | null,
|
||
) {
|
||
const compare = sort && comparators[sort.id]
|
||
if (!sort || !compare) return [...rows]
|
||
const dir = sort.direction === "asc" ? 1 : -1
|
||
return [...rows].sort((a, b) => dir * compare(a, b))
|
||
}
|
||
|
||
/** Отсортировать строки по колонкам таблицы (для пагинации снаружи). */
|
||
export function sortRows<T>(rows: readonly T[], columns: readonly DataColumn<T>[], sort: SortState | null) {
|
||
return sortBy(rows, Object.fromEntries(columns.map((c) => [c.id, c.sort])), sort)
|
||
}
|
||
|
||
/** Клик по заголовку: по возрастанию → по убыванию → без сортировки. */
|
||
export function nextSort(current: SortState | null, id: string): SortState | null {
|
||
if (current?.id !== id) return { id, direction: "asc" }
|
||
if (current.direction === "asc") return { id, direction: "desc" }
|
||
return null
|
||
}
|
||
|
||
/**
|
||
* Таблица кита: липкая шапка, сортировка по клику на заголовок,
|
||
* кликабельные строки. Строки передаются уже отсортированными/порезанными
|
||
* (см. sortRows) — так таблица одинаково работает с пагинацией и без неё.
|
||
*/
|
||
export function DataTable<T>({
|
||
columns,
|
||
rows,
|
||
getRowId,
|
||
sort,
|
||
onSortChange,
|
||
onRowClick,
|
||
rowProps,
|
||
rowClassName,
|
||
empty,
|
||
className,
|
||
}: {
|
||
columns: readonly DataColumn<T>[]
|
||
rows: readonly T[]
|
||
getRowId: (row: T) => React.Key
|
||
sort?: SortState | null
|
||
onSortChange?: (sort: SortState | null) => void
|
||
onRowClick?: (row: T, event: React.MouseEvent) => void
|
||
rowProps?: (row: T, index: number) => React.HTMLAttributes<HTMLTableRowElement>
|
||
rowClassName?: (row: T, index: number) => string | false | undefined
|
||
empty?: React.ReactNode
|
||
className?: string
|
||
}) {
|
||
return (
|
||
<table className={cn("w-full text-sm", className)}>
|
||
<thead className="sticky top-0 z-10 border-b bg-card/95 backdrop-blur">
|
||
<tr className="text-left text-xs text-muted-foreground">
|
||
{columns.map((col) => {
|
||
const active = sort?.id === col.id
|
||
const Icon = !active ? ChevronsUpDownIcon : sort.direction === "asc" ? ArrowUpIcon : ArrowDownIcon
|
||
return (
|
||
<th
|
||
key={col.id}
|
||
aria-sort={active ? (sort.direction === "asc" ? "ascending" : "descending") : undefined}
|
||
className={cn("h-10 px-3 font-medium first:pl-5 last:pr-5", col.headerClassName)}
|
||
>
|
||
{col.sort && onSortChange ? (
|
||
<button
|
||
type="button"
|
||
onClick={() => onSortChange(nextSort(sort ?? null, col.id))}
|
||
className={cn(
|
||
"-mx-1 inline-flex items-center gap-1 rounded px-1 transition hover:text-foreground",
|
||
active && "text-foreground",
|
||
)}
|
||
>
|
||
{col.header}
|
||
<Icon className={cn("size-3.5", !active && "opacity-50")} />
|
||
</button>
|
||
) : (
|
||
col.header
|
||
)}
|
||
</th>
|
||
)
|
||
})}
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{rows.map((row, i) => {
|
||
const extra = rowProps?.(row, i)
|
||
return (
|
||
<tr
|
||
key={getRowId(row)}
|
||
{...extra}
|
||
onClick={onRowClick ? (e) => onRowClick(row, e) : extra?.onClick}
|
||
className={cn(
|
||
"border-b border-border/60 transition-colors last:border-b-0",
|
||
onRowClick && "cursor-pointer hover:bg-muted/50",
|
||
rowClassName?.(row, i),
|
||
extra?.className,
|
||
)}
|
||
>
|
||
{columns.map((col) => (
|
||
<td key={col.id} className={cn("px-3 py-2.5 first:pl-5 last:pr-5", col.className)}>
|
||
{col.cell(row, i)}
|
||
</td>
|
||
))}
|
||
</tr>
|
||
)
|
||
})}
|
||
{!rows.length && empty && (
|
||
<tr>
|
||
<td colSpan={columns.length} className="py-12 text-center text-sm text-muted-foreground">
|
||
{empty}
|
||
</td>
|
||
</tr>
|
||
)}
|
||
</tbody>
|
||
</table>
|
||
)
|
||
}
|