243 lines
8.0 KiB
TypeScript
243 lines
8.0 KiB
TypeScript
import { ChevronRight, type LucideIcon } from "lucide-react";
|
|
import { Fragment, type ReactNode, useEffect, useMemo, useState } from "react";
|
|
import { Pagination, type PaginationProps } from "~/components/ui/pagination.tsx";
|
|
import { cn } from "~/lib/utils.ts";
|
|
import { groupRows, readCollapsed, toggleCollapsed, writeCollapsed } from "./data-table-groups.ts";
|
|
import { EmptyState, ErrorState, LoadingState } from "./empty-state.tsx";
|
|
import { useListPagination } from "./use-list-pagination.ts";
|
|
|
|
export type DataColumn<T> = {
|
|
/** 列 key(React key 用) */
|
|
key: string;
|
|
header: ReactNode;
|
|
cell: (row: T) => ReactNode;
|
|
/** 窄屏隐藏该列,避免横向溢出 */
|
|
hideBelow?: "sm" | "md" | "lg" | "xl";
|
|
align?: "left" | "right";
|
|
className?: string;
|
|
};
|
|
|
|
/** 分组:按键把行归组,组头可折叠并显示计数;给 storageKey 时在本浏览器记住折叠的组 */
|
|
export type DataGroupBy<T> = {
|
|
key: (row: T) => string;
|
|
/** 组头文字,缺省为 key */
|
|
label?: (key: string, rows: T[]) => ReactNode;
|
|
/** 组顺序,缺省按首次出现 */
|
|
order?: (a: string, b: string) => number;
|
|
storageKey?: string;
|
|
};
|
|
|
|
const HIDE: Record<NonNullable<DataColumn<unknown>["hideBelow"]>, string> = {
|
|
sm: "hidden sm:table-cell",
|
|
md: "hidden md:table-cell",
|
|
lg: "hidden lg:table-cell",
|
|
xl: "hidden xl:table-cell",
|
|
};
|
|
|
|
/**
|
|
* 数据表:内置 loading / error / empty 三态与统一分页。
|
|
* 外层自带 pg-slab 卡片(plain 时不带);表格在卡片内横向滚动,页面本身不溢出。
|
|
*
|
|
* <DataTable columns={cols} rows={q.data?.items} rowKey={(r) => r.id}
|
|
* loading={q.isPending} error={q.error} onRetry={q.refetch}
|
|
* empty={{ title: "还没有记录" }} onRowClick={(r) => open(r.id)}
|
|
* hasMore={!!next} onLoadMore={...} loadingMore={...} />
|
|
*/
|
|
export function DataTable<T>({
|
|
columns,
|
|
rows: allRows,
|
|
rowKey,
|
|
loading = false,
|
|
error,
|
|
onRetry,
|
|
empty,
|
|
onRowClick,
|
|
selectedKey,
|
|
hasMore = false,
|
|
onLoadMore,
|
|
loadingMore = false,
|
|
plain = false,
|
|
groupBy,
|
|
className,
|
|
pagination = true,
|
|
paginationKey,
|
|
}: {
|
|
columns: DataColumn<T>[];
|
|
rows: T[] | undefined;
|
|
rowKey: (row: T) => string;
|
|
loading?: boolean;
|
|
error?: unknown;
|
|
onRetry?: () => void;
|
|
empty?: { title: string; description?: ReactNode; icon?: LucideIcon; action?: ReactNode };
|
|
onRowClick?: (row: T) => void;
|
|
selectedKey?: string | null;
|
|
hasMore?: boolean;
|
|
onLoadMore?: () => void;
|
|
loadingMore?: boolean;
|
|
plain?: boolean;
|
|
groupBy?: DataGroupBy<T>;
|
|
className?: string;
|
|
pagination?: boolean | PaginationProps;
|
|
paginationKey?: string;
|
|
}) {
|
|
const paged = useListPagination(allRows, {
|
|
hasMore: pagination === true && hasMore,
|
|
onLoadMore,
|
|
loadingMore,
|
|
error,
|
|
resetKey: paginationKey ?? (allRows?.[0] ? rowKey(allRows[0]) : ""),
|
|
});
|
|
const rows = pagination === true ? paged.items : allRows;
|
|
const storageKey = groupBy?.storageKey;
|
|
const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set());
|
|
// 折叠态在挂载后读(服务端渲染时没有 localStorage,首屏一律展开)
|
|
useEffect(() => {
|
|
const saved = readCollapsed(storageKey);
|
|
if (saved) setCollapsed(saved);
|
|
}, [storageKey]);
|
|
const groupKey = groupBy?.key;
|
|
const groupOrder = groupBy?.order;
|
|
const groups = useMemo(
|
|
() => (groupKey && rows ? groupRows(rows, groupKey, groupOrder) : null),
|
|
[rows, groupKey, groupOrder],
|
|
);
|
|
const toggleGroup = (k: string) =>
|
|
setCollapsed((prev) => {
|
|
const next = toggleCollapsed(prev, k);
|
|
writeCollapsed(storageKey, next);
|
|
return next;
|
|
});
|
|
|
|
const renderRow = (row: T) => {
|
|
const key = rowKey(row);
|
|
return (
|
|
<tr
|
|
key={key}
|
|
onClick={onRowClick ? () => onRowClick(row) : undefined}
|
|
onKeyDown={
|
|
onRowClick
|
|
? (e) => {
|
|
if (e.key === "Enter" || e.key === " ") {
|
|
e.preventDefault();
|
|
onRowClick(row);
|
|
}
|
|
}
|
|
: undefined
|
|
}
|
|
tabIndex={onRowClick ? 0 : undefined}
|
|
aria-selected={selectedKey != null ? selectedKey === key : undefined}
|
|
className={cn(
|
|
"border-b border-border/60 transition-colors duration-micro last:border-b-0",
|
|
onRowClick && "cursor-pointer outline-none hover:bg-foreground/[0.04] focus-visible:bg-foreground/[0.06]",
|
|
selectedKey === key && "bg-foreground/[0.05]",
|
|
)}
|
|
>
|
|
{columns.map((c) => (
|
|
<td
|
|
key={c.key}
|
|
className={cn(
|
|
"px-4 py-2.5 align-middle",
|
|
c.align === "right" && "text-right",
|
|
c.hideBelow && HIDE[c.hideBelow],
|
|
c.className,
|
|
)}
|
|
>
|
|
{c.cell(row)}
|
|
</td>
|
|
))}
|
|
</tr>
|
|
);
|
|
};
|
|
|
|
let body: ReactNode;
|
|
if (loading && !rows) {
|
|
body = <LoadingState rows={5} className="p-4" />;
|
|
} else if (error && !rows) {
|
|
body = <ErrorState plain error={error} onRetry={onRetry} />;
|
|
} else if (!rows || rows.length === 0) {
|
|
body = (
|
|
<EmptyState
|
|
plain
|
|
icon={empty?.icon}
|
|
title={empty?.title ?? "暂无数据"}
|
|
description={empty?.description}
|
|
action={empty?.action}
|
|
className="py-12"
|
|
/>
|
|
);
|
|
} else {
|
|
body = (
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full text-left text-sm">
|
|
<thead>
|
|
<tr className="border-b border-border">
|
|
{columns.map((c) => (
|
|
<th
|
|
key={c.key}
|
|
scope="col"
|
|
className={cn(
|
|
"px-4 py-2.5 text-meta font-medium whitespace-nowrap text-muted-foreground",
|
|
c.align === "right" && "text-right",
|
|
c.hideBelow && HIDE[c.hideBelow],
|
|
c.className,
|
|
)}
|
|
>
|
|
{c.header}
|
|
</th>
|
|
))}
|
|
</tr>
|
|
</thead>
|
|
{groups ? (
|
|
groups.map((g) => {
|
|
const open = !collapsed.has(g.key);
|
|
return (
|
|
<Fragment key={`g:${g.key}`}>
|
|
<tbody>
|
|
<tr className="border-b border-border/60 bg-foreground/[0.02]">
|
|
<th scope="colgroup" colSpan={columns.length} className="p-0 text-left font-normal">
|
|
<button
|
|
type="button"
|
|
aria-expanded={open}
|
|
onClick={() => toggleGroup(g.key)}
|
|
className="flex w-full items-center gap-2 px-4 py-2 text-meta text-muted-foreground outline-none hover:text-foreground focus-visible:bg-foreground/[0.06]"
|
|
>
|
|
<ChevronRight
|
|
aria-hidden
|
|
className={cn(
|
|
"h-3.5 w-3.5 shrink-0 transition-transform duration-micro",
|
|
open && "rotate-90",
|
|
)}
|
|
/>
|
|
<span className="min-w-0 truncate font-medium text-foreground">
|
|
{groupBy?.label ? groupBy.label(g.key, g.rows) : g.key}
|
|
</span>
|
|
<span className="tabular-nums">{g.rows.length}</span>
|
|
</button>
|
|
</th>
|
|
</tr>
|
|
</tbody>
|
|
{open ? <tbody>{g.rows.map(renderRow)}</tbody> : null}
|
|
</Fragment>
|
|
);
|
|
})
|
|
) : (
|
|
<tbody>{rows.map(renderRow)}</tbody>
|
|
)}
|
|
</table>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className={cn("min-w-0 overflow-hidden rounded-xl", !plain && "pg-slab", className)}>
|
|
{body}
|
|
{error && allRows?.length ? (
|
|
<div className="px-4 py-2 text-meta text-destructive">{String((error as Error).message ?? error)}</div>
|
|
) : null}
|
|
{pagination && allRows ? (
|
|
<Pagination {...(typeof pagination === "object" ? pagination : paged.pagination)} />
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|