index.tsx 11.4 KB
import type { CSSProperties, ReactNode } from 'react';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { UButton, UTable, UTooltip, FillTable } from '@uj/ui';
import { PermButton } from '@/access';
import type { ActionSchema } from '../formSchema';

/** 列表分页统一默认每页条数。 */
export const DEFAULT_PAGE_SIZE = 10;

/** 表格列扩展:line 为 1 时单行省略并显示完整提示;大于 1 时按指定行数截断。 */
export type DataTableColumn<T> = ColumnsType<T>[number] & { line?: number };
export type DataTableColumnsType<T> = DataTableColumn<T>[];

/** 通用行选择配置,兼容原生受控选中值、回调和逐行禁用。 */
export interface DataTableRowSelection<T> extends NonNullable<TableProps<T>['rowSelection']> {
  /** 暂停整组选择交互,保留已有勾选,适用于请求或批量操作期间。 */
  disabled?: boolean;
}

/** 列表行操作配置;配置 permission 时自动使用权限按钮。 */
export interface RowActionSchema<T> extends Omit<ActionSchema, 'danger' | 'label' | 'onClick'> {
  /** 可按当前行动态生成操作文案。 */
  label: ReactNode | ((record: T) => ReactNode);
  /** 可按当前行动态决定是否使用警示颜色。 */
  danger?: boolean | ((record: T) => boolean);
  onClick: (record: T) => void;
  visible?: (record: T) => boolean;
}

export interface DataTableProps<T> extends Pick<
  TableProps<T>,
  'dataSource' | 'loading' | 'rowKey' | 'onChange' | 'scroll' | 'size' | 'locale' | 'className'
> {
  columns: DataTableColumnsType<T>;
  /** true 开启默认多选,false/省略关闭;对象可配置受控选择与禁用规则。 */
  rowSelection?: boolean | DataTableRowSelection<T>;
  showIndex?: boolean;
  pagination?:
    | {
        current: number;
        /** 每页条数,默认 10。 */
        pageSize?: number;
        total: number;
        onChange: (page: number, pageSize: number) => void;
        /** 是否展示每页条数选择,默认展示。 */
        showSizeChanger?: boolean;
        /** 每页条数选择项,默认 10 / 20 / 50 / 100。 */
        pageSizeOptions?: (string | number)[];
        /** 默认展示总数;false 隐藏,也可传入自定义文案。 */
        showTotal?: boolean | ((total: number, range: [number, number]) => ReactNode);
      }
    | false;
  actions?: ActionSchema[];
  /** 行内操作。配置 permission 时自动按权限显示,未配置则使用普通按钮。 */
  rowActions?: RowActionSchema<T>[];
  /** 行内操作列标题,默认“操作”。 */
  actionColumnTitle?: ReactNode;
  /** 行内操作列宽度。 */
  actionColumnWidth?: number;
  actionColumnFixed?: 'left' | 'right';
  toolbarClassName?: string;
  toolbarTitle?: ReactNode;
  fillHeight?: boolean;
  /** 接口返回的分页对象;传入后自动从 recordsKey 读取列表数据。 */
  pageData?: Record<string, unknown>;
  /** 分页对象中的列表字段名,默认 records。 */
  recordsKey?: string;
  /** 分页对象中的总数、页码和每页条数字段名。 */
  totalKey?: string;
  currentKey?: string;
  sizeKey?: string;
}
export function DataTable<T extends object>({
  columns,
  showIndex,
  pagination,
  actions,
  rowActions,
  rowSelection,
  actionColumnTitle = '操作',
  actionColumnWidth,
  actionColumnFixed = 'right',
  toolbarClassName,
  toolbarTitle,
  fillHeight = false,
  pageData,
  recordsKey = 'records',
  totalKey = 'total',
  currentKey = 'current',
  sizeKey = 'size',
  ...props
}: DataTableProps<T>) {
  const records = pageData?.[recordsKey];
  const dataSource = Array.isArray(records) ? (records as T[]) : props.dataSource;
  const { disabled, getCheckboxProps, getTitleCheckboxProps, ...selectionOptions } =
    typeof rowSelection === 'object' ? rowSelection : {};
  const resolvedSelection: TableProps<T>['rowSelection'] = rowSelection
    ? {
        type: 'checkbox',
        fixed: 'left',
        columnWidth: 48,
        preserveSelectedRowKeys: false,
        ...selectionOptions,
        selections: disabled ? false : selectionOptions.selections,
        getCheckboxProps: (record) => {
          const checkboxProps = getCheckboxProps?.(record);
          return { ...checkboxProps, disabled: disabled || checkboxProps?.disabled };
        },
        getTitleCheckboxProps: () => {
          const checkboxProps = getTitleCheckboxProps?.();
          return { ...checkboxProps, disabled: disabled || checkboxProps?.disabled };
        },
      }
    : undefined;
  const resolvedPagination = pagination
    ? {
        ...pagination,
        current: Number(pageData?.[currentKey] ?? pagination.current),
        pageSize: Number(pageData?.[sizeKey] ?? pagination.pageSize ?? DEFAULT_PAGE_SIZE),
        total: Number(pageData?.[totalKey] ?? pagination.total),
      }
    : pagination;
  const page = resolvedPagination || undefined;
  const renderActionButton = (
    action: Omit<ActionSchema, 'onClick'>,
    onClick: () => void,
    key: string,
    isRowAction = false,
    style?: CSSProperties,
  ) => {
    const type = action.type ?? (isRowAction ? ('text' as const) : undefined);
    const buttonProps = {
      danger: action.danger,
      disabled: action.disabled,
      onClick,
      type,
      style:
        isRowAction && type === 'text'
          ? {
              color: action.danger ? 'var(--ant-color-error)' : 'var(--ant-color-primary)',
              ...style,
            }
          : style,
    };

    return action.permission ? (
      <PermButton key={key} permission={action.permission} {...buttonProps}>
        {action.label}
      </PermButton>
    ) : (
      <UButton key={key} {...buttonProps}>
        {action.label}
      </UButton>
    );
  };
  const actionColumn: ColumnsType<T>[number] | undefined = rowActions?.length
    ? {
        title: actionColumnTitle,
        key: '__actions',
        width: actionColumnWidth,
        fixed: actionColumnFixed,
        render: (_: unknown, record: T) => {
          const visibleActions = rowActions.filter((action) => action.visible?.(record) ?? true);
          const lastPermissionActionIndex = visibleActions.reduce(
            (lastIndex, action, index) => (action.permission ? index : lastIndex),
            -1,
          );
          return visibleActions.map((action, index) => {
            const label = typeof action.label === 'function' ? action.label(record) : action.label;
            const danger =
              typeof action.danger === 'function' ? action.danger(record) : action.danger;
            return renderActionButton(
              { ...action, danger, label },
              () => action.onClick(record),
              `row-action-${index}`,
              true,
              action.permission && index < lastPermissionActionIndex
                ? { marginRight: 8 }
                : undefined,
            );
          });
        },
      }
    : undefined;
  const sourceColumns: DataTableColumnsType<T> = showIndex
    ? [
        {
          title: '序号',
          key: '__index',
          width: 72,
          render: (_: unknown, _row: T, index: number) =>
            ((page?.current ?? 1) - 1) * (page?.pageSize ?? 0) + index + 1,
        },
        ...columns,
        ...(actionColumn ? [actionColumn] : []),
      ]
    : [...columns, ...(actionColumn ? [actionColumn] : [])];
  const hasLineLimit = hasLineConfigured(sourceColumns);
  const minTableWidth = getMinimumTableWidth(sourceColumns);
  const tableColumns = withLineLimit(sourceColumns);
  const TableComponent = fillHeight ? FillTable<T> : UTable<T>;
  return (
    <>
      {toolbarTitle || actions?.length ? (
        <div
          className={toolbarClassName}
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            flexWrap: 'wrap',
            gap: 12,
            padding: 16,
          }}
        >
          <div>{toolbarTitle}</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {actions?.map((action, index) =>
              renderActionButton(action, action.onClick, `toolbar-action-${index}`),
            )}
          </div>
        </div>
      ) : null}
      <TableComponent
        {...props}
        dataSource={dataSource}
        columns={tableColumns}
        tableLayout={hasLineLimit ? 'fixed' : undefined}
        rowSelection={resolvedSelection}
        scroll={{ ...props.scroll, x: props.scroll?.x ?? minTableWidth }}
        styles={{
          header: { cell: { paddingLeft: 20 } },
          body: { cell: { paddingLeft: 20 } },
        }}
        pagination={
          resolvedPagination === false
            ? false
            : resolvedPagination && {
                ...resolvedPagination,
                current: resolvedPagination.current,
                pageSize: resolvedPagination.pageSize,
                total: resolvedPagination.total,
                onChange: resolvedPagination.onChange,
                showSizeChanger: resolvedPagination.showSizeChanger ?? true,
                pageSizeOptions: resolvedPagination.pageSizeOptions ?? [10, 20, 50, 100],
                showTotal:
                  typeof resolvedPagination.showTotal === 'function'
                    ? resolvedPagination.showTotal
                    : resolvedPagination.showTotal === false
                      ? undefined
                      : (total: number) => `共 ${total} 条`,
              }
        }
      />
    </>
  );
}

function hasLineConfigured<T extends object>(columns: ColumnsType<T>): boolean {
  return columns.some((column) => {
    const customColumn = column as DataTableColumn<T>;
    return (
      Boolean(customColumn.line) ||
      ('children' in column &&
        Boolean(column.children?.length) &&
        hasLineConfigured(column.children))
    );
  });
}

function getMinimumTableWidth<T extends object>(columns: ColumnsType<T>): number {
  return columns.reduce((width, column) => {
    if ('children' in column && column.children) {
      return width + getMinimumTableWidth(column.children);
    }
    return width + (typeof column.width === 'number' ? column.width : 120);
  }, 0);
}

function withLineLimit<T extends object>(columns: DataTableColumnsType<T>): ColumnsType<T> {
  return columns.map((column) => {
    if ('children' in column && column.children) {
      return { ...column, children: withLineLimit(column.children as DataTableColumnsType<T>) };
    }
    if (!column.line || column.line < 1) return column;
    const { line, render, ...rest } = column;
    return {
      ...rest,
      render: (value: unknown, record: T, index: number) => {
        const content = toCellContent(render?.(value, record, index), value);
        const title =
          typeof value === 'string' || typeof value === 'number' ? String(value) : content;
        return (
          <UTooltip title={title}>
            <span style={lineStyle(line)}>{content}</span>
          </UTooltip>
        );
      },
    };
  });
}

function toCellContent(rendered: unknown, fallback: unknown): ReactNode {
  if (rendered && typeof rendered === 'object' && 'children' in rendered && 'props' in rendered) {
    return (rendered as { children: ReactNode }).children;
  }
  return (rendered ?? fallback) as ReactNode;
}

function lineStyle(line: number): CSSProperties {
  if (line === 1)
    return { display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' };
  return {
    display: '-webkit-box',
    overflow: 'hidden',
    WebkitBoxOrient: 'vertical',
    WebkitLineClamp: line,
    whiteSpace: 'pre-wrap',
    overflowWrap: 'anywhere',
  };
}