import * as React from "react"; import { cn } from "@/lib/utils"; interface TableClassNames { th?: string; td?: string; tr?: string; wrapper?: string; } interface TableStyleContextValue { thClassName?: string; tdClassName?: string; trClassName?: string; } const TableStyleContext = React.createContext({}); export interface TableProps extends React.ComponentProps<"table"> { classNames?: TableClassNames; } export function Table({ children, className, classNames, ...props }: TableProps) { return (
{children}
); } export function TableHeader({ children, className, ...props }: React.ComponentProps<"thead">) { const childArray = React.Children.toArray(children); const hasRow = childArray.some( (child) => React.isValidElement(child) && child.type === TableRow, ); return ( {hasRow ? children : {children}} ); } interface TableBodyProps extends Omit, "children"> { children?: React.ReactNode | ((item: T) => React.ReactNode); emptyContent?: React.ReactNode; isLoading?: boolean; items?: T[]; loadingContent?: React.ReactNode; } export const TableBody = React.forwardRef< HTMLTableSectionElement, TableBodyProps >(function TableBody( { children, className, emptyContent, isLoading, items, loadingContent, ...props }: TableBodyProps, ref: React.Ref, ) { if (isLoading) { return ( {loadingContent ?? "加载中..."} ); } if (items && typeof children === "function") { if (items.length === 0) { return ( {emptyContent ?? "暂无数据"} ); } return ( {items.map((item) => { const key = typeof item === "object" && item !== null && "id" in item ? String((item as { id: React.Key }).id) : JSON.stringify(item); return {children(item)}; })} ); } const staticChildren = typeof children === "function" ? [] : React.Children.toArray(children); if (staticChildren.length === 0) { return ( {emptyContent ?? "暂无数据"} ); } return ( {typeof children === "function" ? null : children} ); }); export function TableColumn({ className, ...props }: React.ComponentProps<"th">) { const { thClassName } = React.useContext(TableStyleContext); return ( ); } export const TableRow = React.forwardRef< HTMLTableRowElement, React.ComponentProps<"tr"> >(({ className, ...props }, ref) => { const { trClassName } = React.useContext(TableStyleContext); return ( ); }); TableRow.displayName = "TableRow"; export function TableCell({ className, ...props }: React.ComponentProps<"td">) { const { tdClassName } = React.useContext(TableStyleContext); return ( ); }