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:
parent
51611deece
commit
50a01fc34e
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
@ -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,15 +92,23 @@ 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 (
|
||||
<div ref={ref}>
|
||||
<ul className={cn("divide-y divide-border/60 text-sm", className)}>
|
||||
{skeleton &&
|
||||
Array.from({ length: 5 }, (_, i) => (
|
||||
|
|
@ -117,23 +136,27 @@ export function DataTable<T>({
|
|||
})}
|
||||
{!rows.length && !skeleton && emptyNode && <li>{emptyNode}</li>}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<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">
|
||||
{columns.map((col) => {
|
||||
{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,
|
||||
)}
|
||||
>
|
||||
|
|
@ -172,8 +195,8 @@ export function DataTable<T>({
|
|||
extra?.className,
|
||||
)}
|
||||
>
|
||||
{columns.map((col) => (
|
||||
<td key={col.id} className={cn("px-3 py-2.5 first:pl-5 last:pr-5", col.className)}>
|
||||
{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>
|
||||
))}
|
||||
|
|
@ -183,7 +206,7 @@ export function DataTable<T>({
|
|||
{skeleton &&
|
||||
Array.from({ length: 6 }, (_, i) => (
|
||||
<tr key={i} className="border-b border-border/60 last:border-b-0">
|
||||
{columns.map((col, c) => (
|
||||
{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>
|
||||
|
|
@ -192,10 +215,11 @@ export function DataTable<T>({
|
|||
))}
|
||||
{!rows.length && !skeleton && emptyNode && (
|
||||
<tr>
|
||||
<td colSpan={columns.length}>{emptyNode}</td>
|
||||
<td colSpan={visible.length}>{emptyNode}</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue