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

/** 列表行操作配置;配置 permission 时自动使用权限按钮。 */
export interface RowActionSchema<T> extends Omit<ActionSchema, 'onClick'> {
  onClick: (record: T) => void;
  visible?: (record: T) => boolean;
}

export interface DataTableProps<T> extends Pick<
  TableProps<T>,
  | 'dataSource'
  | 'loading'
  | 'rowKey'
  | 'rowSelection'
  | 'onChange'
  | 'scroll'
  | 'size'
  | 'locale'
  | 'className'
> {
  columns: ColumnsType<T>;
  showIndex?: boolean;
  pagination?:
    | {
        current: number;
        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,
  actionColumnTitle = '操作',
  actionColumnWidth,
  actionColumnFixed,
  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 resolvedPagination = pagination
    ? {
        ...pagination,
        current: Number(pageData?.[currentKey] ?? pagination.current),
        pageSize: Number(pageData?.[sizeKey] ?? pagination.pageSize),
        total: Number(pageData?.[totalKey] ?? pagination.total),
      }
    : pagination;
  const page = resolvedPagination || undefined;
  const renderActionButton = (
    action: Omit<ActionSchema, 'onClick'>,
    onClick: () => void,
    key: string,
    isRowAction = false,
  ) => {
    const buttonProps = {
      danger: action.danger,
      disabled: action.disabled,
      onClick,
      type: action.type ?? (isRowAction ? ('link' as const) : undefined),
    };

    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) =>
          rowActions
            .filter((action) => action.visible?.(record) ?? true)
            .map((action, index) =>
              renderActionButton(action, () => action.onClick(record), `row-action-${index}`, true),
            ),
      }
    : undefined;
  const tableColumns = 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 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}
        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} 条`,
              }
        }
      />
    </>
  );
}