Table.tsx 4.35 KB
import { isValidElement, type ReactNode } from 'react';

import styles from './Shared.module.css';
import { Empty, type EmptyProps } from './Navigation';

export interface TableColumn<T extends Record<string, unknown>> {
  title: ReactNode;
  dataIndex?: keyof T;
  key?: string;
  sorter?: boolean;
  render?: (value: unknown, record: T, index: number) => ReactNode;
}

export interface TableProps<T extends Record<string, unknown>> {
  /** rowKey 固定每行身份,是列表选择、更新和测试定位的基础。 */
  rowKey: keyof T | ((record: T) => string);
  columns: Array<TableColumn<T>>;
  dataSource: T[];
  loading?: boolean;
  /** empty 是表格空数据时的统一插槽;新代码优先使用它承载说明、操作或完整自定义节点。 */
  empty?: ReactNode | EmptyProps;
  /** emptyText 保留兼容早期纯文本空状态,后续业务建议迁移到 empty。 */
  emptyText?: ReactNode;
  rowSelection?: {
    selectedRowKeys: string[];
    onChange?: (keys: string[], rows: T[]) => void;
  };
  onSort?: (key: string, order: 'ascend' | 'descend') => void;
}

function getKey<T extends Record<string, unknown>>(rowKey: TableProps<T>['rowKey'], record: T) {
  return typeof rowKey === 'function' ? rowKey(record) : String(record[rowKey]);
}

function isEmptyConfig(empty: TableProps<Record<string, unknown>>['empty']): empty is EmptyProps {
  return Boolean(empty && typeof empty === 'object' && !Array.isArray(empty) && !isValidElement(empty));
}

function renderEmptyState(empty: TableProps<Record<string, unknown>>['empty'], emptyText: ReactNode) {
  if (isEmptyConfig(empty)) {
    return <Empty {...empty} />;
  }

  return empty ?? <Empty description={emptyText} />;
}

export function Table<T extends Record<string, unknown>>({ columns, dataSource, empty, emptyText = '暂无数据', loading, rowKey, rowSelection, onSort }: TableProps<T>) {
  if (loading) {
    return <div role="status" aria-label="表格加载中" className={styles.panel}>加载中...</div>;
  }

  return (
    <table className={styles.table}>
      <thead>
        <tr>
          {rowSelection ? <th>选择</th> : null}
          {columns.map((column) => {
            const key = String(column.key ?? column.dataIndex ?? column.title);
            return (
              <th key={key} scope="col">
                {column.sorter ? (
                  <button className={styles.sortButton} type="button" aria-label={`按${column.title}排序`} onClick={() => onSort?.(key, 'ascend')}>
                    {column.title}
                  </button>
                ) : (
                  column.title
                )}
              </th>
            );
          })}
        </tr>
      </thead>
      <tbody>
        {dataSource.length === 0 ? (
          <tr>
            <td className={styles.tableEmptyCell} colSpan={columns.length + (rowSelection ? 1 : 0)}>
              <div role="status" aria-label="表格空状态" className={styles.tableEmpty}>
                {renderEmptyState(empty, emptyText)}
              </div>
            </td>
          </tr>
        ) : null}
        {dataSource.map((record, rowIndex) => {
          const key = getKey(rowKey, record);
          const selected = rowSelection?.selectedRowKeys.includes(key) ?? false;
          return (
            <tr key={key}>
              {rowSelection ? (
                <td>
                  <input
                    aria-label={`选择${String(record.name ?? key)}`}
                    checked={selected}
                    type="checkbox"
                    onChange={() => {
                      const nextKeys = selected ? rowSelection.selectedRowKeys.filter((item) => item !== key) : [...rowSelection.selectedRowKeys, key];
                      const nextRows = dataSource.filter((item) => nextKeys.includes(getKey(rowKey, item)));
                      rowSelection.onChange?.(nextKeys, nextRows);
                    }}
                  />
                </td>
              ) : null}
              {columns.map((column, columnIndex) => {
                const columnKey = String(column.key ?? column.dataIndex ?? columnIndex);
                const value = column.dataIndex ? record[column.dataIndex] : undefined;
                return <td key={columnKey}>{column.render ? column.render(value, record, rowIndex) : String(value ?? '')}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}