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.
 
 

1076 lines
33 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 Pagination from '../pagination';
import Icon from '../icon';
import Spin from '../spin';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
import warning from '../_util/warning';
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 { SpinProps } from '../spin';
import {
TableProps,
TableSize,
TableState,
TableComponents,
RowSelectionType,
TableLocale,
ColumnProps,
CompareFn,
TableStateFilters,
SelectionItemSelectFn,
SelectionInfo,
TableSelectWay,
TableRowSelection,
PaginationConfig,
} from './interface';
import { RadioChangeEvent } from '../radio';
import { CheckboxChangeEvent } from '../checkbox';
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,
};
/**
* 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,
loading: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.object,
]),
bordered: PropTypes.bool,
onChange: PropTypes.func,
locale: PropTypes.object,
dropdownPrefixCls: PropTypes.string,
};
static defaultProps = {
dataSource: [],
prefixCls: 'ant-table',
useFixedHeader: false,
className: '',
size: 'default' as TableSize,
loading: false,
bordered: false,
indentSize: 20,
locale: {},
rowKey: 'key',
showHeader: true,
};
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),
'`columnsPageRange` and `columnsPageSize` are removed, please use ' +
'fixed columns instead, see: https://u.ant.design/fixed-columns.',
);
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]) {
this.CheckboxPropsCache[key] = rowSelection.getCheckboxProps(item);
}
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 = props.pagination || {};
return this.hasPagination(props) ?
{
...defaultPagination,
...pagination,
current: pagination.defaultCurrent || pagination.current || 1,
pageSize: pagination.defaultPageSize || pagination.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 || [],
});
}
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 = (record: T, index: number) => {
const { onRow, prefixCls } = 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>[]) {
let 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);
let 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,
sortOrder: sortedColumn.sortOrder,
};
}
return {
sortColumn: null,
sortOrder: null,
};
}
getSorterFn() {
const { sortOrder, sortColumn } = this.state;
if (!sortOrder || !sortColumn ||
typeof sortColumn.sorter !== 'function') {
return;
}
return (a: T, b: T) => {
const result = (sortColumn!.sorter as CompareFn<T>)(a, b, sortOrder);
if (result !== 0) {
return (sortOrder === 'descend') ? -result : result;
}
return 0;
};
}
toggleSortOrder(order: 'ascend'|'descend', column: ColumnProps<T>) {
let { sortColumn, sortOrder } = this.state;
// 只同时允许一列进行排序,否则会导致排序顺序的逻辑问题
let isSortColumn = this.isSortColumn(column);
if (!isSortColumn) { // 当前列未排序
sortOrder = order;
sortColumn = column;
} else { // 当前列已排序
if (sortOrder === order) { // 切换为未排序状态
sortOrder = undefined;
sortColumn = null;
} else { // 切换为排序状态