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.
 
 

1409 lines
43 KiB

/* eslint-disable prefer-spread */
import * as React from 'react';
import omit from 'omit.js';
import RcTable, { INTERNAL_COL_DEFINE } from 'rc-table';
import * as PropTypes from 'prop-types';
import classNames from 'classnames';
import shallowEqual from 'shallowequal';
import { polyfill } from 'react-lifecycles-compat';
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 scrollTo from '../_util/scrollTo';
import {
TableProps,
InternalTableProps,
TableSize,
TableState,
TableComponents,
RowSelectionType,
TableLocale,
AdditionalCellProps,
ColumnProps,
CompareFn,
SortOrder,
TableStateFilters,
SelectionItemSelectFn,
SelectionInfo,
TableSelectWay,
TableRowSelection,
PaginationConfig,
PrepareParamsArgumentsReturn,
ExpandIconProps,
CheckboxPropsCache,
} from './interface';
import Pagination from '../pagination';
import Icon from '../icon';
import Spin, { SpinProps } from '../spin';
import { RadioChangeEvent } from '../radio';
import TransButton from '../_util/transButton';
import { CheckboxChangeEvent } from '../checkbox';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale/default';
import { ConfigConsumer, ConfigConsumerProps, RenderEmptyHandler } from '../config-provider';
import warning from '../_util/warning';
function noop() {}
function stopPropagation(e: React.SyntheticEvent<any>) {
e.stopPropagation();
}
function getRowSelection<T>(props: TableProps<T>): TableRowSelection<T> {
return props.rowSelection || {};
}
function getColumnKey<T>(column: ColumnProps<T>, index?: number) {
return column.key || column.dataIndex || index;
}
function isSameColumn<T>(a: ColumnProps<T> | null, b: ColumnProps<T> | null) {
if (a && b && a.key && a.key === b.key) {
return true;
}
return (
a === b ||
shallowEqual(a, b, (value: any, other: any) => {
// https://github.com/ant-design/ant-design/issues/12737
if (typeof value === 'function' && typeof other === 'function') {
return value === other || value.toString() === other.toString();
}
// https://github.com/ant-design/ant-design/issues/19398
if (Array.isArray(value) && Array.isArray(other)) {
return value === other || shallowEqual(value, other);
}
})
);
}
const defaultPagination = {
onChange: noop,
onShowSizeChange: noop,
};
/**
* Avoid creating new object, so that parent component's shouldComponentUpdate
* can works appropriately。
*/
const emptyObject = {};
const createComponents = (components: TableComponents = {}) => {
const bodyRow = components && components.body && components.body.row;
return {
...components,
body: {
...components.body,
row: createBodyRow(bodyRow),
},
};
};
function isTheSameComponents(components1: TableComponents = {}, components2: TableComponents = {}) {
return (
components1 === components2 ||
['table', 'header', 'body'].every((key: keyof TableComponents) =>
shallowEqual(components1[key], components2[key]),
)
);
}
function getFilteredValueColumns<T>(state: TableState<T>, columns?: ColumnProps<T>[]) {
return flatFilter(
columns || (state || {}).columns || [],
(column: ColumnProps<T>) => typeof column.filteredValue !== 'undefined',
);
}
function getFiltersFromColumns<T>(
state: TableState<T> = {} as TableState<T>,
columns?: ColumnProps<T>[],
) {
const filters: any = {};
getFilteredValueColumns<T>(state, columns).forEach((col: ColumnProps<T>) => {
const colKey = getColumnKey(col) as string;
filters[colKey] = col.filteredValue;
});
return filters;
}
function isFiltersChanged<T>(state: TableState<T>, filters: TableStateFilters): boolean {
if (Object.keys(filters).length !== Object.keys(state.filters).length) {
return true;
}
return Object.keys(filters).some(columnKey => filters[columnKey] !== state.filters[columnKey]);
}
class Table<T> extends React.Component<InternalTableProps<T>, TableState<T>> {
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,
getPopupContainer: PropTypes.func,
};
static defaultProps = {
dataSource: [],
useFixedHeader: false,
className: '',
size: 'default' as TableSize,
loading: false,
bordered: false,
indentSize: 20,
locale: {},
rowKey: 'key',
showHeader: true,
sortDirections: ['ascend', 'descend'],
childrenColumnName: 'children',
};
static getDerivedStateFromProps(nextProps: InternalTableProps<any>, prevState: TableState<any>) {
const { prevProps } = prevState;
const columns =
nextProps.columns || normalizeColumns(nextProps.children as React.ReactChildren);
let nextState: TableState<any> = {
...prevState,
prevProps: nextProps,
columns,
};
if ('pagination' in nextProps || 'pagination' in prevProps) {
const newPagination = {
...defaultPagination,
...prevState.pagination,
...nextProps.pagination,
};
newPagination.current = newPagination.current || 1;
newPagination.pageSize = newPagination.pageSize || 10;
nextState = {
...nextState,
pagination: nextProps.pagination !== false ? newPagination : emptyObject,
};
}
if (nextProps.rowSelection && 'selectedRowKeys' in nextProps.rowSelection) {
nextProps.store.setState({
selectedRowKeys: nextProps.rowSelection.selectedRowKeys || [],
});
} else if (prevProps.rowSelection && !nextProps.rowSelection) {
nextProps.store.setState({
selectedRowKeys: [],
});
}
if ('dataSource' in nextProps && nextProps.dataSource !== prevProps.dataSource) {
nextProps.store.setState({
selectionDirty: false,
});
}
// https://github.com/ant-design/ant-design/issues/10133
nextProps.setCheckboxPropsCache({});
// Update filters
const filteredValueColumns = getFilteredValueColumns(nextState, nextState.columns);
if (filteredValueColumns.length > 0) {
const filtersFromColumns = getFiltersFromColumns(nextState, nextState.columns);
const newFilters = { ...nextState.filters };
Object.keys(filtersFromColumns).forEach(key => {
newFilters[key] = filtersFromColumns[key];
});
if (isFiltersChanged(nextState, newFilters)) {
nextState = {
...nextState,
filters: newFilters,
};
}
}
if (!isTheSameComponents(nextProps.components, prevProps.components)) {
const components = createComponents(nextProps.components);
nextState = {
...nextState,
components,
};
}
return nextState;
}
row: React.ComponentType<any>;
rcTable: any;
constructor(props: InternalTableProps<T>) {
super(props);
const { expandedRowRender, columns: columnsProp } = 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.',
);
if (expandedRowRender && (columnsProp || []).some(({ fixed }) => !!fixed)) {
warning(
false,
'Table',
'`expandedRowRender` and `Column.fixed` are not compatible. Please use one of them at one time.',
);
}
const columns = columnsProp || normalizeColumns(props.children as React.ReactChildren);
this.state = {
...this.getDefaultSortOrder(columns || []),
// ε‡ε°‘ηŠΆζ€
filters: getFiltersFromColumns<T>(),
pagination: this.getDefaultPagination(props),
pivot: undefined,
prevProps: props,
components: createComponents(props.components),
columns,
};
}
componentDidUpdate() {
const { columns, sortColumn, sortOrder } = this.state;
if (this.getSortOrderColumns(columns).length > 0) {
const sortState = this.getSortStateFromColumns(columns);
if (!isSameColumn(sortState.sortColumn, sortColumn) || sortState.sortOrder !== sortOrder) {
this.setState(sortState);
}
}
}
setTableRef = (table: any) => {
this.rcTable = table;
};
getCheckboxPropsByItem = (item: T, index: number) => {
const rowSelection = getRowSelection(this.props);
if (!rowSelection.getCheckboxProps) {
return {};
}
const key = this.getRecordKey(item, index);
// Cache checkboxProps
if (!this.props.checkboxPropsCache[key]) {
this.props.checkboxPropsCache[key] = rowSelection.getCheckboxProps(item) || {};
const checkboxProps = this.props.checkboxPropsCache[key];
warning(
!('checked' in checkboxProps) && !('defaultChecked' in checkboxProps),
'Table',
'Do not set `checked` or `defaultChecked` in `getCheckboxProps`. Please use `selectedRowKeys` instead.',
);
}
return this.props.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,
}
: {};
}
getSortOrderColumns(columns?: ColumnProps<T>[]) {
return flatFilter(
columns || (this.state || {}).columns || [],
(column: ColumnProps<T>) => 'sortOrder' in column,
);
}
getDefaultSortOrder(columns?: ColumnProps<T>[]) {
const definedSortState = this.getSortStateFromColumns(columns);
const defaultSortedColumn = flatFilter(columns || [], (column: ColumnProps<T>) => {
return column.defaultSortOrder != null;
})[0];
if (defaultSortedColumn && !definedSortState.sortColumn) {
return {
sortColumn: defaultSortedColumn,
sortOrder: defaultSortedColumn.defaultSortOrder,
};
}
return definedSortState;
}