From 50a01fc34ea61d520988694ccff2dba9ac6a922d Mon Sep 17 00:00:00 2001 From: Ilya Mukhortov Date: Mon, 26 Oct 2026 17:12:03 +1000 Subject: [PATCH] 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 --- src/charts/chart-hover.tsx | 15 +-- src/hooks/use-element-width.ts | 16 +++ src/kit/data-table.tsx | 222 ++++++++++++++++++--------------- 3 files changed, 140 insertions(+), 113 deletions(-) create mode 100644 src/hooks/use-element-width.ts diff --git a/src/charts/chart-hover.tsx b/src/charts/chart-hover.tsx index 1fec26d..a207dad 100644 --- a/src/charts/chart-hover.tsx +++ b/src/charts/chart-hover.tsx @@ -2,20 +2,7 @@ import * as React from "react" import { cn } from "../lib/utils" -/** Ширина контейнера — чтобы SVG рисовался в реальных пикселях и текст не масштабировался. */ -export function useElementWidth() { - const ref = React.useRef(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 { readonly item: T diff --git a/src/hooks/use-element-width.ts b/src/hooks/use-element-width.ts new file mode 100644 index 0000000..7c70416 --- /dev/null +++ b/src/hooks/use-element-width.ts @@ -0,0 +1,16 @@ +import * as React from "react" + +/** Ширина элемента по ResizeObserver; первый замер до отрисовки, чтобы не было мигания. 0 — ещё не измерено. */ +export function useElementWidth() { + const ref = React.useRef(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 +} diff --git a/src/kit/data-table.tsx b/src/kit/data-table.tsx index c467325..9722319 100644 --- a/src/kit/data-table.tsx +++ b/src/kit/data-table.tsx @@ -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 { 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`. + * Если колонки всё равно не влезают — оберните таблицу в ``. */ export function DataTable({ columns, @@ -66,6 +76,7 @@ export function DataTable({ empty, loading, renderCard, + cardsBelow = 640, className, }: { columns: readonly DataColumn[] @@ -81,121 +92,134 @@ export function DataTable({ loading?: boolean /** Карточка строки для узкого экрана; без неё таблица остаётся таблицей. */ renderCard?: (row: T, index: number) => React.ReactNode + /** Ширина таблицы, уже которой строки показываются карточками. */ + cardsBelow?: number className?: string }) { - const narrow = useMediaQuery("(max-width: 767px)") + const [ref, width] = useElementWidth() + // 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" ? : empty if (renderCard && narrow) { return ( -
    - {skeleton && - Array.from({ length: 5 }, (_, i) => ( -
  • - - -
  • - ))} - {rows.map((row, i) => { - const extra = rowProps?.(row, i) - return ( -
  • 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)} -
  • - ) - })} - {!rows.length && !skeleton && emptyNode &&
  • {emptyNode}
  • } -
+
+
    + {skeleton && + Array.from({ length: 5 }, (_, i) => ( +
  • + + +
  • + ))} + {rows.map((row, i) => { + const extra = rowProps?.(row, i) + return ( +
  • 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)} +
  • + ) + })} + {!rows.length && !skeleton && emptyNode &&
  • {emptyNode}
  • } +
+
) } return ( - - {/* Липкая шапка: фон непрозрачный, линия — тенью ячеек (border у thead при прокрутке остаётся на месте). */} - - - {columns.map((col) => { - const active = sort?.id === col.id - const Icon = !active ? ChevronsUpDownIcon : sort.direction === "asc" ? ArrowUpIcon : ArrowDownIcon +
+
+ {/* Липкая шапка: фон непрозрачный, линия — тенью ячеек (border у thead при прокрутке остаётся на месте). */} + + + {visible.map((col) => { + const active = sort?.id === col.id + const Icon = !active ? ChevronsUpDownIcon : sort.direction === "asc" ? ArrowUpIcon : ArrowDownIcon + return ( + + ) + })} + + + + {rows.map((row, i) => { + const extra = rowProps?.(row, i) return ( - + {visible.map((col) => ( + + ))} + ) })} - - - - {rows.map((row, i) => { - const extra = rowProps?.(row, i) - return ( - 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) => ( - - ))} + {skeleton && + Array.from({ length: 6 }, (_, i) => ( + + {visible.map((col, c) => ( + + ))} + + ))} + {!rows.length && !skeleton && emptyNode && ( + + - ) - })} - {skeleton && - Array.from({ length: 6 }, (_, i) => ( - - {columns.map((col, c) => ( - - ))} - - ))} - {!rows.length && !skeleton && emptyNode && ( - - - - )} - -
+ {col.sort && onSortChange ? ( + + ) : ( + col.header + )} +
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 ? ( - - ) : ( - col.header - )} - + {col.cell(row, i)} +
- {col.cell(row, i)} -
+ +
{emptyNode}
- -
{emptyNode}
+ )} + + + ) }