ant-design/components/table/Table.tsx

1172 lines
36 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
2018-09-17 18:33:52 +08:00
import * as ReactDOM from 'react-dom';
import RcTable from 'rc-table';
2018-08-07 21:07:52 +08:00
import * as PropTypes from 'prop-types';
import classNames from 'classnames';
import shallowEqual from 'shallowequal';
import Pagination from '../pagination';
import Icon from '../icon';
2017-11-21 13:48:37 +08:00
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';
2017-11-21 13:48:37 +08:00
import SelectionCheckboxAll from './SelectionCheckboxAll';
import Column from './Column';
import ColumnGroup from './ColumnGroup';
2017-11-18 00:36:22 +08:00
import createBodyRow from './createBodyRow';
import { flatArray, treeMap, flatFilter, normalizeColumns } from './util';
import { SpinProps } from '../spin';
2017-11-21 13:48:37 +08:00
import {
TableProps,
TableSize,
2017-11-21 13:48:37 +08:00
TableState,
TableComponents,
RowSelectionType,
TableLocale,
AdditionalCellProps,
2017-11-21 13:48:37 +08:00
ColumnProps,
CompareFn,
TableStateFilters,
SelectionItemSelectFn,
2018-05-07 12:32:26 +08:00
SelectionInfo,
TableSelectWay,
TableRowSelection,
PaginationConfig,
PrepareParamsArgumentsReturn,
2017-11-21 13:48:37 +08:00
} from './interface';
import { RadioChangeEvent } from '../radio';
import { CheckboxChangeEvent } from '../checkbox';
2018-12-07 16:17:45 +08:00
function noop() {}
2017-11-21 13:48:37 +08:00
function stopPropagation(e: React.SyntheticEvent<any>) {
e.stopPropagation();
if (e.nativeEvent.stopImmediatePropagation) {
e.nativeEvent.stopImmediatePropagation();
}
}
2018-05-07 12:32:26 +08:00
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 = {};
2017-11-21 13:48:37 +08:00
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,
2018-12-07 16:17:45 +08:00
loading: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
bordered: PropTypes.bool,
onChange: PropTypes.func,
locale: PropTypes.object,
dropdownPrefixCls: PropTypes.string,
2016-07-13 11:14:24 +08:00
};
static defaultProps = {
dataSource: [],
prefixCls: 'ant-table',
useFixedHeader: false,
className: '',
size: 'default' as TableSize,
loading: false,
bordered: false,
indentSize: 20,
locale: {},
rowKey: 'key',
showHeader: true,
2016-07-13 11:14:24 +08:00
};
2017-11-21 13:48:37 +08:00
CheckboxPropsCache: {
[key: string]: any;
};
store: Store;
columns: ColumnProps<T>[];
components: TableComponents;
row: React.ComponentType<any>;
2017-11-21 13:48:37 +08:00
constructor(props: TableProps<T>) {
super(props);
warning(
!('columnsPageRange' in props || 'columnsPageSize' in props),
'`columnsPageRange` and `columnsPageSize` are removed, please use ' +
2018-12-07 16:17:45 +08:00
'fixed columns instead, see: https://u.ant.design/fixed-columns.',
);
2017-11-21 13:48:37 +08:00
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({
2018-05-07 12:32:26 +08:00
selectedRowKeys: getRowSelection(props).selectedRowKeys || [],
selectionDirty: false,
});
}
2017-11-21 13:48:37 +08:00
getCheckboxPropsByItem = (item: T, index: number) => {
2018-12-07 16:17:45 +08:00
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];
2018-12-07 16:17:45 +08:00
};
getDefaultSelection() {
2018-05-07 12:32:26 +08:00
const rowSelection = getRowSelection(this.props);
if (!rowSelection.getCheckboxProps) {
return [];
}
return this.getFlatData()
2017-11-21 13:48:37 +08:00
.filter((item: T, rowIndex) => this.getCheckboxPropsByItem(item, rowIndex).defaultChecked)
.map((record, rowIndex) => this.getRecordKey(record, rowIndex));
}
2017-11-21 13:48:37 +08:00
getDefaultPagination(props: TableProps<T>) {
const pagination: PaginationConfig = props.pagination || {};
2018-12-07 16:17:45 +08:00
return this.hasPagination(props)
? {
...defaultPagination,
...pagination,
current: pagination.defaultCurrent || pagination.current || 1,
pageSize: pagination.defaultPageSize || pagination.pageSize || 10,
}
: {};
}
2017-11-21 13:48:37 +08:00
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 };
});
}
2018-12-07 16:17:45 +08:00
if (nextProps.rowSelection && 'selectedRowKeys' in nextProps.rowSelection) {
this.store.setState({
selectedRowKeys: nextProps.rowSelection.selectedRowKeys || [],
});
}
2018-12-07 16:17:45 +08:00
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);
2018-12-07 16:17:45 +08:00
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);
}
2017-11-21 13:48:37 +08:00
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),
};
2018-12-07 16:17:45 +08:00
};
2018-05-07 12:32:26 +08:00
setSelectedRowKeys(selectedRowKeys: string[], selectionInfo: SelectionInfo<T>) {
const { selectWay, record, checked, changeRowKeys, nativeEvent } = selectionInfo;
const rowSelection = getRowSelection(this.props);
2016-08-03 21:08:13 +08:00
if (rowSelection && !('selectedRowKeys' in rowSelection)) {
this.store.setState({ selectedRowKeys });
}
const data = this.getFlatData();
2016-08-03 21:08:13 +08:00
if (!rowSelection.onChange && !rowSelection[selectWay]) {
return;
}
const selectedRows = data.filter(
(row, i) => selectedRowKeys.indexOf(this.getRecordKey(row, i)) >= 0,
2016-08-03 21:08:13 +08:00
);
if (rowSelection.onChange) {
rowSelection.onChange(selectedRowKeys, selectedRows);
}
if (selectWay === 'onSelect' && rowSelection.onSelect) {
2018-05-07 12:32:26 +08:00
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);
2016-08-03 21:08:13 +08:00
} else if (selectWay === 'onSelectAll' && rowSelection.onSelectAll) {
const changeRows = data.filter(
2018-05-07 12:32:26 +08:00
(row, i) => changeRowKeys!.indexOf(this.getRecordKey(row, i)) >= 0,
);
2018-05-07 12:32:26 +08:00
rowSelection.onSelectAll(checked!, selectedRows, changeRows);
} else if (selectWay === 'onSelectInvert' && rowSelection.onSelectInvert) {
rowSelection.onSelectInvert(selectedRowKeys);
}
}
hasPagination(props?: any) {
return (props || this.props).pagination !== false;
}
2017-11-21 13:48:37 +08:00
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;
}
2017-11-21 13:48:37 +08:00
getSortOrderColumns(columns?: ColumnProps<T>[]) {
return flatFilter(
columns || this.columns || [],
(column: ColumnProps<T>) => 'sortOrder' in column,
);
}
2017-11-21 13:48:37 +08:00
getFilteredValueColumns(columns?: ColumnProps<T>[]) {
return flatFilter(
columns || this.columns || [],
(column: ColumnProps<T>) => typeof column.filteredValue !== 'undefined',
);
}
2017-11-21 13:48:37 +08:00
getFiltersFromColumns(columns?: ColumnProps<T>[]) {
2018-11-10 21:40:21 +08:00
const filters: any = {};
2017-11-21 13:48:37 +08:00
this.getFilteredValueColumns(columns).forEach((col: ColumnProps<T>) => {
const colKey = this.getColumnKey(col) as string;
filters[colKey] = col.filteredValue;
});
return filters;
}
2017-11-21 13:48:37 +08:00
getDefaultSortOrder(columns?: ColumnProps<T>[]) {
const definedSortState = this.getSortStateFromColumns(columns);
2018-12-07 16:17:45 +08:00
const defaultSortedColumn = flatFilter(
columns || [],
(column: ColumnProps<T>) => column.defaultSortOrder != null,
)[0];
if (defaultSortedColumn && !definedSortState.sortColumn) {
return {
sortColumn: defaultSortedColumn,
sortOrder: defaultSortedColumn.defaultSortOrder,
};
}
return definedSortState;
}
2017-11-21 13:48:37 +08:00
getSortStateFromColumns(columns?: ColumnProps<T>[]) {
// return first column which sortOrder is not falsy
2018-12-07 16:17:45 +08:00
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(state: TableState<T>) {
const { sortOrder, sortColumn } = state || this.state;
2018-12-07 16:17:45 +08:00
if (!sortOrder || !sortColumn || typeof sortColumn.sorter !== 'function') {
return;
}
2017-11-21 13:48:37 +08:00
return (a: T, b: T) => {
const result = (sortColumn!.sorter as CompareFn<T>)(a, b, sortOrder);
if (result !== 0) {
2018-12-07 16:17:45 +08:00
return sortOrder === 'descend' ? -result : result;
}
return 0;
};
}
isSameColumn(a: ColumnProps<T> | null, b: ColumnProps<T> | null) {
if (a && b && a.key && a.key === b.key) {
return true;
}
2018-12-07 16:17:45 +08:00
return (
a === b ||
shallowEqual(a, b, (value: any, other: any) => {
if (typeof value === 'function' && typeof other === 'function') {
return value === other || value.toString() === other.toString();
}
})
);
}
2018-09-17 17:57:01 +08:00
toggleSortOrder(column: ColumnProps<T>) {
if (!column.sorter) {
return;
}
const { sortOrder, sortColumn } = this.state;
// 只同时允许一列进行排序,否则会导致排序顺序的逻辑问题
2018-09-17 17:57:01 +08:00
let newSortOrder: 'descend' | 'ascend' | undefined;
// 切换另一列时,丢弃 sortOrder 的状态
const oldSortOrder = this.isSameColumn(sortColumn, column) ? sortOrder : undefined;
2018-09-17 17:57:01 +08:00
// 切换排序状态,按照降序/升序/不排序的顺序
if (!oldSortOrder) {
2018-09-17 17:57:01 +08:00
newSortOrder = 'ascend';
} else if (oldSortOrder === 'ascend') {
newSortOrder = 'descend';
2018-09-17 17:57:01 +08:00
} else {
newSortOrder = undefined;
}
2018-09-17 17:57:01 +08:00
const newState = {
2018-09-17 17:57:01 +08:00
sortOrder: newSortOrder,
sortColumn: newSortOrder ? column : null,
};
// Controlled
if (this.getSortOrderColumns().length === 0) {
this.setState(newState);
}
2018-09-17 17:57:01 +08:00
const { onChange } = this.props;
2016-10-24 16:30:38 +08:00
if (onChange) {
2018-12-07 16:17:45 +08:00
onChange.apply(
null,
this.prepareParamsArguments({
...this.state,
...newState,
}),
);
2016-10-24 16:30:38 +08:00
}
}
2017-11-21 13:48:37 +08:00
handleFilter = (column: ColumnProps<T>, nextFilters: string[]) => {
const props = this.props;
2018-11-10 21:40:21 +08:00
const pagination = { ...this.state.pagination };
const filters = {
...this.state.filters,
2017-11-21 13:48:37 +08:00
[this.getColumnKey(column) as string]: nextFilters,
};
// Remove filters not in current columns
2016-12-03 15:13:10 +08:00
const currentColumnKeys: string[] = [];
treeMap(this.columns, c => {
if (!c.children) {
2017-11-21 13:48:37 +08:00
currentColumnKeys.push(this.getColumnKey(c) as string);
2016-12-03 15:13:10 +08:00
}
});
2018-12-07 16:17:45 +08:00
Object.keys(filters).forEach(columnKey => {
if (currentColumnKeys.indexOf(columnKey) < 0) {
delete filters[columnKey];
}
});
if (props.pagination) {
// Reset current prop
pagination.current = 1;
2017-11-21 13:48:37 +08:00
pagination.onChange!(pagination.current);
}
const newState = {
pagination,
filters: {},
};
const filtersToSetState = { ...filters };
// Remove filters which is controlled
2017-11-21 13:48:37 +08:00
this.getFilteredValueColumns().forEach((col: ColumnProps<T>) => {
const columnKey = this.getColumnKey(col);
if (columnKey) {
delete filtersToSetState[columnKey];
}
});
if (Object.keys(filtersToSetState).length > 0) {
newState.filters = filtersToSetState;
}
// Controlled current prop will not respond user interaction
if (typeof props.pagination === 'object' && 'current' in (props.pagination as Object)) {
newState.pagination = {
...pagination,
current: this.state.pagination.current,
};
}
this.setState(newState, () => {
this.store.setState({
selectionDirty: false,
});
2018-09-21 15:36:27 +08:00
const { onChange } = this.props;
2016-10-24 16:30:38 +08:00
if (onChange) {
2018-12-07 16:17:45 +08:00
onChange.apply(
null,
this.prepareParamsArguments({
...this.state,
selectionDirty: false,
filters,
pagination,
}),
);
2016-10-24 16:30:38 +08:00
}
});
2018-12-07 16:17:45 +08:00
};
handleSelect = (record: T, rowIndex: number, e: CheckboxChangeEvent) => {
const checked = e.target.checked;
const nativeEvent = e.nativeEvent;
const defaultSelection = this.store.getState().selectionDirty ? [] : this.getDefaultSelection();
let selectedRowKeys = this.store.getState().selectedRowKeys.concat(defaultSelection);
2018-11-10 21:40:21 +08:00
const key = this.getRecordKey(record, rowIndex);
2018-09-21 15:36:27 +08:00
const { pivot } = this.state;
const rows = this.getFlatCurrentPageData(this.props.childrenColumnName);
let realIndex = rowIndex;
if (this.props.expandedRowRender) {
realIndex = rows.findIndex(row => this.getRecordKey(row, rowIndex) === key);
}
if (nativeEvent.shiftKey && pivot !== undefined && realIndex !== pivot) {
const changeRowKeys = [];
const direction = Math.sign(pivot - realIndex);
const dist = Math.abs(pivot - realIndex);
let step = 0;
while (step <= dist) {
2018-12-07 16:17:45 +08:00
const i = realIndex + step * direction;
step += 1;
const row = rows[i];
const rowKey = this.getRecordKey(row, i);
const checkboxProps = this.getCheckboxPropsByItem(row, i);
if (!checkboxProps.disabled) {
if (selectedRowKeys.includes(rowKey)) {
if (!checked) {
selectedRowKeys = selectedRowKeys.filter((j: string) => rowKey !== j);
changeRowKeys.push(rowKey);
}
} else if (checked) {
selectedRowKeys.push(rowKey);
changeRowKeys.push(rowKey);
}
}
}
this.setState({ pivot: realIndex });
this.store.setState({
selectionDirty: true,
});
this.setSelectedRowKeys(selectedRowKeys, {
selectWay: 'onSelectMultiple',
record,
checked,
changeRowKeys,
nativeEvent,
});
} else {
if (checked) {
selectedRowKeys.push(this.getRecordKey(record, realIndex));
} else {
selectedRowKeys = selectedRowKeys.filter((i: string) => key !== i);
}
this.setState({ pivot: realIndex });
this.store.setState({
selectionDirty: true,
});
this.setSelectedRowKeys(selectedRowKeys, {
selectWay: 'onSelect',
record,
checked,
2018-12-07 16:17:45 +08:00
changeRowKeys: void 0,
nativeEvent,
});
}
2018-12-07 16:17:45 +08:00
};
handleRadioSelect = (record: T, rowIndex: number, e: RadioChangeEvent) => {
const checked = e.target.checked;
const nativeEvent = e.nativeEvent;
const defaultSelection = this.store.getState().selectionDirty ? [] : this.getDefaultSelection();
let selectedRowKeys = this.store.getState().selectedRowKeys.concat(defaultSelection);
2018-11-10 21:40:21 +08:00
const key = this.getRecordKey(record, rowIndex);
selectedRowKeys = [key];
this.store.setState({
selectionDirty: true,
});
2016-08-03 21:08:13 +08:00
this.setSelectedRowKeys(selectedRowKeys, {
selectWay: 'onSelect',
record,
checked,
2018-12-07 16:17:45 +08:00
changeRowKeys: void 0,
nativeEvent,
2016-08-03 21:08:13 +08:00
});
2018-12-07 16:17:45 +08:00
};
2017-11-21 13:48:37 +08:00
handleSelectRow = (selectionKey: string, index: number, onSelectFunc: SelectionItemSelectFn) => {
const data = this.getFlatCurrentPageData(this.props.childrenColumnName);
const defaultSelection = this.store.getState().selectionDirty ? [] : this.getDefaultSelection();
const selectedRowKeys = this.store.getState().selectedRowKeys.concat(defaultSelection);
const changeableRowKeys = data
.filter((item, i) => !this.getCheckboxPropsByItem(item, i).disabled)
.map((item, i) => this.getRecordKey(item, i));
2018-11-10 21:40:21 +08:00
const changeRowKeys: string[] = [];
2018-05-07 12:32:26 +08:00
let selectWay: TableSelectWay = 'onSelectAll';
let checked;
// handle default selection
switch (selectionKey) {
case 'all':
changeableRowKeys.forEach(key => {
if (selectedRowKeys.indexOf(key) < 0) {
selectedRowKeys.push(key);
changeRowKeys.push(key);
}
});
selectWay = 'onSelectAll';
checked = true;
break;
case 'removeAll':
changeableRowKeys.forEach(key => {
if (selectedRowKeys.indexOf(key) >= 0) {
selectedRowKeys.splice(selectedRowKeys.indexOf(key), 1);
changeRowKeys.push(key);
}
});
selectWay = 'onSelectAll';
checked = false;
break;
case 'invert':
changeableRowKeys.forEach(key => {
if (selectedRowKeys.indexOf(key) < 0) {
selectedRowKeys.push(key);
2017-10-21 20:06:12 +08:00
} else {
selectedRowKeys.splice(selectedRowKeys.indexOf(key), 1);
}
changeRowKeys.push(key);
selectWay = 'onSelectInvert';
});
break;
default:
break;
}
this.store.setState({
selectionDirty: true,
});
// when select custom selection, callback selections[n].onSelect
const { rowSelection } = this.props;
let customSelectionStartIndex = 2;
if (rowSelection && rowSelection.hideDefaultSelections) {
customSelectionStartIndex = 0;
}
if (index >= customSelectionStartIndex && typeof onSelectFunc === 'function') {
return onSelectFunc(changeableRowKeys);
}
2016-08-03 21:08:13 +08:00
this.setSelectedRowKeys(selectedRowKeys, {
2018-05-07 12:32:26 +08:00
selectWay,
2016-08-03 21:08:13 +08:00
checked,
changeRowKeys,
});
2018-12-07 16:17:45 +08:00
};
2017-11-21 13:48:37 +08:00
handlePageChange = (current: number, ...otherArguments: any[]) => {
const props = this.props;
2018-11-10 21:40:21 +08:00
const pagination = { ...this.state.pagination };
if (current) {
pagination.current = current;
} else {
pagination.current = pagination.current || 1;
}
2017-11-21 13:48:37 +08:00
pagination.onChange!(pagination.current, ...otherArguments);
const newState = {
pagination,
};
// Controlled current prop will not respond user interaction
2018-12-07 16:17:45 +08:00
if (
props.pagination &&
typeof props.pagination === 'object' &&
'current' in (props.pagination as Object)
) {
newState.pagination = {
...pagination,
current: this.state.pagination.current,
};
}
this.setState(newState);
this.store.setState({
selectionDirty: false,
});
2018-09-21 15:36:27 +08:00
const { onChange } = this.props;
2016-10-24 16:30:38 +08:00
if (onChange) {
2018-12-07 16:17:45 +08:00
onChange.apply(
null,
this.prepareParamsArguments({
...this.state,
selectionDirty: false,
pagination,
}),
);
2016-10-24 16:30:38 +08:00
}
2018-12-07 16:17:45 +08:00
};
2017-11-21 13:48:37 +08:00
renderSelectionBox = (type: RowSelectionType | undefined) => {
return (_: any, record: T, index: number) => {
const rowKey = this.getRecordKey(record, index);
const props = this.getCheckboxPropsByItem(record, index);
const handleChange = (e: RadioChangeEvent | CheckboxChangeEvent) => {
2018-12-07 16:17:45 +08:00
type === 'radio'
? this.handleRadioSelect(record, index, e)
: this.handleSelect(record, index, e);
};
return (
<span onClick={stopPropagation}>
<SelectionBox
type={type}
store={this.store}
rowIndex={rowKey}
onChange={handleChange}
defaultSelection={this.getDefaultSelection()}
{...props}
/>
</span>
);
};
2018-12-07 16:17:45 +08:00
};
2017-11-21 13:48:37 +08:00
getRecordKey = (record: T, index: number) => {
2018-09-21 15:36:27 +08:00
const { rowKey } = this.props;
2018-12-07 16:17:45 +08:00
const recordKey =
typeof rowKey === 'function' ? rowKey(record, index) : (record as any)[rowKey as string];
warning(
recordKey !== undefined,
2018-07-20 12:10:43 +08:00
'Each record in dataSource of table should have a unique `key` prop, ' +
2018-12-07 16:17:45 +08:00
'or set `rowKey` of Table to an unique primary key, ' +
'see https://u.ant.design/table-row-key',
2016-09-27 13:41:57 +08:00
);
return recordKey === undefined ? index : recordKey;
2018-12-07 16:17:45 +08:00
};
2018-09-17 18:33:52 +08:00
getPopupContainer = () => {
return ReactDOM.findDOMNode(this) as HTMLElement;
2018-12-07 16:17:45 +08:00
};
2017-11-21 13:48:37 +08:00
renderRowSelection(locale: TableLocale) {
const { prefixCls, rowSelection, childrenColumnName } = this.props;
const columns = this.columns.concat();
2016-10-24 16:30:38 +08:00
if (rowSelection) {
const data = this.getFlatCurrentPageData(childrenColumnName).filter((item, index) => {
2016-10-24 16:30:38 +08:00
if (rowSelection.getCheckboxProps) {
return !this.getCheckboxPropsByItem(item, index).disabled;
}
return true;
});
2018-11-10 21:40:21 +08:00
const selectionColumnClass = classNames(`${prefixCls}-selection-column`, {
[`${prefixCls}-selection-column-custom`]: rowSelection.selections,
});
const selectionColumn: ColumnProps<any> = {
key: 'selection-column',
render: this.renderSelectionBox(rowSelection.type),
className: selectionColumnClass,
fixed: rowSelection.fixed,
width: rowSelection.columnWidth,
title: rowSelection.columnTitle,
};
if (rowSelection.type !== 'radio') {
2018-12-07 16:17:45 +08:00
const checkboxAllDisabled = data.every(
(item, index) => this.getCheckboxPropsByItem(item, index).disabled,
);
selectionColumn.title = selectionColumn.title || (
<SelectionCheckboxAll
store={this.store}
locale={locale}
data={data}
getCheckboxPropsByItem={this.getCheckboxPropsByItem}
getRecordKey={this.getRecordKey}
disabled={checkboxAllDisabled}
prefixCls={prefixCls}
onSelect={this.handleSelectRow}
selections={rowSelection.selections}
hideDefaultSelections={rowSelection.hideDefaultSelections}
getPopupContainer={this.getPopupContainer}
/>
);
}
if ('fixed' in rowSelection) {
selectionColumn.fixed = rowSelection.fixed;
} else if (columns.some(column => column.fixed === 'left' || column.fixed === true)) {
selectionColumn.fixed = 'left';
}
if (columns[0] && columns[0].key === 'selection-column') {
columns[0] = selectionColumn;
} else {
columns.unshift(selectionColumn);
}
}
return columns;
}
2017-11-21 13:48:37 +08:00
getColumnKey(column: ColumnProps<T>, index?: number) {
return column.key || column.dataIndex || index;
}
2017-11-21 13:48:37 +08:00
getMaxCurrent(total: number) {
2018-12-07 16:17:45 +08:00
const {
pagination: { current, pageSize },
} = this.state;
2017-11-21 13:48:37 +08:00
if ((current! - 1) * pageSize! >= total) {
return Math.floor((total - 1) / pageSize!) + 1;
}
return current;
}
2017-11-21 13:48:37 +08:00
isSortColumn(column: ColumnProps<T>) {
const { sortColumn } = this.state;
if (!column || !sortColumn) {
return false;
}
return this.getColumnKey(sortColumn) === this.getColumnKey(column);
}
2017-11-21 13:48:37 +08:00
renderColumnsDropdown(columns: ColumnProps<T>[], locale: TableLocale) {
const { prefixCls, dropdownPrefixCls } = this.props;
const { sortOrder, filters } = this.state;
return treeMap(columns, (column, i) => {
const key = this.getColumnKey(column, i) as string;
let filterDropdown;
let sortButton;
let onHeaderCell = column.onHeaderCell;
2018-12-02 16:07:39 +08:00
const sortTitle = this.getColumnTitle(column.title, {}) || locale.sortTitle;
const isSortColumn = this.isSortColumn(column);
if ((column.filters && column.filters.length > 0) || column.filterDropdown) {
const colFilters = key in filters ? filters[key] : [];
filterDropdown = (
2016-06-20 16:25:35 +08:00
<FilterDropdown
locale={locale}
column={column}
selectedKeys={colFilters}
confirmFilter={this.handleFilter}
prefixCls={`${prefixCls}-filter`}
2016-10-24 16:30:38 +08:00
dropdownPrefixCls={dropdownPrefixCls || 'ant-dropdown'}
getPopupContainer={this.getPopupContainer}
key="filter-dropdown"
/>
);
}
if (column.sorter) {
const isAscend = isSortColumn && sortOrder === 'ascend';
const isDescend = isSortColumn && sortOrder === 'descend';
sortButton = (
<div className={`${prefixCls}-column-sorter`} key="sorter">
<Icon
className={`${prefixCls}-column-sorter-up ${isAscend ? 'on' : 'off'}`}
type="caret-up"
theme="filled"
/>
<Icon
className={`${prefixCls}-column-sorter-down ${isDescend ? 'on' : 'off'}`}
type="caret-down"
theme="filled"
/>
</div>
);
onHeaderCell = (col: Column<T>) => {
let colProps: AdditionalCellProps = {};
// Get original first
if (column.onHeaderCell) {
colProps = {
...column.onHeaderCell(col),
};
}
// Add sorter logic
const onHeaderCellClick = colProps.onClick;
colProps.onClick = (...args) => {
this.toggleSortOrder(column);
if (onHeaderCellClick) {
onHeaderCellClick(...args);
}
};
return colProps;
};
}
const sortTitleString = sortButton && typeof sortTitle === 'string' ? sortTitle : undefined;
return {
...column,
className: classNames(column.className, {
[`${prefixCls}-column-has-actions`]: sortButton || filterDropdown,
[`${prefixCls}-column-has-filters`]: filterDropdown,
[`${prefixCls}-column-has-sorters`]: sortButton,
[`${prefixCls}-column-sort`]: isSortColumn && sortOrder,
}),
title: [
2018-09-17 19:03:06 +08:00
<div
key="title"
2018-12-13 22:51:53 +08:00
title={sortTitleString}
2018-09-17 19:03:06 +08:00
className={sortButton ? `${prefixCls}-column-sorters` : undefined}
>
{this.renderColumnTitle(column.title)}
{sortButton}
</div>,
filterDropdown,
],
onHeaderCell,
};
});
}
renderColumnTitle(title: ColumnProps<T>['title']) {
const { filters, sortOrder } = this.state;
// https://github.com/ant-design/ant-design/issues/11246#issuecomment-405009167
if (title instanceof Function) {
return title({
filters,
sortOrder,
});
}
return title;
}
2018-12-03 11:45:09 +08:00
getColumnTitle: any = (title: any, parentNode: any) => {
2018-12-07 16:17:45 +08:00
if (!title) {
2018-12-03 11:45:09 +08:00
return;
2018-12-02 15:56:44 +08:00
}
2018-12-07 16:17:45 +08:00
if (!(title instanceof Function) && typeof title !== 'string' && typeof title !== 'number') {
2018-12-03 11:45:09 +08:00
const props = title.props;
2018-12-02 15:56:44 +08:00
if (props && props.children) {
const { children } = props;
2018-12-05 16:39:27 +08:00
return this.getColumnTitle(children, props);
2018-12-02 15:56:44 +08:00
}
} else {
2018-12-03 12:47:05 +08:00
return parentNode.title || title;
2018-12-02 15:56:44 +08:00
}
2018-12-07 16:17:45 +08:00
};
2018-12-02 15:56:44 +08:00
2017-11-21 13:48:37 +08:00
handleShowSizeChange = (current: number, pageSize: number) => {
2018-09-21 15:36:27 +08:00
const { pagination } = this.state;
2017-11-21 13:48:37 +08:00
pagination.onShowSizeChange!(current, pageSize);
const nextPagination = {
...pagination,
pageSize,
current,
};
this.setState({ pagination: nextPagination });
2016-10-24 16:30:38 +08:00
2018-09-21 15:36:27 +08:00
const { onChange } = this.props;
2016-10-24 16:30:38 +08:00
if (onChange) {
2018-12-07 16:17:45 +08:00
onChange.apply(
null,
this.prepareParamsArguments({
...this.state,
pagination: nextPagination,
}),
);
2016-10-24 16:30:38 +08:00
}
2018-12-07 16:17:45 +08:00
};
renderPagination(paginationPosition: string) {
// 强制不需要分页
if (!this.hasPagination()) {
return null;
}
let size = 'default';
2016-07-12 18:24:16 +08:00
const { pagination } = this.state;
if (pagination.size) {
size = pagination.size;
2018-12-07 16:17:45 +08:00
} else if ((this.props.size as string) === 'middle' || this.props.size === 'small') {
size = 'small';
}
2018-11-10 21:40:21 +08:00
const position = pagination.position || 'bottom';
const total = pagination.total || this.getLocalData().length;
2018-12-07 16:17:45 +08:00
return total > 0 && (position === paginationPosition || position === 'both') ? (
2016-07-12 18:24:16 +08:00
<Pagination
key={`pagination-${paginationPosition}`}
2016-07-12 18:24:16 +08:00
{...pagination}
className={classNames(pagination.className, `${this.props.prefixCls}-pagination`)}
onChange={this.handlePageChange}
total={total}
size={size}
current={this.getMaxCurrent(total)}
onShowSizeChange={this.handleShowSizeChange}
/>
) : null;
}
// Get pagination, filters, sorter
prepareParamsArguments(state: any): PrepareParamsArgumentsReturn<T> {
const pagination = { ...state.pagination };
// remove useless handle function in Table.onChange
delete pagination.onChange;
delete pagination.onShowSizeChange;
const filters = state.filters;
const sorter: any = {};
if (state.sortColumn && state.sortOrder) {
sorter.column = state.sortColumn;
sorter.order = state.sortOrder;
sorter.field = state.sortColumn.dataIndex;
sorter.columnKey = this.getColumnKey(state.sortColumn);
}
const extra = {
currentDataSource: this.getLocalData(state),
};
return [pagination, filters, sorter, extra];
}
2017-11-21 13:48:37 +08:00
findColumn(myKey: string | number) {
2016-12-03 15:13:10 +08:00
let column;
treeMap(this.columns, c => {
if (this.getColumnKey(c) === myKey) {
column = c;
}
});
return column;
}
getCurrentPageData() {
let data = this.getLocalData();
2017-11-21 13:48:37 +08:00
let current: number;
let pageSize: number;
2018-11-10 21:40:21 +08:00
const state = this.state;
// 如果没有分页的话,默认全部展示
if (!this.hasPagination()) {
pageSize = Number.MAX_VALUE;
current = 1;
} else {
2017-11-21 13:48:37 +08:00
pageSize = state.pagination.pageSize as number;
current = this.getMaxCurrent(state.pagination.total || data.length) as number;
}
// 分页
// ---
// 当数据量少于等于每页数量时,直接设置数据
// 否则进行读取分页数据
if (data.length > pageSize || pageSize === Number.MAX_VALUE) {
2016-10-20 22:10:46 +08:00
data = data.filter((_, i) => {
return i >= (current - 1) * pageSize && i < current * pageSize;
});
}
return data;
}
getFlatData() {
return flatArray(this.getLocalData(null, false));
}
getFlatCurrentPageData(childrenColumnName: string | undefined) {
return flatArray(this.getCurrentPageData(), childrenColumnName);
}
2017-11-21 13:48:37 +08:00
recursiveSort(data: T[], sorterFn: (a: any, b: any) => number): T[] {
2016-10-24 16:30:38 +08:00
const { childrenColumnName = 'children' } = this.props;
2018-12-07 16:17:45 +08:00
return data.sort(sorterFn).map((item: any) =>
item[childrenColumnName]
? {
...item,
[childrenColumnName]: this.recursiveSort(item[childrenColumnName], sorterFn),
}
: item,
);
2016-08-26 15:04:19 +08:00
}
getLocalData(state?: TableState<T> | null, filter: boolean = true): Array<T> {
const currentState: TableState<T> = state || this.state;
2016-08-26 15:04:19 +08:00
const { dataSource } = this.props;
2016-08-25 21:12:23 +08:00
let data = dataSource || [];
// 优化本地排序
data = data.slice(0);
const sorterFn = this.getSorterFn(currentState);
if (sorterFn) {
2016-08-26 15:04:19 +08:00
data = this.recursiveSort(data, sorterFn);
}
// 筛选
if (filter && currentState.filters) {
2018-12-07 16:17:45 +08:00
Object.keys(currentState.filters).forEach(columnKey => {
2018-11-10 21:40:21 +08:00
const col = this.findColumn(columnKey) as any;
if (!col) {
return;
}
2018-11-10 21:40:21 +08:00
const values = currentState.filters[columnKey] || [];
if (values.length === 0) {
return;
}
2016-10-24 16:30:38 +08:00
const onFilter = col.onFilter;
2018-12-07 16:17:45 +08:00
data = onFilter
? data.filter(record => {
return values.some(v => onFilter(v, record));
})
: data;
});
}
return data;
}
createComponents(components: TableComponents = {}, prevComponents?: TableComponents) {
const bodyRow = components && components.body && components.body.row;
const preBodyRow = prevComponents && prevComponents.body && prevComponents.body.row;
if (!this.row || bodyRow !== preBodyRow) {
this.row = createBodyRow(bodyRow);
}
this.components = {
...components,
body: {
...components.body,
row: this.row,
},
};
}
renderTable = (contextLocale: TableLocale, loading: SpinProps) => {
const locale = { ...contextLocale, ...this.props.locale };
const { style, className, prefixCls, showHeader, ...restProps } = this.props;
2016-08-30 17:01:51 +08:00
const data = this.getCurrentPageData();
const expandIconAsCell = this.props.expandedRowRender && this.props.expandIconAsCell !== false;
const classString = classNames({
[`${prefixCls}-${this.props.size}`]: true,
[`${prefixCls}-bordered`]: this.props.bordered,
[`${prefixCls}-empty`]: !data.length,
[`${prefixCls}-without-column-header`]: !showHeader,
});
let columns = this.renderRowSelection(locale);
columns = this.renderColumnsDropdown(columns, locale);
columns = columns.map((column, i) => {
const newColumn = { ...column };
newColumn.key = this.getColumnKey(newColumn, i);
return newColumn;
});
2018-12-07 16:17:45 +08:00
let expandIconColumnIndex = columns[0] && columns[0].key === 'selection-column' ? 1 : 0;
if ('expandIconColumnIndex' in restProps) {
2016-12-19 15:19:15 +08:00
expandIconColumnIndex = restProps.expandIconColumnIndex as number;
}
return (
<RcTable
key="table"
{...restProps}
onRow={this.onRow}
components={this.components}
2016-09-14 16:59:45 +08:00
prefixCls={prefixCls}
data={data}
columns={columns}
showHeader={showHeader}
className={classString}
expandIconColumnIndex={expandIconColumnIndex}
expandIconAsCell={expandIconAsCell}
emptyText={!loading.spinning && locale.emptyText}
/>
);
2018-12-07 16:17:45 +08:00
};
render() {
const { style, className, prefixCls } = this.props;
const data = this.getCurrentPageData();
let loading = this.props.loading as SpinProps;
if (typeof loading === 'boolean') {
loading = {
spinning: loading,
};
}
const table = (
2018-12-07 16:17:45 +08:00
<LocaleReceiver componentName="Table" defaultLocale={defaultLocale.Table}>
{locale => this.renderTable(locale, loading)}
</LocaleReceiver>
);
// if there is no pagination or no data,
// the height of spin should decrease by half of pagination
2018-12-07 16:17:45 +08:00
const paginationPatchClass =
this.hasPagination() && data && data.length !== 0
? `${prefixCls}-with-pagination`
: `${prefixCls}-without-pagination`;
return (
2018-12-07 16:17:45 +08:00
<div className={classNames(`${prefixCls}-wrapper`, className)} style={style}>
<Spin
2017-02-20 12:18:41 +08:00
{...loading}
className={loading.spinning ? `${paginationPatchClass} ${prefixCls}-spin-holder` : ''}
>
{this.renderPagination('top')}
{table}
{this.renderPagination('bottom')}
</Spin>
</div>
);
}
}