DataTable: container-width columns, grow and minWidth

Columns now adapt to the table's own width instead of the window's:
minWidth hides secondary columns, grow columns take the free space and
shrink first, and cardsBelow (640px) switches to renderCard cards.
useElementWidth moves to hooks/ and is still re-exported from chart-hover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ilya Mukhortov 2026-10-26 17:12:03 +10:00
parent 51611deece
commit 50a01fc34e
3 changed files with 140 additions and 113 deletions

View File

@ -2,20 +2,7 @@ import * as React from "react"
import { cn } from "../lib/utils"
/** Ширина контейнера — чтобы SVG рисовался в реальных пикселях и текст не масштабировался. */
export function useElementWidth<T extends HTMLElement>() {
const ref = React.useRef<T>(null)
const [width, setWidth] = React.useState(0)
React.useLayoutEffect(() => {
const el = ref.current
if (!el) return
const observer = new ResizeObserver(([entry]) => setWidth(Math.round(entry.contentRect.width)))
observer.observe(el)
setWidth(Math.round(el.getBoundingClientRect().width))
return () => observer.disconnect()
}, [])
return [ref, width] as const
}
export { useElementWidth } from "../hooks/use-element-width"
export interface HoverState<T> {
readonly item: T

View File

@ -0,0 +1,16 @@
import * as React from "react"
/** Ширина элемента по ResizeObserver; первый замер до отрисовки, чтобы не было мигания. 0 — ещё не измерено. */
export function useElementWidth<T extends HTMLElement>() {
const ref = React.useRef<T>(null)
const [width, setWidth] = React.useState(0)
React.useLayoutEffect(() => {
const el = ref.current
if (!el) return
const observer = new ResizeObserver(([entry]) => setWidth(Math.round(entry.contentRect.width)))
observer.observe(el)
setWidth(Math.round(el.getBoundingClientRect().width))
return () => observer.disconnect()
}, [])
return [ref, width] as const
}

View File

@ -2,7 +2,7 @@ import * as React from "react"
import { ArrowDownIcon, ArrowUpIcon, ChevronsUpDownIcon } from "lucide-react"
import { cn } from "../lib/utils"
import { useMediaQuery } from "../hooks/use-media-query"
import { useElementWidth } from "../hooks/use-element-width"
import { Skeleton } from "../ui/skeleton"
import { EmptyState } from "./empty-state"
@ -21,6 +21,14 @@ export interface DataColumn<T> {
readonly sort?: (a: T, b: T) => number
readonly className?: string
readonly headerClassName?: string
/** Колонка видна, только когда таблица не уже стольких пикселей (второстепенные данные). */
readonly minWidth?: number
/**
* Колонка забирает свободное место и сжимается первой (ширина в %, `max-w-0`): внутри работают
* `truncate` и `line-clamp-*`; для переноса длинных слов — `break-words`. Несколько grow-колонок делят место.
* Ширину соседней колонки задавайте через `min-w-*`: обычный `w-*` проигрывает процентной grow-колонке.
*/
readonly grow?: boolean
}
/** Отсортировать строки по словарю компараторов {columnId: compare}. */
@ -52,7 +60,9 @@ export function nextSort(current: SortState | null, id: string): SortState | nul
* кликабельные строки. Строки передаются уже отсортированными/порезанными
* (см. sortRows) — так таблица одинаково работает с пагинацией и без неё.
* `empty` — строка (станет EmptyState) или свой EmptyState; `loading` без строк — скелетоны;
* `renderCard` — на узком экране (< 768px) строки показываются карточками.
* Ширина считается по контейнеру, а не по окну: колонки с `minWidth` прячутся, когда места мало,
* `grow`-колонка сжимается первой, а уже `cardsBelow` (640px) строки показываются карточками `renderCard`.
* Если колонки всё равно не влезают — оберните таблицу в `<ScrollArea horizontal>`.
*/
export function DataTable<T>({
columns,
@ -66,6 +76,7 @@ export function DataTable<T>({
empty,
loading,
renderCard,
cardsBelow = 640,
className,
}: {
columns: readonly DataColumn<T>[]
@ -81,121 +92,134 @@ export function DataTable<T>({
loading?: boolean
/** Карточка строки для узкого экрана; без неё таблица остаётся таблицей. */
renderCard?: (row: T, index: number) => React.ReactNode
/** Ширина таблицы, уже которой строки показываются карточками. */
cardsBelow?: number
className?: string
}) {
const narrow = useMediaQuery("(max-width: 767px)")
const [ref, width] = useElementWidth<HTMLDivElement>()
// 0 — ещё не измерено: показываем всё, замер успеет до отрисовки.
const narrow = width > 0 && width < cardsBelow
const visible = width > 0 ? columns.filter((c) => !c.minWidth || width >= c.minWidth) : columns
// grow-колонки делят свободное место поровну: две по 100% отдали бы всё первой.
const growWidth = `${100 / Math.max(1, visible.filter((c) => c.grow).length)}%`
const skeleton = loading && !rows.length
const emptyNode =
typeof empty === "string" ? <EmptyState size="sm" title={empty} /> : empty
if (renderCard && narrow) {
return (
<ul className={cn("divide-y divide-border/60 text-sm", className)}>
{skeleton &&
Array.from({ length: 5 }, (_, i) => (
<li key={i} className="space-y-2 px-4 py-3">
<Skeleton className="h-4 w-2/3" />
<Skeleton className="h-3 w-1/2" />
</li>
))}
{rows.map((row, i) => {
const extra = rowProps?.(row, i)
return (
<li
key={getRowId(row)}
onClick={onRowClick ? (e) => onRowClick(row, e) : undefined}
className={cn(
"px-4 py-3 transition-colors",
onRowClick && "cursor-pointer active:bg-muted/60",
rowClassName?.(row, i),
extra?.className,
)}
>
{renderCard(row, i)}
</li>
)
})}
{!rows.length && !skeleton && emptyNode && <li>{emptyNode}</li>}
</ul>
<div ref={ref}>
<ul className={cn("divide-y divide-border/60 text-sm", className)}>
{skeleton &&
Array.from({ length: 5 }, (_, i) => (
<li key={i} className="space-y-2 px-4 py-3">
<Skeleton className="h-4 w-2/3" />
<Skeleton className="h-3 w-1/2" />
</li>
))}
{rows.map((row, i) => {
const extra = rowProps?.(row, i)
return (
<li
key={getRowId(row)}
onClick={onRowClick ? (e) => onRowClick(row, e) : undefined}
className={cn(
"px-4 py-3 transition-colors",
onRowClick && "cursor-pointer active:bg-muted/60",
rowClassName?.(row, i),
extra?.className,
)}
>
{renderCard(row, i)}
</li>
)
})}
{!rows.length && !skeleton && emptyNode && <li>{emptyNode}</li>}
</ul>
</div>
)
}
return (
<table className={cn("w-full text-sm", className)}>
{/* Липкая шапка: фон непрозрачный, линия — тенью ячеек (border у thead при прокрутке остаётся на месте). */}
<thead className="sticky top-0 z-10">
<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
<div ref={ref}>
<table className={cn("w-full text-sm", className)}>
{/* Липкая шапка: фон непрозрачный, линия — тенью ячеек (border у thead при прокрутке остаётся на месте). */}
<thead className="sticky top-0 z-10">
<tr className="text-left text-xs text-muted-foreground">
{visible.map((col) => {
const active = sort?.id === col.id
const Icon = !active ? ChevronsUpDownIcon : sort.direction === "asc" ? ArrowUpIcon : ArrowDownIcon
return (
<th
key={col.id}
style={col.grow ? { width: growWidth } : undefined}
aria-sort={active ? (sort.direction === "asc" ? "ascending" : "descending") : undefined}
className={cn(
"h-10 bg-card px-3 font-medium shadow-[inset_0_-1px_0_var(--border)] first:pl-5 last:pr-5",
col.grow && "max-w-0",
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 (
<th
key={col.id}
aria-sort={active ? (sort.direction === "asc" ? "ascending" : "descending") : undefined}
<tr
key={getRowId(row)}
{...extra}
onClick={onRowClick ? (e) => onRowClick(row, e) : extra?.onClick}
className={cn(
"h-10 bg-card px-3 font-medium shadow-[inset_0_-1px_0_var(--border)] first:pl-5 last:pr-5",
col.headerClassName,
"border-b border-border/60 transition-colors last:border-b-0",
onRowClick && "cursor-pointer hover:bg-muted/50",
rowClassName?.(row, i),
extra?.className,
)}
>
{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>
{visible.map((col) => (
<td key={col.id} className={cn("px-3 py-2.5 first:pl-5 last:pr-5", col.grow && "max-w-0", col.className)}>
{col.cell(row, i)}
</td>
))}
</tr>
)
})}
</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>
))}
{skeleton &&
Array.from({ length: 6 }, (_, i) => (
<tr key={i} className="border-b border-border/60 last:border-b-0">
{visible.map((col, c) => (
<td key={col.id} className="px-3 py-3.5 first:pl-5 last:pr-5">
<Skeleton className={cn("h-3.5", c === 0 ? "w-12" : c % 2 ? "w-3/4" : "w-1/2")} />
</td>
))}
</tr>
))}
{!rows.length && !skeleton && emptyNode && (
<tr>
<td colSpan={visible.length}>{emptyNode}</td>
</tr>
)
})}
{skeleton &&
Array.from({ length: 6 }, (_, i) => (
<tr key={i} className="border-b border-border/60 last:border-b-0">
{columns.map((col, c) => (
<td key={col.id} className="px-3 py-3.5 first:pl-5 last:pr-5">
<Skeleton className={cn("h-3.5", c === 0 ? "w-12" : c % 2 ? "w-3/4" : "w-1/2")} />
</td>
))}
</tr>
))}
{!rows.length && !skeleton && emptyNode && (
<tr>
<td colSpan={columns.length}>{emptyNode}</td>
</tr>
)}
</tbody>
</table>
)}
</tbody>
</table>
</div>
)
}