组件Data Display
DataTable
@mox-hub/ui 组件 · Data Display · canonical
data-table@mox-hub/uiData Displaycanonicalsrc/components/data-table.tsx变体演示data-table
| 林晓 | 管理员 | 在线 |
| 陈默 | 编辑 | 离线 |
| 周屿 | 访客 | 邀请中 |
显示 1–3 条,共 3 条
Props API
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
| columns* | ColumnDef<T, unknown>[] | — | — |
| data* | T[] | — | — |
| getRowId* | (row: T, index: number) => string | — | — |
| onRowClick* | (row: T) => void | — | — |
| onRowContextMenu* | (row: T) => MenuItem[] | — | — |
| enableSelection* | boolean | false | — |
| selectedIds* | string[] | [] | — |
| onSelectedIdsChange* | (ids: string[]) => void | — | — |
| selectionActions* | (selectedRows: T[], clear: () => void) => ReactNode | — | — |
| sorting* | SortingState | — | — |
| onSortingChange* | OnChangeFn<SortingState> | — | — |
| manualPagination* | DataTableManualPagination | — | — |
| pageSize* | number | 20 | — |
| emptyContent* | ReactNode | — | — |
| labels* | Partial<DataTableLabels> | — | — |
| className* | string | — | — |
| stickyHeader* | boolean | true | — |
| maxHeight* | string | — | — |
| loading* | boolean | false | — |
| wrapCells* | boolean | false | — |
| selectionColumnSize* | number | 36 | — |
源码
"use client"
/**
* DataTable — 通用数据表(coss ui p-table-8 形态的泛化)
* TanStack Table 无头核心 + shadcn Table 原语:
* - 卡片式外壳(coss CardFrame 结构:圆角卡片内含表格 + border-t 分隔 footer)
* - 可排序列(表头按钮,键盘可达,aria-sort)
* - 可选行选择列(checkbox + 表头全选/半选)+ 选中悬浮操作胶囊(对齐 DataList SelectionBar)
* - 双模式分页:客户端(内置分页模型)/ 受控 manual(服务端分页,翻页回调)
*
* 排序始终为客户端排序(当前数据内);manual 分页模式下即"当前页内排序",
* 需要服务端排序的调用方请在数据层处理后再传入。
*/
import { Fragment, useEffect, useRef, useState, type ReactNode } from "react"
import {
flexRender,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
type ColumnDef,
type OnChangeFn,
type RowSelectionState,
type SortingState,
} from "@tanstack/react-table"
import {
ChevronDown,
ChevronLeft,
ChevronRight,
ChevronUp,
ChevronsUpDown,
X,
} from "lucide-react"
import { useMessages } from "../i18n"
import { cn } from "../lib/utils"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "./table"
import { Checkbox } from "./checkbox"
import { ContextMenu, type MenuItem } from "./context-menu"
import { Button } from "./button"
import { Spinner } from "./spinner"
export type { ColumnDef }
/**
* i18n 去耦(2026-11-08 迁移批):库不依赖 react-i18next,内置中文缺省文案
* (与主仓 i18n 资源 zh-CN 逐字一致),消费方可经 labels prop 整体覆写。
*/
export interface DataTableLabels {
/** 空态文案(emptyContent 未传时使用) */
empty: string
/** 加载态文案(loading=true 时使用) */
loading: string
/** 分页区间文案(from–to / total) */
range: (from: number, to: number, total: number) => string
prevPage: string
nextPage: string
selected: (count: number) => string
selectedWithTotal: (count: number, total: number) => string
/** 选中胶囊关闭按钮(aria-label + title) */
close: string
/** 表头全选 checkbox 的无障碍名 */
selectAll: string
/** 行选择 checkbox 的无障碍名 */
selectRow: string
/** 表格滚动区 role=region 的无障碍名 */
tableLabel: string
}
/** 受控(服务端)分页:page 为 1-based,total 为服务端总数 */
export interface DataTableManualPagination {
page: number
pageSize: number
total: number
onPageChange: (page: number) => void
}
export interface DataTableProps<T> {
columns: ColumnDef<T, unknown>[]
data: T[]
getRowId?: (row: T, index: number) => string
/** 行点击(整行可点,自动 cursor-pointer;点击选择框不触发) */
onRowClick?: (row: T) => void
/** 行右键菜单:返回该行菜单项(与 DataList.onItemContextMenu 同构) */
onRowContextMenu?: (row: T) => MenuItem[] | undefined
/** 启用行选择列(checkbox),受控:选中 id 列表 + 回调 */
enableSelection?: boolean
selectedIds?: string[]
onSelectedIdsChange?: (ids: string[]) => void
/** 选中悬浮胶囊内的批量操作(对齐 DataList.selectionActions;配合 ListActionButton 使用) */
selectionActions?: (selectedRows: T[], clear: () => void) => ReactNode
/** 受控排序(页面级 state 下发,如与「显示」菜单排序共用一个状态源);不传则组件内部自管 */
sorting?: SortingState
/** 受控排序回调(与 sorting 成对出现);不传则组件内部自管排序状态 */
onSortingChange?: OnChangeFn<SortingState>
/** 受控分页(服务端);不传则客户端分页(默认 pageSize 20) */
manualPagination?: DataTableManualPagination
pageSize?: number
/** 空态内容(默认内置空态文案) */
emptyContent?: ReactNode
/** 文案覆写(缺省内置中文,与主仓 i18n 资源逐字一致);i18n 去耦后由消费方注入 */
labels?: Partial<DataTableLabels>
/** 表格外层附加类名 */
className?: string
/** 是否固定吸顶表头(默认 true) */
stickyHeader?: boolean
/** 滚动容器最大高度(内容独立滚动,表头稳固吸顶) */
maxHeight?: string
/** 加载态(审计 P2-28):服务端翻页/首屏显示加载行,而不是先闪「暂无数据」 */
loading?: boolean
/** 单元格换行(审计 P2-28):长标题/URL/en-XA 下允许换行;默认保持 nowrap */
wrapCells?: boolean
/** 选择列宽度(px,默认 36,对齐 --spacing-control-md) */
selectionColumnSize?: number
}
export function DataTable<T>({
columns,
data,
getRowId,
onRowClick,
onRowContextMenu,
enableSelection = false,
selectedIds = [],
onSelectedIdsChange,
selectionActions,
sorting,
onSortingChange,
manualPagination,
pageSize = 20,
emptyContent,
labels,
className,
stickyHeader = true,
maxHeight,
loading = false,
wrapCells = false,
selectionColumnSize = 36,
}: DataTableProps<T>) {
const M = useMessages()
const L: DataTableLabels = { ...M.dataTable, ...labels }
const [internalSorting, setInternalSorting] = useState<SortingState>([])
const [clientPage, setClientPage] = useState(1)
// 排序受控环:外部传 onSortingChange 即为受控(sorting 可选,缺省视为未排序),
// 否则回落内部状态——两种模式对表头渲染无差别
const sortingManaged = onSortingChange !== undefined
const effectiveSorting = sortingManaged ? (sorting ?? []) : internalSorting
// 选择列受控:外部 string[] <-> tanstack RowSelectionState(受控环:
// state 由 selectedIds 派生,内部 toggle 经 onRowSelectionChange 上报后由外部回流)
const selectionManaged =
enableSelection && onSelectedIdsChange !== undefined && getRowId !== undefined
const derivedSelection: RowSelectionState = {}
if (selectionManaged) {
for (const id of selectedIds) derivedSelection[id] = true
}
// P3-11:只有受控选择(selectedIds + onSelectedIdsChange + getRowId)才插入选择列;
// 仅传 enableSelection 时不再留下 36px 空白列。
const columnsWithSelector: ColumnDef<T, unknown>[] = selectionManaged
? [
{
id: "__select",
enableSorting: false,
size: selectionColumnSize,
header: ({ table }) => {
if (!selectionManaged) return null
const all = table.getIsAllPageRowsSelected()
const some = table.getIsSomePageRowsSelected()
return (
<Checkbox
checked={all}
indeterminate={some && !all}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label={L.selectAll}
/>
)
},
cell: ({ row }) =>
selectionManaged ? (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
onClick={(e) => e.stopPropagation()}
aria-label={L.selectRow}
/>
) : null,
},
...columns,
]
: columns
const table = useReactTable({
data,
columns: columnsWithSelector,
getRowId,
state: {
sorting: effectiveSorting,
...(selectionManaged ? { rowSelection: derivedSelection } : {}),
...(manualPagination
? { pagination: { pageIndex: manualPagination.page - 1, pageSize: manualPagination.pageSize } }
: { pagination: { pageIndex: clientPage - 1, pageSize } }),
},
onSortingChange: sortingManaged ? onSortingChange : setInternalSorting,
enableRowSelection: enableSelection,
...(selectionManaged
? {
onRowSelectionChange: (updater) => {
const next =
typeof updater === "function"
? updater(derivedSelection)
: updater
onSelectedIdsChange!(
Object.entries(next)
.filter(([, v]) => v)
.map(([k]) => k),
)
},
}
: {}),
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
// manual 模式不用客户端分页模型(数据已经是当前页)
...(manualPagination
? { manualPagination: true, pageCount: Math.max(1, Math.ceil(manualPagination.total / manualPagination.pageSize)) }
: { getPaginationRowModel: getPaginationRowModel() }),
})
// 分页区间(manual:服务端 total;客户端:本地 filtered 行数)
const total = manualPagination ? manualPagination.total : table.getFilteredRowModel().rows.length
const currentPage = manualPagination ? manualPagination.page : clientPage
const size = manualPagination ? manualPagination.pageSize : pageSize
const from = total === 0 ? 0 : (currentPage - 1) * size + 1
const to = Math.min(currentPage * size, total)
const pageCount = Math.max(1, Math.ceil(total / size))
// 审计 P2-28:客户端模式不足一页时不渲染翻页控件(4 行数据仍显示 1/1 的禁用翻页)。
const showPager = manualPagination !== undefined || total > size
// 客户端分页在数据变少(筛选/删除)后必须回收到有效页,否则会显示 41–5 / 5 这类越界区间。
// manual 模式由消费方的 page 驱动,不在这里改写。
useEffect(() => {
if (manualPagination) return
setClientPage((page) => Math.min(page, pageCount))
}, [manualPagination, pageCount])
const selectedRows = selectionManaged
? data.filter((row, index) => selectedIds.includes(getRowId(row, index)))
: []
const clearSelection = () => onSelectedIdsChange?.([])
// 键盘行光标(宪法 §8.2:↑↓/j/k 移动、Enter 打开、x/space 选中、Escape 清除)
const containerRef = useRef<HTMLDivElement | null>(null)
const [activeRowId, setActiveRowId] = useState<string | null>(null)
const visibleRows = table.getRowModel().rows
const moveActiveRow = (delta: number) => {
if (visibleRows.length === 0) return
const idx = visibleRows.findIndex((r) => r.id === activeRowId)
const next =
idx === -1
? delta > 0
? 0
: visibleRows.length - 1
: Math.min(visibleRows.length - 1, Math.max(0, idx + delta))
const target = visibleRows[next]
setActiveRowId(target.id)
requestAnimationFrame(() => {
const el = containerRef.current?.querySelector(`[data-row-id="${CSS.escape(target.id)}"]`)
el?.scrollIntoView({ block: "nearest" })
})
}
const toggleRowSelection = (id: string) => {
const next = selectedIds.includes(id)
? selectedIds.filter((s) => s !== id)
: [...selectedIds, id]
onSelectedIdsChange?.(next)
}
// 键盘流只在表格容器自身聚焦时接管:焦点落在行内交互元素(checkbox/排序按钮/链接)
// 时按键交还原生行为,避免 Enter/Space 双触发与 j/k 干扰,也不与命令面板/表单快捷键冲突。
// base-ui Checkbox.Root 渲染为 span[role=checkbox](非 button),需显式纳入
const isInteractiveTarget = (e: React.KeyboardEvent | React.MouseEvent) => {
if (e.target === e.currentTarget) return false
return !!(e.target as HTMLElement).closest(
"button, a, input, textarea, select, [role=\"checkbox\"], [contenteditable=\"true\"]",
)
}
const handleContainerFocus = () => {
// 聚焦即激活首行(Tab 进入后直接可 Enter/x 操作,无需先按 j 探路)
if (!activeRowId && visibleRows.length > 0) setActiveRowId(visibleRows[0].id)
}
const handleContainerClickCapture = (e: React.MouseEvent) => {
if (isInteractiveTarget(e)) return
// 先聚焦(触发 onFocus 激活首行),再覆盖为被点击的行——
// 此前点击不可聚焦的 tr 会把焦点丢回 body,键盘流随之中断
containerRef.current?.focus({ preventScroll: true })
const rowEl = (e.target as HTMLElement).closest<HTMLElement>("[data-row-id]")
if (rowEl?.dataset.rowId) setActiveRowId(rowEl.dataset.rowId)
}
const handleListKeyDown = (e: React.KeyboardEvent) => {
if (isInteractiveTarget(e)) return
if (e.key === "ArrowDown" || e.key === "j") {
e.preventDefault()
moveActiveRow(1)
} else if (e.key === "ArrowUp" || e.key === "k") {
e.preventDefault()
moveActiveRow(-1)
} else if ((e.key === "x" || e.key === "X" || e.key === " ") && selectionManaged && activeRowId) {
// x / space 切换当前行选中:走既有 enableSelection 受控契约(selectedIds/onSelectedIdsChange,
// 悬浮胶囊与页面批量操作随选中状态联动)
e.preventDefault()
toggleRowSelection(activeRowId)
} else if (e.key === "Enter" || (e.key === " " && !selectionManaged)) {
if (activeRowId && onRowClick) {
const row = visibleRows.find((r) => r.id === activeRowId)
if (row) {
e.preventDefault()
onRowClick(row.original)
}
}
} else if (e.key === "Escape") {
clearSelection()
setActiveRowId(null)
}
}
return (
<div
ref={containerRef}
role="region"
tabIndex={0}
onKeyDown={handleListKeyDown}
onFocus={handleContainerFocus}
onBlur={(event) => {
// P3-11:焦点移出表格后清除活动行,避免残留高亮像被选中。
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
setActiveRowId(null)
}
}}
onClickCapture={handleContainerClickCapture}
className={cn("space-y-2 outline-none focus-visible:ring-2 focus-visible:ring-ring/50", className)}
aria-label={L.tableLabel}
aria-busy={loading || undefined}
>
{/* 卡片式外壳(coss CardFrame 结构):表格 + border-t 分隔 footer */}
<div className="rounded-xl border border-border bg-card shadow-xs overflow-hidden">
<div
data-slot="data-table-scroll"
className={cn(
"w-full overflow-x-auto",
maxHeight ? "overflow-y-auto overscroll-contain" : "",
)}
style={maxHeight ? { maxHeight } : undefined}
>
<Table containerClassName="overflow-visible">
<TableHeader
className={cn(
"bg-muted/40",
stickyHeader && "sticky top-0 z-dropdown bg-card border-b border-border shadow-xs",
)}
>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
const canSort = header.column.getCanSort()
const sorted = header.column.getIsSorted()
return (
<TableHead
key={header.id}
className={cn(
stickyHeader && "sticky top-0 z-dropdown bg-card",
wrapCells && "whitespace-normal break-words",
)}
style={header.getSize() !== 150 ? { width: header.getSize() } : undefined}
aria-sort={
sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : undefined
}
>
{header.isPlaceholder ? null : canSort ? (
<button
type="button"
className="group flex items-center gap-1 text-start font-medium outline-hidden focus-visible:ring-2 focus-visible:ring-ring/50 rounded-xs"
onClick={header.column.getToggleSortingHandler()}
>
{flexRender(header.column.columnDef.header, header.getContext())}
{sorted === "asc" ? (
<ChevronUp className="size-3.5 shrink-0" />
) : sorted === "desc" ? (
<ChevronDown className="size-3.5 shrink-0" />
) : (
<ChevronsUpDown className="size-3.5 shrink-0 opacity-0 transition-opacity duration-fast group-hover:opacity-50 group-focus-visible:opacity-50" />
)}
</button>
) : (
flexRender(header.column.columnDef.header, header.getContext())
)}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={columnsWithSelector.length} className="h-24 text-center">
<span className="inline-flex items-center gap-2 text-muted-foreground">
<Spinner size="sm" label={L.loading} />
{L.loading}
</span>
</TableCell>
</TableRow>
) : table.getRowModel().rows.length === 0 ? (
<TableRow>
<TableCell colSpan={columnsWithSelector.length} className="h-24 text-center">
{emptyContent ?? L.empty}
</TableCell>
</TableRow>
) : (
visibleRows.map((row) => {
const rowEl = (
<TableRow
data-row-id={row.id}
data-state={row.getIsSelected() ? "selected" : undefined}
className={cn(
onRowClick && "cursor-pointer",
// P3-11:活动行用 ring,避免与 selected 的 bg-muted 叠色冲突
activeRowId === row.id && "ring-1 ring-inset ring-ring/60",
)}
onClick={onRowClick ? () => onRowClick(row.original) : undefined}
>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
className={cn(wrapCells && "whitespace-normal break-words")}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
);
const menuItems = onRowContextMenu?.(row.original);
return menuItems?.length ? (
<ContextMenu key={row.id} items={menuItems}>
{rowEl}
</ContextMenu>
) : (
<Fragment key={row.id}>{rowEl}</Fragment>
);
})
)}
</TableBody>
</Table>
</div>
{/* 卡片 footer:结果区间常驻(有数据时);翻页控件不足一页时隐藏(审计 P2-28) */}
{total > 0 && (
<div className="flex items-center justify-between border-t border-border px-4 py-2.5 text-xs text-muted-foreground">
<span>{L.range(from, to, total)}</span>
{showPager && (
<span className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="size-control-2xs p-0 pointer-coarse:size-11"
disabled={currentPage <= 1}
onClick={() =>
manualPagination
? manualPagination.onPageChange(currentPage - 1)
: setClientPage((p) => Math.max(1, p - 1))
}
aria-label={L.prevPage}
>
<ChevronLeft className="size-4 rtl:-scale-x-100" />
</Button>
<span className="tabular-nums">
{currentPage} / {pageCount}
</span>
<Button
variant="ghost"
size="sm"
className="size-control-2xs p-0 pointer-coarse:size-11"
disabled={currentPage >= pageCount}
onClick={() =>
manualPagination
? manualPagination.onPageChange(currentPage + 1)
: setClientPage((p) => p + 1)
}
aria-label={L.nextPage}
>
<ChevronRight className="size-4 rtl:-scale-x-100" />
</Button>
</span>
)}
</div>
)}
</div>
{/* 多选悬浮胶囊(对齐 DataList SelectionBar 形态) */}
{selectionManaged && selectionActions && selectedRows.length > 0 && (
<div className="pointer-events-none fixed bottom-28 left-1/2 z-modal -translate-x-1/2 transition-[transform,opacity] duration-normal">
<div className="pointer-events-auto flex items-center gap-1 rounded-full border border-border bg-card px-2.5 py-2 shadow-xs">
<span className="px-2 text-sm font-semibold tabular-nums">
{total > 0
? L.selectedWithTotal(selectedRows.length, total)
: L.selected(selectedRows.length)}
</span>
<div className="flex items-center gap-1">
{selectionActions(selectedRows, clearSelection)}
</div>
<button
type="button"
aria-label={L.close}
title={L.close}
onClick={clearSelection}
className="flex size-control-2xs items-center justify-center rounded-full text-muted-foreground transition-colors duration-fast hover:bg-muted hover:text-foreground pointer-coarse:size-11"
>
<X className="size-4" />
</button>
</div>
</div>
)}
</div>
)
}
可访问性与 RTL
- 键盘:交互件保留
:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。 - RTL:间距、对齐与方向性图标使用逻辑属性 (
ms-*/text-start/rtl:-scale-x-100);通过ThemeProvider或I18nProvider的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。 - 文案:优先用组件
labels/translate/translatorprops,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。 - 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。
用法说明
TanStack Table 封装,列定义、排序、筛选、分页按 props 注入;大数据量接服务端分页。