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.
 
 

870 lines
26 KiB

import React from 'react';
import RcTable from 'rc-table';
import FilterDropdown from './filterDropdown';
import Pagination, { PaginationProps } from '../pagination';
import Icon from '../icon';
import Spin from '../spin';
import classNames from 'classnames';
import { flatArray, treeMap, normalizeColumns } from './util';
import assign from 'object-assign';
import splitObject from '../_util/splitObject';
import warning from '../_util/warning';
import createStore, { Store } from './createStore';
import SelectionBox from './SelectionBox';
import SelectionCheckboxAll from './SelectionCheckboxAll';
import Column, { ColumnProps } from './Column';
import ColumnGroup from './ColumnGroup';
function noop() {
}
function stopPropagation(e) {
e.stopPropagation();
if (e.nativeEvent.stopImmediatePropagation) {
e.nativeEvent.stopImmediatePropagation();
}
}
const defaultLocale = {
filterTitle: '筛选',
filterConfirm: '确定',
filterReset: '重置',
emptyText: <span><Icon type="frown-o" /></span>,
};
const defaultPagination = {
onChange: noop,
onShowSizeChange: noop,
};
export interface TableRowSelection<T> {
type?: 'checkbox' | 'radio';
selectedRowKeys?: string[];
onChange?: (selectedRowKeys: string[], selectedRows: Object[]) => any;
getCheckboxProps?: (record: T) => Object;
onSelect?: (record: T, selected: boolean, selectedRows: Object[]) => any;
onSelectAll?: (selected: boolean, selectedRows: Object[], changeRows: Object[]) => any;
}
export interface TableProps<T> {
prefixCls?: string;
dropdownPrefixCls?: string;
rowSelection?: TableRowSelection<T>;
pagination?: PaginationProps | boolean;
size?: 'default' | 'small';
dataSource?: T[];
columns?: ColumnProps<T>[];
rowKey?: string | ((record: T, index: number) => string);
rowClassName?: (record: T, index: number) => string;
expandedRowRender?: any;
defaultExpandedRowKeys?: string[];
expandedRowKeys?: string[];
expandIconAsCell?: boolean;
expandIconColumnIndex?: number;
onChange?: (pagination: PaginationProps | boolean, filters: string[], sorter: Object) => any;
loading?: boolean;
locale?: Object;
indentSize?: number;
onRowClick?: (record: T, index: number) => any;
useFixedHeader?: boolean;
bordered?: boolean;
showHeader?: boolean;
footer?: (currentPageData: Object[]) => React.ReactNode;
title?: (currentPageData: Object[]) => React.ReactNode;
scroll?: { x?: boolean | number, y?: boolean | number};
childrenColumnName?: string;
bodyStyle?: React.CSSProperties;
className?: string;
}
export interface TableContext {
antLocale?: {
Table?: any,
};
}
export default class Table<T> extends React.Component<TableProps<T>, any> {
static Column = Column;
static ColumnGroup = ColumnGroup;
static propTypes = {
dataSource: React.PropTypes.array,
columns: React.PropTypes.array,
prefixCls: React.PropTypes.string,
useFixedHeader: React.PropTypes.bool,
rowSelection: React.PropTypes.object,
className: React.PropTypes.string,
size: React.PropTypes.string,
loading: React.PropTypes.bool,
bordered: React.PropTypes.bool,
onChange: React.PropTypes.func,
locale: React.PropTypes.object,
dropdownPrefixCls: React.PropTypes.string,
};
static defaultProps = {
dataSource: [],
prefixCls: 'ant-table',
useFixedHeader: false,
rowSelection: null,
className: '',
size: 'large',
loading: false,
bordered: false,
indentSize: 20,
locale: {},
rowKey: 'key',
};
static contextTypes = {
antLocale: React.PropTypes.object,
};
context: TableContext;
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](http://ant.design/components/table/#components-table-demo-fixed-columns) ' +
'instead.'
);
const pagination = props.pagination || {};
this.columns = props.columns || normalizeColumns(props.children);
this.state = assign({}, this.getSortStateFromColumns(), {
// 减少状态
filters: this.getFiltersFromColumns(),
pagination: this.hasPagination() ?
assign({}, defaultPagination, pagination, {
current: pagination.defaultCurrent || pagination.current || 1,
pageSize: pagination.defaultPageSize || pagination.pageSize || 10,
}) : {},
});
this.CheckboxPropsCache = {};
this.store = createStore({
selectedRowKeys: (props.rowSelection || {}).selectedRowKeys || [],
selectionDirty: false,
});
}
getCheckboxPropsByItem = (item) => {
const { rowSelection = {} } = this.props;
if (!rowSelection.getCheckboxProps) {
return {};
}
const key = this.getRecordKey(item);
// 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 => this.getCheckboxPropsByItem(item).defaultChecked)
.map((record, rowIndex) => this.getRecordKey(record, rowIndex));
}
getLocale() {
let locale = {};
if (this.context.antLocale && this.context.antLocale.Table) {
locale = this.context.antLocale.Table;
}
return assign({}, defaultLocale, locale, this.props.locale);
}
componentWillReceiveProps(nextProps) {
if (('pagination' in nextProps) && nextProps.pagination !== false) {
this.setState(previousState => {
const newPagination = assign({}, defaultPagination, previousState.pagination, nextProps.pagination);
newPagination.current = newPagination.current || 1;
return { pagination: newPagination };
});
}
// dataSource 的变化会清空选中项
if ('dataSource' in nextProps &&
nextProps.dataSource !== this.props.dataSource) {
this.store.setState({
selectionDirty: false,
});
this.CheckboxPropsCache = {};
}
if (nextProps.rowSelection &&
'selectedRowKeys' in nextProps.rowSelection) {
this.store.setState({
selectedRowKeys: nextProps.rowSelection.selectedRowKeys || [],
});
const { rowSelection } = this.props;
if (rowSelection && (
nextProps.rowSelection.getCheckboxProps !== rowSelection.getCheckboxProps
)) {
this.CheckboxPropsCache = {};
}
}
if (this.getSortOrderColumns(nextProps.columns).length > 0) {
const sortState = this.getSortStateFromColumns(nextProps.columns);
if (sortState.sortColumn !== this.state.sortColumn ||
sortState.sortOrder !== this.state.sortOrder) {
this.setState(sortState);
}
}
const filteredValueColumns = this.getFilteredValueColumns(nextProps.columns);
if (filteredValueColumns.length > 0) {
const filtersFromColumns = this.getFiltersFromColumns(nextProps.columns);
const newFilters = assign({}, this.state.filters);
Object.keys(filtersFromColumns).forEach(key => {
newFilters[key] = filtersFromColumns[key];
});
if (this.isFiltersChanged(newFilters)) {
this.setState({ filters: newFilters });
}
}
this.columns = nextProps.columns || normalizeColumns(nextProps.children);
}
setSelectedRowKeys(selectedRowKeys, { selectWay, record, checked, changeRowKeys }: any) {
const { rowSelection = {} } = 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);
} else if (selectWay === 'onSelectAll' && rowSelection.onSelectAll) {
const changeRows = data.filter(
(row, i) => changeRowKeys.indexOf(this.getRecordKey(row, i)) >= 0
);
rowSelection.onSelectAll(checked, selectedRows, changeRows);
}
}
hasPagination() {
return 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 (columns || this.columns || []).filter(column => 'sortOrder' in column);
}
getFilteredValueColumns(columns?) {
return (columns || this.columns || []).filter(column => column.filteredValue);
}
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);
}
const onChange = this.props.onChange;
if (onChange) {
onChange.apply(null, this.prepareParamsArguments(assign({}, this.state, newState)));
}
}
handleFilter = (column, nextFilters) => {
const props = this.props;
let pagination = assign({}, this.state.pagination);
const filters = assign({}, this.state.filters, {
[this.getColumnKey(column)]: nextFilters,
});