BusinessTable.tsx 6.05 KB
import { useMemo } from 'react';
import type { ReactElement, ReactNode } from 'react';
import { CloseCircleIcon, SearchIcon } from 'tdesign-icons-react';
import { Button, Empty, Pagination, Table, Tooltip, Typography, type EmptyProps, type PaginationProps, type PrimaryTableCol, type TableProps, type TableRowData } from 'tdesign-react';

import { classNames } from '../shared/classNames';
import styles from './BusinessTable.module.css';

const { Text } = Typography;

export type BusinessTableColumn<T extends TableRowData> = PrimaryTableCol<T> & {
  ellipsisTooltip?: boolean;
  tooltipValue?: (row: T) => string | number | boolean | null | undefined;
};

export interface BusinessTableEmptyStateConfig {
  onAction?: () => void;
}

export interface BusinessTableErrorStateConfig {
  kind?: 'offline' | 'forbidden';
  onRetry?: () => void;
}

export interface BusinessTableProps<T extends TableRowData>
  extends Omit<TableProps<T>, 'columns' | 'data' | 'rowKey' | 'empty' | 'pagination'> {
  columns: BusinessTableColumn<T>[];
  data: T[];
  rowKey: TableProps<T>['rowKey'];
  hasFilter?: boolean;
  error?: boolean;
  filteredEmptyState?: BusinessTableEmptyStateConfig;
  errorState?: BusinessTableErrorStateConfig;
  pagination?: PaginationProps | false;
  totalLabel?: ReactNode;
  tableClassName?: string;
}

function createActionButton(
  label: ReactNode,
  onClick?: () => void,
  variant: 'base' | 'text' = 'base',
) : ReactElement | undefined {
  if (!onClick || !label) return undefined;

  return (
    <Button theme="primary" variant={variant} onClick={onClick}>
      {label}
    </Button>
  );
}

function createEmptyNode({
  action,
  description,
  image,
  title,
  type,
}: {
  action?: ReactElement;
  description?: ReactNode;
  image?: ReactNode;
  title: ReactNode;
  type?: EmptyProps['type'];
}) {
  return (
    <div className={styles.emptyState}>
      <Empty
        action={action}
        description={description}
        image={image}
        title={title}
        type={type ?? 'empty'}
      />
    </div>
  );
}

const stateIconProps = {
  className: styles.stateIcon,
  size: '64px',
  strokeWidth: 2,
};

const defaultLoadingProps = {
  className: styles.businessTableLoading,
  delay: 120,
  showOverlay: true,
  size: '20px',
  text: '加载中',
} satisfies TableProps<TableRowData>['loadingProps'];

function isPlainTextValue(value: unknown): value is string | number | boolean {
  return ['string', 'number', 'boolean'].includes(typeof value);
}

function renderPlainTextCell<T extends TableRowData>(
  row: T,
  column: BusinessTableColumn<T>,
): ReactNode {
  const value = column.tooltipValue
    ? column.tooltipValue(row)
    : row[column.colKey as keyof T];
  if (value === undefined || value === null) return '-';
  if (!isPlainTextValue(value)) return value as ReactNode;

  const text = String(value);
  const normalizedText = text.trim();
  if (!normalizedText || normalizedText === '-') return '-';

  return (
    <Tooltip
      content={(
        <span
          className={styles.cellTooltipContent}
          style={{ width: 200, maxWidth: 200, whiteSpace: 'normal' }}
        >
          {text}
        </span>
      )}
    >
      <span className={styles.cellText}>{text}</span>
    </Tooltip>
  );
}

function withPlainTextTooltipColumns<T extends TableRowData>(
  columns: BusinessTableColumn<T>[],
): BusinessTableColumn<T>[] {
  return columns.map((column) => {
    if (!column.ellipsisTooltip || column.cell) return column;

    const { ellipsisTooltip, tooltipValue, ...tableColumn } = column;

    return {
      ...tableColumn,
      cell: ({ row }) => renderPlainTextCell(row, column),
    };
  });
}

const errorStatePresets: Record<NonNullable<BusinessTableErrorStateConfig['kind']>, {
  actionText?: string;
  description?: string;
  icon?: ReactElement;
  title: string;
  type?: EmptyProps['type'];
}> = {
  offline: {
    title: '请求失败',
    type: 'fail',
  },
  forbidden: {
    actionText: '申请权限',
    description: '当前账号暂无访问权限',
    icon: <CloseCircleIcon {...stateIconProps} />,
    title: '权限受限',
  },
};

export function BusinessTable<T extends TableRowData>({
  columns,
  data,
  error = false,
  errorState,
  filteredEmptyState,
  hasFilter = false,
  loadingProps,
  pagination,
  rowKey,
  tableClassName,
  totalLabel,
  ...tableProps
}: BusinessTableProps<T>) {
  if (error) {
    const errorPreset = errorStatePresets[errorState?.kind ?? 'offline'];

    return (
      <div className={styles.root}>
        {createEmptyNode({
          action: createActionButton(errorPreset.actionText, errorState?.onRetry, 'base'),
          description: errorPreset.description,
          image: errorPreset.icon,
          title: errorPreset.title,
          type: errorPreset.type,
        })}
      </div>
    );
  }

  const isEmpty = data.length === 0;
  const isLoading = Boolean(tableProps.loading);
  const displayColumns = useMemo(() => withPlainTextTooltipColumns(columns), [columns]);
  const mergedLoadingProps = isLoading
    ? {
        ...defaultLoadingProps,
        ...loadingProps,
        className: classNames(defaultLoadingProps.className, loadingProps?.className),
      }
    : loadingProps;
  const emptyNode = isEmpty
    && !isLoading
    ? hasFilter
      ? createEmptyNode({
          image: <SearchIcon {...stateIconProps} />,
          title: '未找到匹配结果',
        })
      : createEmptyNode({
        title: '暂无数据',
        type: 'empty',
      })
    : undefined;

  return (
    <div className={classNames(styles.root, tableProps.className)}>
      <Table
        {...tableProps}
        className={classNames(styles.table, tableClassName)}
        columns={displayColumns}
        data={data}
        empty={emptyNode}
        loadingProps={mergedLoadingProps}
        rowKey={rowKey}
      />
      {pagination || totalLabel ? (
        <div className={styles.footer}>
          {!pagination && totalLabel ? <Text className={styles.totalLabel}>{totalLabel}</Text> : <span />}
          {pagination ? <Pagination className={styles.pagination} {...pagination} /> : null}
        </div>
      ) : null}
    </div>
  );
}