ant-design/components/table/Table.tsx

973 lines
30 KiB
TypeScript
Raw Normal View History

2016-09-21 11:54:53 +08:00
import React from 'react';
2017-05-24 16:16:42 +08:00
import { findDOMNode } from 'react-dom';
import RcTable from 'rc-table';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Pagination, { PaginationProps } from '../pagination';
import Icon from '../icon';
import Spin, { SpinProps } 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, { SelectionDecorator } from './SelectionCheckboxAll';
import Column, { ColumnProps } from './Column';
import ColumnGroup from './ColumnGroup';
import { flatArray, treeMap, flatFilter, normalizeColumns } from './util';
function noop() {
}
function stopPropagation(e) {
e.stopPropagation();
if (e.nativeEvent.stopImmediatePropagation) {
e.nativeEvent.stopImmediatePropagation();
}
}
const defaultPagination = {
onChange: noop,
onShowSizeChange: noop,
};
/**
* Avoid creating new object, so that parent component's shouldComponentUpdate
* can works appropriately
*/
const emptyObject = {};
2017-01-20 16:08:20 +08:00
export type TableColumnConfig<T> = ColumnProps<T>;
export interface TableRowSelection<T> {
type?: 'checkbox' | 'radio';
selectedRowKeys?: string[] | number[];
onChange?: (selectedRowKeys: string[] | number[], selectedRows: Object[]) => any;
getCheckboxProps?: (record: T) => Object;
onSelect?: (record: T, selected: boolean, selectedRows: Object[]) => any;
onSelectAll?: (selected: boolean, selectedRows: Object[], changeRows: Object[]) => any;
onSelectInvert?: (selectedRows: Object[]) => any;
selections?: SelectionDecorator[] | boolean;
hideDefaultSelections?: boolean;
}
export interface TableProps<T> {
prefixCls?: string;
dropdownPrefixCls?: string;
rowSelection?: TableRowSelection<T>;
pagination?: PaginationProps | boolean;
size?: 'default' | 'middle' | 'small';
dataSource?: T[];
columns?: ColumnProps<T>[];
rowKey?: string | ((record: T, index: number) => string);
rowClassName?: (record: T, index: number) => string;
expandedRowRender?: any;
defaultExpandedRowKeys?: string[] | number[];
expandedRowKeys?: string[] | number[];
expandIconAsCell?: boolean;
expandIconColumnIndex?: number;
onExpandedRowsChange?: (expandedRowKeys: string[] | number[]) => void;
onExpand?: (expanded: boolean, record: T) => void;
onChange?: (pagination: PaginationProps | boolean, filters: string[], sorter: Object) => any;
2017-03-28 15:00:19 +08:00
loading?: boolean | SpinProps;
locale?: Object;
indentSize?: number;
onRowClick?: (record: T, index: number, event: Event) => any;
useFixedHeader?: boolean;
bordered?: boolean;
showHeader?: boolean;
footer?: (currentPageData: Object[]) => React.ReactNode;
title?: (currentPageData: Object[]) => React.ReactNode;
2017-09-17 15:44:01 +08:00
scroll?: { x?: boolean | number | string, y?: boolean | number | string };
2016-10-24 16:30:38 +08:00
childrenColumnName?: string;
2016-09-19 17:35:17 +08:00
bodyStyle?: React.CSSProperties;
className?: string;
2016-12-19 15:19:15 +08:00
style?: React.CSSProperties;
}
export default class Table<T> extends React.Component<TableProps<T>, any> {
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,
2016-07-13 11:14:24 +08:00
};
static defaultProps = {
dataSource: [],
prefixCls: 'ant-table',
useFixedHeader: false,
rowSelection: null,
className: '',
size: 'large',
loading: false,
bordered: false,
indentSize: 20,
locale: {},
rowKey: 'key',
showHeader: true,
2016-07-13 11:14:24 +08:00
};
CheckboxPropsCache: Object;
store: Store;
columns: ColumnProps<T>[];
constructor(props) {
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);
this.state = {
...this.getSortStateFromColumns(),
// 减少状态
filters: this.getFiltersFromColumns(),
pagination: this.getDefaultPagination(props),
};
this.CheckboxPropsCache = {};
this.store = createStore({
selectedRowKeys: (props.rowSelection || {}).selectedRowKeys || [],
selectionDirty: false,
});
}
getCheckboxPropsByItem = (item, index) => {
const { rowSelection = {} } = 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 = {} } = this.props;
if (!rowSelection.getCheckboxProps) {
return [];
}
return this.getFlatData()
.filter((item, rowIndex) => this.getCheckboxPropsByItem(item, rowIndex).defaultChecked)
.map((record, rowIndex) => this.getRecordKey(record, rowIndex));
}
getDefaultPagination(props) {
const pagination = props.pagination || {};
return this.hasPagination(props) ?
{
...defaultPagination,
...pagination,
current: pagination.defaultCurrent || pagination.current || 1,
pageSize: pagination.defaultPageSize || pagination.pageSize || 10,
} : {};
}
componentWillReceiveProps(nextProps) {
this.columns = nextProps.columns || normalizeColumns(nextProps.children);
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 || [],
});
2016-06-21 19:35:29 +08:00
const { rowSelection } = this.props;
if (rowSelection && (
nextProps.rowSelection.getCheckboxProps !== rowSelection.getCheckboxProps
)) {
this.CheckboxPropsCache = {};
}
}
if ('dataSource' in nextProps &&
nextProps.dataSource !== this.props.dataSource) {
this.store.setState({
selectionDirty: false,
});
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 });
}
}
}
setSelectedRowKeys(selectedRowKeys, { selectWay, record, checked, changeRowKeys }: any) {
2016-08-03 21:08:13 +08:00
const { rowSelection = {} } = this.props;
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) {
rowSelection.onSelect(record, checked, selectedRows);
} else if (selectWay === 'onSelectAll' && rowSelection.onSelectAll) {
const changeRows = data.filter(
(row, i) => changeRowKeys.indexOf(this.getRecordKey(row, i)) >= 0,
);
2016-08-03 21:08:13 +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;
}
isFiltersChanged(filters) {
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?) {
return flatFilter(columns || this.columns || [], column => 'sortOrder' in column);
}
getFilteredValueColumns(columns?) {
return flatFilter(columns || this.columns || [], column => typeof column.filteredValue !== 'undefined');
}
getFiltersFromColumns(columns?) {
let filters = {};
this.getFilteredValueColumns(columns).forEach(col => {
filters[this.getColumnKey(col)] = col.filteredValue;
});
return filters;
}
getSortStateFromColumns(columns?) {
// return fisrt column which sortOrder is not falsy
const sortedColumn =
this.getSortOrderColumns(columns).filter(col => 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, b) => {
const result = sortColumn.sorter(a, b);
if (result !== 0) {
return (sortOrder === 'descend') ? -result : result;
}
return 0;
};
}
toggleSortOrder(order, column) {
let { sortColumn, sortOrder } = this.state;
// 只同时允许一列进行排序,否则会导致排序顺序的逻辑问题
let isSortColumn = this.isSortColumn(column);
if (!isSortColumn) { // 当前列未排序
sortOrder = order;
sortColumn = column;
} else { // 当前列已排序
if (sortOrder === order) { // 切换为未排序状态
sortOrder = '';
sortColumn = null;
} else { // 切换为排序状态
sortOrder = order;
}
}
const newState = {
sortOrder,
sortColumn,
};
// Controlled
if (this.getSortOrderColumns().length === 0) {
this.setState(newState);
}
2016-10-24 16:30:38 +08:00
const onChange = this.props.onChange;
if (onChange) {
onChange.apply(null, this.prepareParamsArguments({
...this.state,
...newState,
}));
2016-10-24 16:30:38 +08:00
}
}
handleFilter = (column, nextFilters) => {
const props = this.props;
let pagination = { ...this.state.pagination };
const filters = {
...this.state.filters,
[this.getColumnKey(column)]: 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) {
currentColumnKeys.push(this.getColumnKey(c));
}
});
Object.keys(filters).forEach((columnKey) => {
if (currentColumnKeys.indexOf(columnKey) < 0) {
delete filters[columnKey];
}
});
if (props.pagination) {
// Reset current prop
pagination.current = 1;
pagination.onChange(pagination.current);
}
const newState = {
pagination,
filters: {},
};
const filtersToSetState = { ...filters };
// Remove filters which is controlled
this.getFilteredValueColumns().forEach(col => {
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,
});
2016-10-24 16:30:38 +08:00
const onChange = this.props.onChange;
if (onChange) {
onChange.apply(null, this.prepareParamsArguments({
...this.state,
2016-10-24 16:30:38 +08:00
selectionDirty: false,
filters,
pagination,
}));
2016-10-24 16:30:38 +08:00
}
});
}
handleSelect = (record, rowIndex, e) => {
const checked = e.target.checked;
const defaultSelection = this.store.getState().selectionDirty ? [] : this.getDefaultSelection();
let selectedRowKeys = this.store.getState().selectedRowKeys.concat(defaultSelection);
let key = this.getRecordKey(record, rowIndex);
if (checked) {
selectedRowKeys.push(this.getRecordKey(record, rowIndex));
} else {
selectedRowKeys = selectedRowKeys.filter((i) => key !== i);
}
this.store.setState({
selectionDirty: true,
});
2016-08-03 21:08:13 +08:00
this.setSelectedRowKeys(selectedRowKeys, {
selectWay: 'onSelect',
record,
checked,
});
}
handleRadioSelect = (record, rowIndex, e) => {
const checked = e.target.checked;
const defaultSelection = this.store.getState().selectionDirty ? [] : this.getDefaultSelection();
let selectedRowKeys = this.store.getState().selectedRowKeys.concat(defaultSelection);
let 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,
});
}
handleSelectRow = (selectionKey, index, onSelectFunc) => {
const data = this.getFlatCurrentPageData();
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));
let changeRowKeys: string[] = [];
let selectWay = '';
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, {
selectWay: selectWay,
2016-08-03 21:08:13 +08:00
checked,
changeRowKeys,
});
}
handlePageChange = (current, ...otherArguments) => {
const props = this.props;
let pagination = { ...this.state.pagination };
if (current) {
pagination.current = current;
} else {
pagination.current = pagination.current || 1;
}
pagination.onChange(pagination.current, ...otherArguments);
const newState = {
pagination,
};
// Controlled current prop will not respond user interaction
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,
});
2016-10-24 16:30:38 +08:00
const onChange = this.props.onChange;
if (onChange) {
onChange.apply(null, this.prepareParamsArguments({
...this.state,
2016-10-24 16:30:38 +08:00
selectionDirty: false,
pagination,
}));
2016-10-24 16:30:38 +08:00
}
}
renderSelectionBox = (type) => {
return (_, record, index) => {
let rowIndex = this.getRecordKey(record, index); // 从 1 开始
const props = this.getCheckboxPropsByItem(record, index);
const handleChange = (e) => {
type === 'radio' ? this.handleRadioSelect(record, rowIndex, e) :
this.handleSelect(record, rowIndex, e);
};
return (
<span onClick={stopPropagation}>
<SelectionBox
type={type}
store={this.store}
rowIndex={rowIndex}
disabled={props.disabled}
onChange={handleChange}
defaultSelection={this.getDefaultSelection()}
/>
</span>
);
};
}
getRecordKey = (record, index): string => {
const rowKey = this.props.rowKey;
const recordKey = (typeof rowKey === 'function') ?
rowKey(record, index) : record[rowKey as string];
2016-09-27 13:41:57 +08:00
warning(recordKey !== undefined,
2017-03-05 18:35:49 +08:00
'Each record in dataSource of table should have a unique `key` prop, or set `rowKey` 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;
}
getPopupContainer = () => {
2017-05-24 16:16:42 +08:00
return findDOMNode(this) as HTMLElement;
}
renderRowSelection(locale) {
2016-10-24 16:30:38 +08:00
const { prefixCls, rowSelection } = this.props;
const columns = this.columns.concat();
2016-10-24 16:30:38 +08:00
if (rowSelection) {
const data = this.getFlatCurrentPageData().filter((item, index) => {
2016-10-24 16:30:38 +08:00
if (rowSelection.getCheckboxProps) {
return !this.getCheckboxPropsByItem(item, index).disabled;
}
return true;
});
let 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,
};
if (rowSelection.type !== 'radio') {
const checkboxAllDisabled = data.every((item, index) => this.getCheckboxPropsByItem(item, index).disabled);
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 (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;
}
getColumnKey(column, index?) {
return column.key || column.dataIndex || index;
}
getMaxCurrent(total) {
const { current, pageSize } = this.state.pagination;
if ((current - 1) * pageSize >= total) {
return Math.floor((total - 1) / pageSize) + 1;
}
return current;
}
isSortColumn(column) {
const { sortColumn } = this.state;
if (!column || !sortColumn) {
return false;
}
return this.getColumnKey(sortColumn) === this.getColumnKey(column);
}
renderColumnsDropdown(columns, locale) {
const { prefixCls, dropdownPrefixCls } = this.props;
const { sortOrder } = this.state;
return treeMap(columns, (originColumn, i) => {
let column = { ...originColumn };
let key = this.getColumnKey(column, i);
let filterDropdown;
let sortButton;
if ((column.filters && column.filters.length > 0) || column.filterDropdown) {
let colFilters = this.state.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}
/>
);
}
if (column.sorter) {
let isSortColumn = this.isSortColumn(column);
if (isSortColumn) {
column.className = column.className || '';
if (sortOrder) {
column.className += ` ${prefixCls}-column-sort`;
}
}
const isAscend = isSortColumn && sortOrder === 'ascend';
const isDescend = isSortColumn && sortOrder === 'descend';
sortButton = (
<div className={`${prefixCls}-column-sorter`}>
<span
className={`${prefixCls}-column-sorter-up ${isAscend ? 'on' : 'off'}`}
title="↑"
onClick={() => this.toggleSortOrder('ascend', column)}
>
<Icon type="caret-up" />
</span>
<span
className={`${prefixCls}-column-sorter-down ${isDescend ? 'on' : 'off'}`}
title="↓"
onClick={() => this.toggleSortOrder('descend', column)}
>
<Icon type="caret-down" />
</span>
</div>
);
}
column.title = (
<span>
{column.title}
{sortButton}
{filterDropdown}
</span>
);
return column;
});
}
handleShowSizeChange = (current, pageSize) => {
const pagination = this.state.pagination;
pagination.onShowSizeChange(current, pageSize);
const nextPagination = {
...pagination,
pageSize,
current,
};
this.setState({ pagination: nextPagination });
2016-10-24 16:30:38 +08:00
const onChange = this.props.onChange;
if (onChange) {
onChange.apply(null, this.prepareParamsArguments({
...this.state,
2016-10-24 16:30:38 +08:00
pagination: nextPagination,
}));
2016-10-24 16:30:38 +08:00
}
}
renderPagination() {
// 强制不需要分页
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;
} else if (this.props.size as string === 'middle' || this.props.size === 'small') {
size = 'small';
}
2016-07-12 18:24:16 +08:00
let total = pagination.total || this.getLocalData().length;
return (total > 0) ? (
2016-07-12 18:24:16 +08:00
<Pagination
key="pagination"
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): [any, string[], Object] {
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);
}
return [pagination, filters, sorter];
}
findColumn(myKey) {
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();
let current;
let pageSize;
let state = this.state;
// 如果没有分页的话,默认全部展示
if (!this.hasPagination()) {
pageSize = Number.MAX_VALUE;
current = 1;
} else {
pageSize = state.pagination.pageSize;
current = this.getMaxCurrent(state.pagination.total || data.length);
}
// 分页
// ---
// 当数据量少于等于每页数量时,直接设置数据
// 否则进行读取分页数据
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());
}
getFlatCurrentPageData() {
return flatArray(this.getCurrentPageData());
}
2016-08-26 15:04:19 +08:00
recursiveSort(data, sorterFn) {
2016-10-24 16:30:38 +08:00
const { childrenColumnName = 'children' } = this.props;
return data.sort(sorterFn).map(item => (item[childrenColumnName] ? {
...item,
2017-10-08 17:58:42 +08:00
[childrenColumnName]: this.recursiveSort(item[childrenColumnName], sorterFn),
} : item));
2016-08-26 15:04:19 +08:00
}
getLocalData() {
const 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();
if (sorterFn) {
2016-08-26 15:04:19 +08:00
data = this.recursiveSort(data, sorterFn);
}
// 筛选
if (state.filters) {
Object.keys(state.filters).forEach((columnKey) => {
2016-12-03 15:51:44 +08:00
let col = this.findColumn(columnKey) as any;
if (!col) {
return;
}
let values = state.filters[columnKey] || [];
if (values.length === 0) {
return;
}
2016-10-24 16:30:38 +08:00
const onFilter = col.onFilter;
data = onFilter ? data.filter(record => {
return values.some(v => onFilter(v, record));
}) : data;
});
}
return data;
}
renderTable = (contextLocale) => {
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;
});
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}
2016-09-14 16:59:45 +08:00
prefixCls={prefixCls}
data={data}
columns={columns}
showHeader={showHeader}
className={classString}
expandIconColumnIndex={expandIconColumnIndex}
expandIconAsCell={expandIconAsCell}
2016-08-30 17:01:51 +08:00
emptyText={() => locale.emptyText}
/>
);
}
render() {
const { style, className, prefixCls } = this.props;
const data = this.getCurrentPageData();
const table = (
<LocaleReceiver
componentName="Table"
defaultLocale={defaultLocale.Table}
>
{this.renderTable}
</LocaleReceiver>
);
// if there is no pagination or no data,
// the height of spin should decrease by half of pagination
const paginationPatchClass = (this.hasPagination() && data && data.length !== 0)
? `${prefixCls}-with-pagination` : `${prefixCls}-without-pagination`;
let loading = this.props.loading;
2017-02-20 12:18:41 +08:00
if (typeof loading === 'boolean') {
loading = {
spinning: loading,
};
}
2017-02-20 12:18:41 +08:00
return (
<div
className={classNames(`${prefixCls}-wrapper`, className)}
style={style}
>
<Spin
2017-02-20 12:18:41 +08:00
{...loading}
className={loading ? `${paginationPatchClass} ${prefixCls}-spin-holder` : ''}
>
{table}
{this.renderPagination()}
</Spin>
</div>
);
}
}