录制演示
源码
"use client";
/**
* Data table — replica of the public UI Stacks spec.
* Original implementation written from the public API docs.
*/
/**
* Data table — replica of the public UI Stacks spec.
* Original implementation written from the public API docs.
*/
import * as React from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { ChevronDown, ChevronLeft, ChevronRight, ChevronsUpDown } from "lucide-react";
import { cn } from "../internal";
export type DataTableColumn<T> = {
id: string;
header: React.ReactNode;
cell?: (row: T) => React.ReactNode;
sortValue?: (row: T) => string | number;
numeric?: boolean;
width?: number | string;
};
export type DataTableSort = { id: string; dir: "asc" | "desc" } | null;
export interface DataTableProps<T> {
columns: DataTableColumn<T>[];
rows: T[];
getRowId: (row: T) => string;
variant?: "outline" | "flat";
density?: "compact" | "default" | "comfortable";
selectable?: boolean;
selected?: string[];
onSelectedChange?: (ids: string[]) => void;
sort?: DataTableSort;
defaultSort?: DataTableSort;
onSortChange?: (sort: DataTableSort) => void;
pageSize?: number;
itemLabel?: string;
toolbar?: React.ReactNode | ((selected: string[], clear: () => void) => React.ReactNode);
rowActions?: (row: T) => React.ReactNode;
empty?: React.ReactNode;
label?: string;
locale?: "en" | "zh-CN";
className?: string;
}
const DENSITY = {
compact: "h-10",
default: "h-12",
comfortable: "h-14",
} as const;
/** A toned dot plus its label, for status cells. */
export function DataTableStatus({
tone,
children,
}: {
tone: "neutral" | "success" | "warning" | "danger";
children?: React.ReactNode;
}) {
const color = {
neutral: "bg-fg-subtle",
success: "bg-success",
warning: "bg-warning",
danger: "bg-danger",
}[tone];
return (
<span className="inline-flex items-center gap-1.5 text-[13px] text-fg">
<span className={cn("size-2 shrink-0 rounded-full", color)} aria-hidden />
{children}
</span>
);
}
/**
* Data table: sortable columns, row checkboxes with a mixed select-all,
* a pager and an empty state. Rows fade in when the sort changes.
*/
export function DataTable<T>({
columns,
rows,
getRowId,
variant = "outline",
density = "default",
selectable = false,
selected,
onSelectedChange,
sort,
defaultSort = null,
onSortChange,
pageSize = 10,
locale = "en",
itemLabel = locale === "zh-CN" ? "行" : "rows",
toolbar,
rowActions,
empty,
label = locale === "zh-CN" ? "表格" : "Table",
className,
}: DataTableProps<T>) {
const reduce = useReducedMotion();
const zh = locale === "zh-CN";
const [innerSort, setInnerSort] = React.useState<DataTableSort>(defaultSort);
const [innerSelected, setInnerSelected] = React.useState<string[]>([]);
const [page, setPage] = React.useState(1);
const activeSort = sort !== undefined ? sort : innerSort;
const activeSelected = selected !== undefined ? selected : innerSelected;
const setSort = (next: DataTableSort) => {
if (sort === undefined) setInnerSort(next);
onSortChange?.(next);
};
const setSelected = (next: string[]) => {
if (selected === undefined) setInnerSelected(next);
onSelectedChange?.(next);
};
const sorted = React.useMemo(() => {
if (!activeSort) return rows;
const column = columns.find((candidate) => candidate.id === activeSort.id);
if (!column?.sortValue) return rows;
const factor = activeSort.dir === "asc" ? 1 : -1;
return [...rows].sort((a, b) => {
const left = column.sortValue!(a);
const right = column.sortValue!(b);
if (typeof left === "number" && typeof right === "number") return (left - right) * factor;
return String(left).localeCompare(String(right)) * factor;
});
}, [rows, columns, activeSort]);
const pages = Math.max(1, Math.ceil(sorted.length / pageSize));
const current = Math.min(page, pages);
const visible = sorted.slice((current - 1) * pageSize, current * pageSize);
const firstRow = sorted.length === 0 ? 0 : (current - 1) * pageSize + 1;
const lastRow = Math.min(current * pageSize, sorted.length);
const ids = visible.map(getRowId);
const allOnPage = ids.length > 0 && ids.every((id) => activeSelected.includes(id));
const someOnPage = ids.some((id) => activeSelected.includes(id));
const cycleSort = (id: string) => {
const column = columns.find((candidate) => candidate.id === id);
if (!column?.sortValue) return;
if (!activeSort || activeSort.id !== id) {
setSort({ id, dir: "asc" });
} else if (activeSort.dir === "asc") {
setSort({ id, dir: "desc" });
} else {
setSort(null);
}
setPage(1);
};
const toggleRow = (id: string) => {
setSelected(
activeSelected.includes(id)
? activeSelected.filter((candidate) => candidate !== id)
: [...activeSelected, id],
);
};
const toggleAll = () => {
setSelected(allOnPage ? activeSelected.filter((id) => !ids.includes(id)) : [...new Set([...activeSelected, ...ids])]);
};
const clear = () => setSelected([]);
return (
<div className={cn("flex flex-col gap-3", className)}>
{toolbar ? (
<div className="flex items-center gap-2">
{typeof toolbar === "function"
? toolbar(activeSelected, clear)
: toolbar}
</div>
) : null}
<div
className={cn(
"overflow-hidden rounded-[14px]",
variant === "outline"
? "border border-border bg-surface shadow-[var(--shadow-card)]"
: "border border-transparent",
)}
>
<table aria-label={label} className="w-full border-collapse text-[13px]">
<thead>
<tr className={cn(variant === "outline" && "bg-subtle")}>
{selectable ? (
<th scope="col" className="w-10 px-3">
<input
type="checkbox"
aria-label={zh ? "选择本页全部行" : "Select all rows on this page"}
checked={allOnPage}
ref={(node) => {
if (node) node.indeterminate = !allOnPage && someOnPage;
}}
onChange={toggleAll}
className="size-3.5 accent-[var(--select)]"
/>
</th>
) : null}
{columns.map((column) => {
const sortedState =
activeSort?.id === column.id ? activeSort.dir : undefined;
return (
<th
key={column.id}
scope="col"
style={column.width ? { width: column.width } : undefined}
aria-sort={
sortedState === "asc"
? "ascending"
: sortedState === "desc"
? "descending"
: column.sortValue
? "none"
: undefined
}
className={cn(
"px-3 py-2.5 text-left text-[11.5px] font-semibold uppercase tracking-wide text-fg-subtle",
column.numeric && "text-right",
)}
>
{column.sortValue ? (
<button
type="button"
data-sort-column={column.id}
onClick={() => cycleSort(column.id)}
className={cn(
"inline-flex items-center gap-1 rounded-[6px] px-1 py-0.5 transition-colors hover:text-fg",
column.numeric && "flex-row-reverse",
)}
>
{column.header}
{sortedState === "asc" ? (
<ChevronDown className="size-3 rotate-180" aria-hidden />
) : sortedState === "desc" ? (
<ChevronDown className="size-3" aria-hidden />
) : (
<ChevronsUpDown className="size-3 opacity-40" aria-hidden />
)}
</button>
) : (
column.header
)}
</th>
);
})}
{rowActions ? <th scope="col" className="w-12 px-3" /> : null}
</tr>
</thead>
<tbody>
<AnimatePresence initial={false} mode="popLayout">
{visible.map((row) => {
const id = getRowId(row);
const isSelected = activeSelected.includes(id);
return (
<motion.tr
key={id}
layout={!reduce}
initial={reduce ? false : { opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
exit={reduce ? undefined : { opacity: 0 }}
transition={{ duration: 0.18 }}
className={cn(
"border-t border-border",
isSelected ? "bg-[var(--select-soft)]" : "bg-surface",
)}
>
{selectable ? (
<td className="px-3">
<input
type="checkbox"
data-select-row={id}
aria-label={zh ? `选择 ${id} 行` : `Select row ${id}`}
checked={isSelected}
onChange={() => toggleRow(id)}
className="size-3.5 accent-[var(--select)]"
/>
</td>
) : null}
{columns.map((column) => (
<td
key={column.id}
className={cn(
"px-3 text-fg-muted",
column.numeric && "text-right tabular-nums",
)}
>
{column.cell
? column.cell(row)
: column.sortValue
? String(column.sortValue(row))
: null}
</td>
))}
{rowActions ? (
<td className="px-3 text-right">{rowActions(row)}</td>
) : null}
</motion.tr>
);
})}
</AnimatePresence>
</tbody>
</table>
{visible.length === 0 ? (
<div className="px-4 py-12 text-center text-[13.5px] text-fg-subtle">
{empty ?? (zh ? "暂无数据" : "Nothing here yet")}
</div>
) : null}
</div>
<div className="flex items-center justify-between gap-3 text-[12.5px] text-fg-subtle">
<span>
{zh
? `${firstRow ? `第 ${firstRow}–${lastRow} 条,` : ""}共 ${sorted.length} ${itemLabel}`
: `Showing ${firstRow}–${lastRow} of ${sorted.length} ${itemLabel}`}
</span>
{pages > 1 ? (
<div className="flex items-center gap-1">
<button
type="button"
data-table-page="previous"
aria-label={zh ? "上一页" : "Previous page"}
disabled={current === 1}
onClick={() => setPage((value) => Math.max(1, value - 1))}
className="grid size-7 place-items-center rounded-[7px] border border-border bg-surface disabled:opacity-40"
>
<ChevronLeft className="size-3.5" aria-hidden />
</button>
<span className="px-2 tabular-nums">
{current} / {pages}
</span>
<button
type="button"
data-table-page="next"
aria-label={zh ? "下一页" : "Next page"}
disabled={current === pages}
onClick={() => setPage((value) => Math.min(pages, value + 1))}
className="grid size-7 place-items-center rounded-[7px] border border-border bg-surface disabled:opacity-40"
>
<ChevronRight className="size-3.5" aria-hidden />
</button>
</div>
) : null}
</div>
</div>
);
}
export default DataTable;
使用说明
把 TSX 加入 React 项目,并安装组件引用的依赖。页面样式依赖 Tailwind CSS 与 主题变量。
包依赖 · lucide-react、motion、react
共享源码 · internal.ts
参数
| 名称 | 类型 | 说明 |
|---|---|---|
`columns` | `{ id; header; cell?; sortValue?; numeric?; width? }[]` | cell renders anything; sortValue makes the column sortable; numeric right-aligns it. |
`rows / getRowId` | `T[] / (row) => string` | Typed with generics: DataTable<Invoice>. |
`variant / density` | `"outline" \| "flat" / "compact" \| "default" \| "comfortable"` | A card with a tinted header, or lines only; rows 40, 48 or 56 tall. |
`selectable / selected / onSelectedChange` | `boolean / string[] / (ids) => void` | Checkboxes and a select-all box that turns mixed. |
`sort / defaultSort / onSortChange` | `{ id; dir: "asc" \| "desc" } \| null` | A click cycles ascending, descending, off and sets aria-sort. |
`pageSize / itemLabel` | `number / string` | Rows per page, and the noun in “Showing 1–5 of 12 invoices”. |
`toolbar` | `ReactNode \| (selected, clear) => ReactNode` | Search and actions above the header; swap in bulk actions while rows are picked. |
`rowActions / empty / label` | `(row) => ReactNode / ReactNode / string` | The last column, the no-rows message, and the table's accessible name. |
`DataTableStatus` | `{ tone: "neutral" \| "success" \| "warning" \| "danger" }` | Exported helper for status cells: a toned dot and its label. |
locale | "en" | "zh-CN" | Optional interface language. Defaults to English. |