You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

1230 lines
38 KiB

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import RcTable from 'rc-table';
import * as PropTypes from 'prop-types';
import classNames from 'classnames';
import shallowEqual from 'shallowequal';
import FilterDropdown from './filterDropdown';
import createStore, { Store } from './createStore';
import SelectionBox from './SelectionBox';
import SelectionCheckboxAll from './SelectionCheckboxAll';
import Column from './Column';
import ColumnGroup from './ColumnGroup';
import createBodyRow from './createBodyRow';
import { flatArray, treeMap, flatFilter, normalizeColumns } from './util';
import {
TableProps,
TableSize,
TableState,
TableComponents,
RowSelectionType,
TableLocale,
AdditionalCellProps,
ColumnProps,
CompareFn,
SortOrder,
TableStateFilters,
SelectionItemSelectFn,
SelectionInfo,
TableSelectWay,
TableRowSelection,
PaginationConfig,
PrepareParamsArgumentsReturn,
} from './interface';
import Pagination from '../pagination';
import Icon from '../icon';
import Spin, { SpinProps } from '../spin';
import { RadioChangeEvent } from '../radio';
import { CheckboxChangeEvent } from '../checkbox';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
import { ConfigConsumer, ConfigConsumerProps, RenderEmptyHandler } from '../config-provider';
import warning from '../_util/warning';
function noop() {}
function stopPropagation(e: React.SyntheticEvent<any>) {
e.stopPropagation();
if (e.nativeEvent.stopImmediatePropagation) {
e.nativeEvent.stopImmediatePropagation();
}
}
function getRowSelection<T>(props: TableProps<T>): TableRowSelection<T> {
return props.rowSelection || {};
}
const defaultPagination = {
onChange: noop,
onShowSizeChange: noop,
};
const ROW_SELECTION_COLUMN_WIDTH = '62px';
/**
* Avoid creating new object, so that parent component's shouldComponentUpdate
* can works appropriately。
*/
const emptyObject = {};
export default class Table<T> extends React.Component<TableProps<T>, TableState<T>> {
static Column = Column;
static ColumnGroup = ColumnGroup;
static propTypes = {
dataSource: PropTypes.array,
columns: PropTypes.array,
prefixCls: PropTypes.string,
useFixedHeader: PropTypes.bool,
rowSelection: PropTypes.object,
className: PropTypes.string,
size: PropTypes.string as PropTypes.Requireable<TableSize>,
loading: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
bordered: PropTypes.bool,
onChange: PropTypes.func,
locale: PropTypes.object,
dropdownPrefixCls: PropTypes.string,
sortDirections: PropTypes.array,
};
static defaultProps = {
dataSource: [],
useFixedHeader: false,
className: '',
size: 'default' as TableSize,
loading: false,
bordered: false,
indentSize: 20,
locale: {},
rowKey: 'key',
showHeader: true,
sortDirections: ['ascend', 'descend'],
};
CheckboxPropsCache: {
[key: string]: any;
};
store: Store;
columns: ColumnProps<T>[];
components: TableComponents;
row: React.ComponentType<any>;
constructor(props: TableProps<T>) {
super(props);
warning(
!('columnsPageRange' in props || 'columnsPageSize' in props),
'Table',
'`columnsPageRange` and `columnsPageSize` are removed, please use ' +
'fixed columns instead, see: https://u.ant.design/fixed-columns.',
);
warning(
!('expandedRowRender' in props) || !('scroll' in props),
'Table',
'`expandedRowRender` and `scroll` are not compatible. Please use one of them at one time.',
);
this.columns = props.columns || normalizeColumns(props.children as React.ReactChildren);
this.createComponents(props.components);
this.state = {
...this.getDefaultSortOrder(this.columns),
// 减少状态
filters: this.getFiltersFromColumns(),
pagination: this.getDefaultPagination(props),
pivot: undefined,
};
this.CheckboxPropsCache = {};
this.store = createStore({
selectedRowKeys: getRowSelection(props).selectedRowKeys || [],
selectionDirty: false,
});
}
getCheckboxPropsByItem = (item: T, index: number) => {
const rowSelection = getRowSelection(this.props);
if (!rowSelection.getCheckboxProps) {
return {};
}
const key = this.getRecordKey(item, index);
// Cache checkboxProps
if (!this.CheckboxPropsCache[key]) {
const checkboxProps = (this.CheckboxPropsCache[key] = rowSelection.getCheckboxProps(item));
warning(
!('checked' in checkboxProps) && !('defaultChecked' in checkboxProps),
'Table',
'Do not set `checked` or `defaultChecked` in `getCheckboxProps`. Please use `selectedRowKeys` instead.',
);
}
return this.CheckboxPropsCache[key];
};
getDefaultSelection() {
const rowSelection = getRowSelection(this.props);
if (!rowSelection.getCheckboxProps) {
return [];
}
return this.getFlatData()
.filter((item: T, rowIndex) => this.getCheckboxPropsByItem(item, rowIndex).defaultChecked)
.map((record, rowIndex) => this.getRecordKey(record, rowIndex));
}
getDefaultPagination(props: TableProps<T>) {
const pagination: PaginationConfig =
typeof props.pagination === 'object' ? props.pagination : {};
let current;
if ('current' in pagination) {
current = pagination.current;
} else if ('defaultCurrent' in pagination) {
current = pagination.defaultCurrent;
}
let pageSize;
if ('pageSize' in pagination) {
pageSize = pagination.pageSize;
} else if ('defaultPageSize' in pagination) {
pageSize = pagination.defaultPageSize;
}
return this.hasPagination(props)
? {
...defaultPagination,
...pagination,
current: current || 1,
pageSize: pageSize || 10,
}
: {};
}
componentWillReceiveProps(nextProps: TableProps<T>) {
this.columns = nextProps.columns || normalizeColumns(nextProps.children as React.ReactChildren);
if ('pagination' in nextProps || 'pagination' in this.props) {
this.setState(previousState => {
const newPagination = {
...defaultPagination,
...previousState.pagination,
...nextProps.pagination,
};
newPagination.current = newPagination.current || 1;
newPagination.pageSize = newPagination.pageSize || 10;
return { pagination: nextProps.pagination !== false ? newPagination : emptyObject };
});
}
if (nextProps.rowSelection && 'selectedRowKeys' in nextProps.rowSelection) {
this.store.setState({
selectedRowKeys: nextProps.rowSelection.selectedRowKeys || [],
});
} else if (this.props.rowSelection && !nextProps.rowSelection) {
this.store.setState({
selectedRowKeys: [],
});
}
if ('dataSource' in nextProps && nextProps.dataSource !== this.props.dataSource) {
this.store.setState({
selectionDirty: false,
});
}
// https://github.com/ant-design/ant-design/issues/10133
this.CheckboxPropsCache = {};
if (this.getSortOrderColumns(this.columns).length > 0) {
const sortState = this.getSortStateFromColumns(this.columns);
if (
sortState.sortColumn !== this.state.sortColumn ||
sortState.sortOrder !== this.state.sortOrder
) {
this.setState(sortState);
}
}
const filteredValueColumns = this.getFilteredValueColumns(this.columns);
if (filteredValueColumns.length > 0) {
const filtersFromColumns = this.getFiltersFromColumns(this.columns);
const newFilters = { ...this.state.filters };
Object.keys(filtersFromColumns).forEach(key => {
newFilters[key] = filtersFromColumns[key];
});
if (this.isFiltersChanged(newFilters)) {
this.setState({ filters: newFilters });
}
}
this.createComponents(nextProps.components, this.props.components);
}
onRow = (prefixCls: string, record: T, index: number) => {
const { onRow } = this.props;
const custom = onRow ? onRow(record, index) : {};
return {
...custom,
prefixCls,
store: this.store,
rowKey: this.getRecordKey(record, index),
};
};
setSelectedRowKeys(selectedRowKeys: string[], selectionInfo: SelectionInfo<T>) {
const { selectWay, record, checked, changeRowKeys, nativeEvent } = selectionInfo;
const rowSelection = getRowSelection(this.props);
if (rowSelection && !('selectedRowKeys' in rowSelection)) {
this.store.setState({ selectedRowKeys });
}
const data = this.getFlatData();
if (!rowSelection.onChange && !rowSelection[selectWay]) {
return;
}
const selectedRows = data.filter(
(row, i) => selectedRowKeys.indexOf(this.getRecordKey(row, i)) >= 0,
);
if (rowSelection.onChange) {
rowSelection.onChange(selectedRowKeys, selectedRows);
}
if (selectWay === 'onSelect' && rowSelection.onSelect) {
rowSelection.onSelect(record!, checked!, selectedRows, nativeEvent!);
} else if (selectWay === 'onSelectMultiple' && rowSelection.onSelectMultiple) {
const changeRows = data.filter(
(row, i) => changeRowKeys!.indexOf(this.getRecordKey(row, i)) >= 0,
);
rowSelection.onSelectMultiple(checked!, selectedRows, changeRows);
} else if (selectWay === 'onSelectAll' && rowSelection.onSelectAll) {
const changeRows = data.filter(
(row, i) => changeRowKeys!.indexOf(this.getRecordKey(row, i)) >= 0,
);
rowSelection.onSelectAll(checked!, selectedRows, changeRows);
} else if (selectWay === 'onSelectInvert' && rowSelection.onSelectInvert) {
rowSelection.onSelectInvert(selectedRowKeys);
}
}
hasPagination(props?: any) {
return (props || this.props).pagination !== false;
}
isFiltersChanged(filters: TableStateFilters) {
let filtersChanged = false;
if (Object.keys(filters).length !== Object.keys(this.state.filters).length) {
filtersChanged = true;
} else {
Object.keys(filters).forEach(columnKey => {
if (filters[columnKey] !== this.state.filters[columnKey]) {
filtersChanged = true;
}
});
}
return filtersChanged;
}
getSortOrderColumns(columns?: ColumnProps<T>[]) {
return flatFilter(
columns || this.columns || [],
(column: ColumnProps<T>) => 'sortOrder' in column,
);
}
getFilteredValueColumns(columns?: ColumnProps<T>[]) {
return flatFilter(
columns || this.columns || [],
(column: ColumnProps<T>) => typeof column.filteredValue !== 'undefined',
);
}
getFiltersFromColumns(columns?: ColumnProps<T>[]) {
const filters: any = {};
this.getFilteredValueColumns(columns).forEach((col: ColumnProps<T>) => {
const colKey = this.getColumnKey(col) as string;
filters[colKey] = col.filteredValue;
});
return filters;
}
getDefaultSortOrder(columns?: ColumnProps<T>[]) {
const definedSortState = this.getSortStateFromColumns(columns);
const defaultSortedColumn = flatFilter(
columns || [],
(column: ColumnProps<T>) => column.defaultSortOrder != null,
)[0];
if (defaultSortedColumn && !definedSortState.sortColumn) {
return {
sortColumn: defaultSortedColumn,
sortOrder: defaultSortedColumn.defaultSortOrder,
};
}
return definedSortState;
}
getSortStateFromColumns(columns?: ColumnProps<T>[]) {
// return first column which sortOrder is not falsy
const sortedColumn = this.getSortOrderColumns(columns).filter(
(col: ColumnProps<T>) => col.sortOrder,
)[0];
if (sortedColumn) {
return {
sortColumn: sortedColumn