Table.tsx 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  1. /* eslint-disable no-nested-ternary */
  2. /* eslint-disable prefer-const */
  3. /* eslint-disable prefer-destructuring */
  4. /* eslint-disable no-shadow */
  5. /* eslint-disable no-param-reassign */
  6. /* eslint-disable max-len */
  7. /* eslint-disable react/no-did-update-set-state */
  8. /* eslint-disable eqeqeq */
  9. /* eslint-disable max-lines-per-function */
  10. import React, { ReactNode, createRef, isValidElement } from 'react';
  11. import PropTypes from 'prop-types';
  12. import classnames from 'classnames';
  13. import {
  14. get,
  15. noop,
  16. includes,
  17. find,
  18. findIndex,
  19. some,
  20. debounce,
  21. flattenDeep,
  22. each,
  23. omit,
  24. isNull,
  25. difference,
  26. isFunction,
  27. isObject
  28. } from 'lodash';
  29. import {
  30. mergeQueries,
  31. equalWith,
  32. mergeColumns,
  33. isAnyFixedRight,
  34. assignColumnKeys,
  35. flattenColumns,
  36. getAllDisabledRowKeys
  37. } from '@douyinfe/semi-foundation/table/utils';
  38. import Store from '@douyinfe/semi-foundation/utils/Store';
  39. import TableFoundation, { TableAdapter, BasePageData, BaseRowKeyType, BaseHeadWidth } from '@douyinfe/semi-foundation/table/foundation';
  40. import { TableSelectionCellEvent } from '@douyinfe/semi-foundation/table/tableSelectionCellFoundation';
  41. import { strings, cssClasses, numbers } from '@douyinfe/semi-foundation/table/constants';
  42. import '@douyinfe/semi-foundation/table/table.scss';
  43. import Spin from '../spin';
  44. import BaseComponent from '../_base/baseComponent';
  45. import LocaleConsumer from '../locale/localeConsumer';
  46. import ColumnShape from './ColumnShape';
  47. import getColumns from './getColumns';
  48. import TableContext, { TableContextProps } from './table-context';
  49. import TableContextProvider from './TableContextProvider';
  50. import ColumnSelection from './ColumnSelection';
  51. import TablePagination from './TablePagination';
  52. import ColumnFilter, { OnSelectData } from './ColumnFilter';
  53. import ColumnSorter from './ColumnSorter';
  54. import ExpandedIcon from './CustomExpandIcon';
  55. import HeadTable, { HeadTableProps } from './HeadTable';
  56. import BodyTable, { BodyProps } from './Body';
  57. import { measureScrollbar, logger, cloneDeep, mergeComponents } from './utils';
  58. import {
  59. ColumnProps,
  60. TablePaginationProps,
  61. BodyScrollEvent,
  62. BodyScrollPosition,
  63. ExpandIcon,
  64. ColumnTitleProps,
  65. Pagination,
  66. RenderPagination,
  67. TableLocale,
  68. TableProps,
  69. TableComponents,
  70. RowSelectionProps,
  71. Data
  72. } from './interface';
  73. import { ArrayElement } from '../_base/base';
  74. export type NormalTableProps<RecordType extends Record<string, any> = Data> = Omit<TableProps<RecordType>, 'resizable'>;
  75. export interface NormalTableState<RecordType extends Record<string, any> = Data> {
  76. cachedColumns?: ColumnProps<RecordType>[];
  77. cachedChildren?: React.ReactNode;
  78. flattenColumns?: ColumnProps<RecordType>[];
  79. components?: TableComponents;
  80. queries?: ColumnProps<RecordType>[];
  81. dataSource?: RecordType[];
  82. flattenData?: RecordType[];
  83. expandedRowKeys?: (string | number)[];
  84. rowSelection?: TableStateRowSelection<RecordType>;
  85. pagination?: Pagination;
  86. groups?: Map<string, RecordType[]>;
  87. allRowKeys?: (string | number)[];
  88. disabledRowKeys?: (string | number)[];
  89. disabledRowKeysSet?: Set<string | number>;
  90. headWidths?: Array<Array<BaseHeadWidth>>;
  91. bodyHasScrollBar?: boolean;
  92. prePropRowSelection?: TableStateRowSelection<RecordType>;
  93. tableWidth?: number;
  94. prePagination?: Pagination;
  95. }
  96. export type TableStateRowSelection<RecordType extends Record<string, any> = Data> = (RowSelectionProps<RecordType> & { selectedRowKeysSet?: Set<(string | number)> }) | boolean;
  97. export interface RenderTableProps<RecordType> extends HeadTableProps, BodyProps {
  98. filteredColumns: ColumnProps<RecordType>[];
  99. useFixedHeader: boolean;
  100. bodyRef: React.MutableRefObject<HTMLDivElement> | ((instance: any) => void);
  101. rowSelection: TableStateRowSelection<RecordType>;
  102. bodyHasScrollBar: boolean;
  103. }
  104. class Table<RecordType extends Record<string, any>> extends BaseComponent<NormalTableProps<RecordType>, NormalTableState<RecordType>> {
  105. static contextType = TableContext;
  106. static propTypes = {
  107. className: PropTypes.string,
  108. style: PropTypes.object,
  109. prefixCls: PropTypes.string,
  110. components: PropTypes.any,
  111. bordered: PropTypes.bool,
  112. loading: PropTypes.bool,
  113. size: PropTypes.oneOf(strings.SIZES),
  114. tableLayout: PropTypes.oneOf(strings.LAYOUTS),
  115. columns: PropTypes.arrayOf(PropTypes.shape(ColumnShape)),
  116. hideExpandedColumn: PropTypes.bool,
  117. id: PropTypes.string,
  118. expandIcon: PropTypes.oneOfType([PropTypes.bool, PropTypes.func, PropTypes.node]),
  119. expandCellFixed: PropTypes.oneOf(strings.FIXED_SET),
  120. title: PropTypes.oneOfType([PropTypes.string, PropTypes.node, PropTypes.func]),
  121. onHeaderRow: PropTypes.func,
  122. showHeader: PropTypes.bool,
  123. indentSize: PropTypes.number,
  124. rowKey: PropTypes.oneOfType([PropTypes.func, PropTypes.string, PropTypes.number]),
  125. onRow: PropTypes.func,
  126. onExpandedRowsChange: PropTypes.func,
  127. onExpand: PropTypes.func,
  128. rowExpandable: PropTypes.func,
  129. expandedRowRender: PropTypes.func,
  130. expandedRowKeys: PropTypes.array,
  131. defaultExpandAllRows: PropTypes.bool,
  132. expandAllRows: PropTypes.bool,
  133. defaultExpandAllGroupRows: PropTypes.bool,
  134. expandAllGroupRows: PropTypes.bool,
  135. defaultExpandedRowKeys: PropTypes.array,
  136. pagination: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
  137. renderPagination: PropTypes.func,
  138. footer: PropTypes.oneOfType([PropTypes.func, PropTypes.string, PropTypes.node]),
  139. empty: PropTypes.node,
  140. dataSource: PropTypes.array,
  141. childrenRecordName: PropTypes.string, // children data property name
  142. rowSelection: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
  143. onChange: PropTypes.func,
  144. scroll: PropTypes.shape({
  145. x: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.bool]),
  146. y: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  147. }),
  148. groupBy: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.func]),
  149. renderGroupSection: PropTypes.oneOfType([PropTypes.func]),
  150. onGroupedRow: PropTypes.func,
  151. clickGroupedRowToExpand: PropTypes.bool,
  152. virtualized: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
  153. dropdownPrefixCls: PropTypes.string, // TODO: future api
  154. expandRowByClick: PropTypes.bool, // TODO: future api
  155. getVirtualizedListRef: PropTypes.func, // TODO: future api
  156. };
  157. static defaultProps = {
  158. // rowExpandable: stubTrue,
  159. tableLayout: '',
  160. dataSource: [] as [],
  161. prefixCls: cssClasses.PREFIX,
  162. rowSelection: null as null,
  163. className: '',
  164. childrenRecordName: 'children',
  165. size: 'default',
  166. loading: false,
  167. bordered: false,
  168. expandCellFixed: false,
  169. hideExpandedColumn: true,
  170. showHeader: true,
  171. indentSize: numbers.DEFAULT_INDENT_WIDTH,
  172. onChange: noop,
  173. pagination: true,
  174. rowKey: 'key',
  175. defaultExpandedRowKeys: [] as [],
  176. defaultExpandAllRows: false,
  177. defaultExpandAllGroupRows: false,
  178. expandAllRows: false,
  179. expandAllGroupRows: false,
  180. onFilterDropdownVisibleChange: noop,
  181. onExpand: noop,
  182. onExpandedRowsChange: noop,
  183. expandRowByClick: false,
  184. };
  185. get adapter(): TableAdapter<RecordType> {
  186. return {
  187. ...super.adapter,
  188. resetScrollY: () => {
  189. if (this.bodyWrapRef.current) {
  190. this.bodyWrapRef.current.scrollTop = 0;
  191. }
  192. },
  193. setSelectedRowKeys: selectedRowKeys => {
  194. this.setState({ rowSelection: {
  195. ...this.state.rowSelection as Record<string, any>,
  196. selectedRowKeys: [...selectedRowKeys],
  197. selectedRowKeysSet: new Set(selectedRowKeys),
  198. } });
  199. },
  200. setDisabledRowKeys: disabledRowKeys => {
  201. this.setState({ disabledRowKeys, disabledRowKeysSet: new Set(disabledRowKeys) });
  202. },
  203. setCurrentPage: currentPage => {
  204. const { pagination } = this.state;
  205. if (typeof pagination === 'object') {
  206. this.setState({ pagination: { ...pagination, currentPage } });
  207. } else {
  208. this.setState({ pagination: { currentPage } });
  209. }
  210. },
  211. setPagination: pagination => this.setState({ pagination }),
  212. setGroups: groups => this.setState({ groups }),
  213. setDataSource: dataSource => this.setState({ dataSource }),
  214. setExpandedRowKeys: expandedRowKeys => this.setState({ expandedRowKeys: [...expandedRowKeys] }),
  215. setQuery: (query = {}) => {
  216. let queries = [...this.state.queries];
  217. queries = mergeQueries(query, queries);
  218. this.setState({ queries });
  219. },
  220. // Update queries when filtering or sorting
  221. setQueries: (queries: ColumnProps<RecordType>[]) => this.setState({ queries }),
  222. setFlattenData: flattenData => this.setState({ flattenData }),
  223. setAllRowKeys: allRowKeys => this.setState({ allRowKeys }),
  224. setHoveredRowKey: hoveredRowKey => {
  225. this.store.setState({ hoveredRowKey });
  226. },
  227. setCachedFilteredSortedDataSource: filteredSortedDataSource => {
  228. this.cachedFilteredSortedDataSource = filteredSortedDataSource;
  229. },
  230. setCachedFilteredSortedRowKeys: filteredSortedRowKeys => {
  231. this.cachedFilteredSortedRowKeys = filteredSortedRowKeys;
  232. this.cachedFilteredSortedRowKeysSet = new Set(filteredSortedRowKeys);
  233. },
  234. getCurrentPage: () => get(this.state, 'pagination.currentPage', 1),
  235. getCurrentPageSize: () => get(this.state, 'pagination.pageSize', numbers.DEFAULT_PAGE_SIZE),
  236. getCachedFilteredSortedDataSource: () => this.cachedFilteredSortedDataSource,
  237. getCachedFilteredSortedRowKeys: () => this.cachedFilteredSortedRowKeys,
  238. getCachedFilteredSortedRowKeysSet: () => this.cachedFilteredSortedRowKeysSet,
  239. notifyFilterDropdownVisibleChange: (visible, dataIndex) =>
  240. this._invokeColumnFn(dataIndex, 'onFilterDropdownVisibleChange', visible),
  241. notifyChange: (...args) => this.props.onChange(...args),
  242. notifyExpand: (...args) => this.props.onExpand(...args),
  243. notifyExpandedRowsChange: (...args) => this.props.onExpandedRowsChange(...args),
  244. notifySelect: (...args) => this._invokeRowSelection('onSelect', ...args),
  245. notifySelectAll: (...args) => this._invokeRowSelection('onSelectAll', ...args),
  246. notifySelectInvert: (...args) => this._invokeRowSelection('onSelectInvert', ...args),
  247. notifySelectionChange: (...args) => this._invokeRowSelection('onChange', ...args),
  248. isAnyColumnFixed: (columns: ColumnProps<RecordType>[]) =>
  249. some(this.getColumns(columns || this.props.columns, this.props.children), column => Boolean(column.fixed)),
  250. useFixedHeader: () => {
  251. const { scroll } = this.props;
  252. if (get(scroll, 'y')) {
  253. return true;
  254. }
  255. return false;
  256. },
  257. setHeadWidths: (headWidths: Array<BaseHeadWidth>, index = 0) => {
  258. if (!equalWith(this.state.headWidths[index], headWidths)) {
  259. // The map call depends on the last state
  260. this.setState(state => {
  261. const newHeadWidths: Array<Array<BaseHeadWidth>> = [...state.headWidths];
  262. newHeadWidths[index] = [...headWidths];
  263. return { headWidths: newHeadWidths };
  264. });
  265. }
  266. },
  267. getHeadWidths: (index = 0) => {
  268. if (this.state.headWidths.length && typeof index === 'number') {
  269. const configs = this.state.headWidths[index] || [];
  270. return configs.map(item => item.width);
  271. }
  272. return [];
  273. },
  274. // This method is called by row rendering function
  275. getCellWidths: (flattenedColumns: ColumnProps<RecordType>[], flattenedWidths: BaseHeadWidth[] = null, ignoreScrollBarKey = false): number[] => {
  276. if (Array.isArray(flattenedColumns) && flattenedColumns.length) {
  277. flattenedWidths =
  278. flattenedWidths == null && this.state.headWidths.length ?
  279. flattenDeep(this.state.headWidths) :
  280. [];
  281. if (
  282. Array.isArray(flattenedWidths) &&
  283. flattenedWidths.length
  284. ) {
  285. return flattenedColumns.reduce((result, column) => {
  286. const found =
  287. column.key === strings.DEFAULT_KEY_COLUMN_SCROLLBAR && ignoreScrollBarKey ?
  288. null :
  289. find(
  290. flattenedWidths,
  291. item => item && item.key != null && item.key === column.key
  292. );
  293. if (found) {
  294. result.push(found.width);
  295. }
  296. return result;
  297. }, [] as number[]);
  298. }
  299. }
  300. return [];
  301. },
  302. mergedRowExpandable: record => {
  303. const { expandedRowRender, childrenRecordName, rowExpandable } = this.props;
  304. const children = get(record, childrenRecordName);
  305. const hasExpandedRowRender = typeof expandedRowRender === 'function';
  306. const hasRowExpandable = typeof rowExpandable === 'function';
  307. const hasChildren = Array.isArray(children) && children.length;
  308. const strictExpandableResult = hasRowExpandable && rowExpandable(record);
  309. const looseExpandableResult = !hasRowExpandable || strictExpandableResult;
  310. return (
  311. ((hasExpandedRowRender || hasChildren) && looseExpandableResult) ||
  312. (!(hasExpandedRowRender || hasChildren) && strictExpandableResult)
  313. );
  314. },
  315. isAnyColumnUseFullRender: (columns: ColumnProps<RecordType>[]) =>
  316. some(columns, column => Boolean(column.useFullRender)),
  317. getNormalizeColumns: () => this.normalizeColumns,
  318. getHandleColumns: () => this.handleColumns,
  319. getMergePagination: () => this.mergePagination,
  320. setBodyHasScrollbar: bodyHasScrollBar => {
  321. if (bodyHasScrollBar !== this.state.bodyHasScrollBar) {
  322. this.setState({ bodyHasScrollBar });
  323. }
  324. }
  325. };
  326. }
  327. bodyWrapRef: React.MutableRefObject<HTMLDivElement>;
  328. rootWrapRef: React.MutableRefObject<HTMLDivElement>;
  329. wrapRef: React.MutableRefObject<HTMLDivElement>;
  330. headerWrapRef: React.MutableRefObject<HTMLDivElement>;
  331. debouncedWindowResize: () => void;
  332. cachedFilteredSortedDataSource: RecordType[];
  333. cachedFilteredSortedRowKeys: BaseRowKeyType[];
  334. cachedFilteredSortedRowKeysSet: Set<string | number>;
  335. store: Store;
  336. lastScrollTop!: number;
  337. lastScrollLeft!: number;
  338. scrollPosition!: BodyScrollPosition;
  339. position!: BodyScrollPosition;
  340. foundation: TableFoundation<RecordType>;
  341. constructor(props: NormalTableProps<RecordType>, context: TableContextProps) {
  342. super(props);
  343. this.foundation = new TableFoundation<RecordType>(this.adapter);
  344. // columns cannot be deepClone, otherwise the comparison will be false
  345. const columns = this.getColumns(props.columns, props.children);
  346. const cachedflattenColumns = flattenColumns(columns);
  347. this.state = {
  348. /**
  349. * Cached props
  350. */
  351. cachedColumns: columns, // update cachedColumns after columns or children change
  352. cachedChildren: props.children,
  353. flattenColumns: cachedflattenColumns,
  354. components: mergeComponents(props.components, props.virtualized), // cached components
  355. /**
  356. * State calculated based on prop
  357. */
  358. queries: cloneDeep(cachedflattenColumns), // flatten columns, update when sorting or filtering
  359. dataSource: [], // data after paging
  360. flattenData: [],
  361. expandedRowKeys: [...(props.expandedRowKeys || []), ...(props.defaultExpandedRowKeys || [])], // cached expandedRowKeys
  362. rowSelection: props.rowSelection ? isObject(props.rowSelection) ? { ...props.rowSelection } : {} : null,
  363. pagination:
  364. props.pagination && typeof props.pagination === 'object' ?
  365. { ...props.pagination } :
  366. props.pagination || false,
  367. /**
  368. * Internal state
  369. */
  370. groups: null,
  371. allRowKeys: [], // row keys after paging
  372. disabledRowKeys: [], // disabled row keys after paging
  373. disabledRowKeysSet: new Set(),
  374. headWidths: [], // header cell width
  375. bodyHasScrollBar: false,
  376. prePropRowSelection: undefined,
  377. prePagination: undefined
  378. };
  379. this.rootWrapRef = createRef();
  380. this.wrapRef = createRef(); // table's outside wrap
  381. this.bodyWrapRef = createRef();
  382. this.headerWrapRef = createRef();
  383. this.store = new Store({
  384. hoveredRowKey: null,
  385. });
  386. this.setScrollPosition('left');
  387. this.debouncedWindowResize = debounce(this.handleWindowResize, 150);
  388. this.cachedFilteredSortedDataSource = [];
  389. this.cachedFilteredSortedRowKeys = [];
  390. this.cachedFilteredSortedRowKeysSet = new Set();
  391. }
  392. static getDerivedStateFromProps(props: NormalTableProps, state: NormalTableState) {
  393. const willUpdateStates: Partial<NormalTableState> = {};
  394. const { rowSelection, dataSource, childrenRecordName, rowKey, pagination } = props;
  395. props.columns && props.children && logger.warn('columns should not given by object and children at the same time');
  396. if (props.columns && props.columns !== state.cachedColumns) {
  397. const newFlattenColumns = flattenColumns(props.columns);
  398. willUpdateStates.flattenColumns = newFlattenColumns;
  399. willUpdateStates.queries = mergeColumns(state.queries, newFlattenColumns, null, false);
  400. willUpdateStates.cachedColumns = props.columns;
  401. willUpdateStates.cachedChildren = null;
  402. } else if (props.children && props.children !== state.cachedChildren) {
  403. const newFlattenColumns = flattenColumns(getColumns(props.children));
  404. const columns = mergeColumns(state.queries, newFlattenColumns, null, false);
  405. willUpdateStates.flattenColumns = newFlattenColumns;
  406. willUpdateStates.queries = [...columns];
  407. willUpdateStates.cachedColumns = [...columns];
  408. willUpdateStates.cachedChildren = props.children;
  409. }
  410. // Update controlled selection column
  411. if (rowSelection !== state.prePropRowSelection) {
  412. let newSelectionStates: TableStateRowSelection = {};
  413. if (isObject(state.rowSelection)) {
  414. newSelectionStates = { ...newSelectionStates, ...state.rowSelection };
  415. }
  416. if (isObject(rowSelection)) {
  417. newSelectionStates = { ...newSelectionStates, ...rowSelection };
  418. }
  419. const selectedRowKeys = get(rowSelection, 'selectedRowKeys');
  420. const getCheckboxProps = get(rowSelection, 'getCheckboxProps');
  421. if (selectedRowKeys && Array.isArray(selectedRowKeys)) {
  422. newSelectionStates.selectedRowKeysSet = new Set(selectedRowKeys);
  423. }
  424. // The return value of getCheckboxProps affects the disabled rows
  425. if (isFunction(getCheckboxProps)) {
  426. const disabledRowKeys = getAllDisabledRowKeys({ dataSource, getCheckboxProps, childrenRecordName, rowKey });
  427. willUpdateStates.disabledRowKeys = disabledRowKeys;
  428. willUpdateStates.disabledRowKeysSet = new Set(disabledRowKeys);
  429. }
  430. willUpdateStates.rowSelection = newSelectionStates;
  431. willUpdateStates.prePropRowSelection = rowSelection;
  432. }
  433. if (pagination !== state.prePagination) {
  434. let newPagination: Pagination = {};
  435. if (isObject(state.pagination)) {
  436. newPagination = { ...newPagination, ...state.pagination };
  437. }
  438. if (isObject(pagination)) {
  439. newPagination = { ...newPagination, ...pagination };
  440. }
  441. willUpdateStates.pagination = newPagination;
  442. willUpdateStates.prePagination = pagination;
  443. }
  444. return willUpdateStates;
  445. }
  446. componentDidMount() {
  447. super.componentDidMount();
  448. if (this.adapter.isAnyColumnFixed() || (this.props.showHeader && this.adapter.useFixedHeader())) {
  449. this.handleWindowResize();
  450. window.addEventListener('resize', this.debouncedWindowResize);
  451. }
  452. }
  453. // TODO: Extract the setState operation to the adapter or getDerivedStateFromProps function
  454. componentDidUpdate(prevProps: NormalTableProps<RecordType>, prevState: NormalTableState<RecordType>) {
  455. const {
  456. dataSource,
  457. expandedRowKeys,
  458. expandAllRows,
  459. expandAllGroupRows,
  460. virtualized,
  461. components,
  462. pagination: propsPagination
  463. } = this.props;
  464. const {
  465. pagination: statePagination,
  466. queries: stateQueries,
  467. cachedColumns: stateCachedColumns,
  468. cachedChildren: stateCachedChildren,
  469. groups: stateGroups,
  470. } = this.state;
  471. /**
  472. * State related to paging
  473. *
  474. * @param dataSource
  475. * @param groups
  476. * @param pagination
  477. * @param disabledRowKeys
  478. * @param allRowKeys
  479. * @param queries
  480. */
  481. const states: Partial<NormalTableState<RecordType>> = {};
  482. this._warnIfNoKey();
  483. /**
  484. * The state that needs to be updated after props changes
  485. */
  486. // Update controlled expand column
  487. if (Array.isArray(expandedRowKeys) && expandedRowKeys !== prevProps.expandedRowKeys) {
  488. this.setState({ expandedRowKeys });
  489. }
  490. // Update components
  491. if (components !== prevProps.components || virtualized !== prevProps.virtualized) {
  492. this.setState({ components: mergeComponents(components, virtualized) });
  493. }
  494. // Update the default expanded column
  495. if (
  496. expandAllRows !== prevProps.expandAllRows ||
  497. expandAllGroupRows !== prevProps.expandAllGroupRows
  498. ) {
  499. this.foundation.initExpandedRowKeys({ groups: stateGroups });
  500. }
  501. /**
  502. * After dataSource is updated || (cachedColumns || cachedChildren updated)
  503. * 1. Cache filtered sorted data and a collection of data rows, stored in this
  504. * 2. Update pager and group, stored in state
  505. */
  506. if (dataSource !== prevProps.dataSource || stateCachedColumns !== prevState.cachedColumns || stateCachedChildren !== prevState.cachedChildren) {
  507. // TODO: foundation.getFilteredSortedDataSource has side effects and will be modified to the dataSource reference
  508. // Temporarily use _dataSource=[...dataSource] for processing
  509. const _dataSource = [...dataSource];
  510. const filteredSortedDataSource = this.foundation.getFilteredSortedDataSource(_dataSource, stateQueries);
  511. this.foundation.setCachedFilteredSortedDataSource(filteredSortedDataSource);
  512. states.dataSource = filteredSortedDataSource;
  513. if (this.props.groupBy) {
  514. states.groups = null;
  515. }
  516. }
  517. // when dataSource has change, should reset currentPage
  518. if (dataSource !== prevProps.dataSource) {
  519. states.pagination = isObject(statePagination) ? {
  520. ...statePagination,
  521. currentPage: isObject(propsPagination) && propsPagination.currentPage ? propsPagination.currentPage : 1,
  522. } : statePagination;
  523. }
  524. if (Object.keys(states).length) {
  525. const {
  526. // eslint-disable-next-line @typescript-eslint/no-shadow
  527. pagination: mergedStatePagination = null,
  528. queries: stateQueries = null,
  529. dataSource: stateDataSource = null,
  530. } = states;
  531. const handledProps: Partial<NormalTableState<RecordType>> = this.foundation.getCurrentPageData(stateDataSource, mergedStatePagination as TablePaginationProps, stateQueries);
  532. // After the pager is updated, reset allRowKeys of the current page
  533. this.adapter.setAllRowKeys(handledProps.allRowKeys);
  534. this.adapter.setDisabledRowKeys(handledProps.disabledRowKeys);
  535. if ('dataSource' in states) {
  536. if (this.props.defaultExpandAllRows && handledProps.groups && handledProps.groups.size ||
  537. this.props.expandAllRows ||
  538. this.props.expandAllGroupRows
  539. ) {
  540. this.foundation.initExpandedRowKeys(handledProps);
  541. }
  542. }
  543. // Centrally update paging related state
  544. const statesKeys: any[] = Object.keys(states);
  545. for (const k of statesKeys) {
  546. this.setState({ [k]: handledProps[k] });
  547. }
  548. }
  549. if (this.adapter.isAnyColumnFixed() || (this.props.showHeader && this.adapter.useFixedHeader())) {
  550. if (!this.debouncedWindowResize) {
  551. window.addEventListener('resize', this.debouncedWindowResize);
  552. }
  553. }
  554. }
  555. componentWillUnmount() {
  556. super.componentWillUnmount();
  557. if (this.debouncedWindowResize) {
  558. window.removeEventListener('resize', this.debouncedWindowResize);
  559. (this.debouncedWindowResize as any).cancel();
  560. this.debouncedWindowResize = null;
  561. }
  562. }
  563. // TODO: notify when data don't have key
  564. _warnIfNoKey = () => {
  565. if (
  566. (this.props.rowSelection || this.props.expandedRowRender) &&
  567. some(this.props.dataSource, record => this.foundation.getRecordKey(record) == null)
  568. ) {
  569. logger.error(
  570. 'You must specify a key for each element in the dataSource or use "rowKey" to specify an attribute name as the primary key!'
  571. );
  572. }
  573. };
  574. _invokeRowSelection = (funcName: string, ...args: any[]) => {
  575. const func = get(this.state, ['rowSelection', funcName]);
  576. if (typeof func === 'function') {
  577. func(...args);
  578. }
  579. };
  580. _invokeColumnFn = (key: string, funcName: string, ...args: any[]) => {
  581. if (key && funcName) {
  582. const column = this.foundation.getQuery(key);
  583. const func = get(column, funcName, null);
  584. if (typeof func === 'function') {
  585. func(...args);
  586. }
  587. }
  588. };
  589. _cacheHeaderRef = (node: HTMLDivElement) => {
  590. this.headerWrapRef.current = node;
  591. };
  592. getCurrentPageData = () => {
  593. const pageData = this.foundation.getCurrentPageData();
  594. const retObj = ['dataSource', 'groups'].reduce((result, key) => {
  595. if (pageData[key]) {
  596. result[key] = pageData[key];
  597. }
  598. return result;
  599. }, {});
  600. return cloneDeep(retObj);
  601. };
  602. getColumns = (columns: ColumnProps<RecordType>[], children: ReactNode) => (!Array.isArray(columns) || !columns || !columns.length ? getColumns(children) : columns);
  603. // @ts-ignore
  604. getCellWidths = (...args: any[]) => this.foundation.getCellWidths(...args);
  605. // @ts-ignore
  606. setHeadWidths = (...args: any[]) => this.foundation.setHeadWidths(...args);
  607. // @ts-ignore
  608. getHeadWidths = (...args: any[]) => this.foundation.getHeadWidths(...args);
  609. // @ts-ignore
  610. mergedRowExpandable = (...args: any[]) => this.foundation.mergedRowExpandable(...args);
  611. // @ts-ignore
  612. setBodyHasScrollbar = (...args: any[]) => this.foundation.setBodyHasScrollbar(...args);
  613. handleWheel = (event: React.WheelEvent<HTMLDivElement>) => {
  614. const { scroll = {} } = this.props;
  615. if (window.navigator.userAgent.match(/Trident\/7\./) && scroll.y) {
  616. event.preventDefault();
  617. const wd = event.deltaY;
  618. const { target } = event;
  619. // const { bodyTable, fixedColumnsBodyLeft, fixedColumnsBodyRight } = this;
  620. const bodyTable = this.bodyWrapRef.current;
  621. let scrollTop = 0;
  622. if (this.lastScrollTop) {
  623. scrollTop = this.lastScrollTop + wd;
  624. } else {
  625. scrollTop = wd;
  626. }
  627. if (bodyTable && target !== bodyTable) {
  628. bodyTable.scrollTop = scrollTop;
  629. }
  630. }
  631. };
  632. handleBodyScrollLeft = (e: BodyScrollEvent) => {
  633. if (e.currentTarget !== e.target) {
  634. return;
  635. }
  636. const { target } = e;
  637. // const { headTable, bodyTable } = this;
  638. const headTable = this.headerWrapRef.current;
  639. const bodyTable = this.bodyWrapRef.current;
  640. if (target.scrollLeft !== this.lastScrollLeft) {
  641. if (target === bodyTable && headTable) {
  642. headTable.scrollLeft = target.scrollLeft;
  643. } else if (target === headTable && bodyTable) {
  644. bodyTable.scrollLeft = target.scrollLeft;
  645. }
  646. this.setScrollPositionClassName();
  647. }
  648. // Remember last scrollLeft for scroll direction detecting.
  649. this.lastScrollLeft = target.scrollLeft;
  650. };
  651. handleWindowResize = () => {
  652. this.syncTableWidth();
  653. this.setScrollPositionClassName();
  654. };
  655. handleBodyScrollTop = (e: BodyScrollEvent) => {
  656. const { target } = e;
  657. if (e.currentTarget !== target) {
  658. return;
  659. }
  660. const { scroll = {} } = this.props;
  661. // const { headTable, bodyTable, fixedColumnsBodyLeft, fixedColumnsBodyRight } = this;
  662. const headTable = this.headerWrapRef.current;
  663. const bodyTable = this.bodyWrapRef.current;
  664. if (target.scrollTop !== this.lastScrollTop && scroll.y && target !== headTable) {
  665. const { scrollTop } = target;
  666. if (bodyTable && target !== bodyTable) {
  667. bodyTable.scrollTop = scrollTop;
  668. }
  669. }
  670. // Remember last scrollTop for scroll direction detecting.
  671. this.lastScrollTop = target.scrollTop;
  672. };
  673. handleBodyScroll = (e: BodyScrollEvent) => {
  674. this.handleBodyScrollLeft(e);
  675. this.handleBodyScrollTop(e);
  676. };
  677. setScrollPosition = (position: BodyScrollPosition) => {
  678. const { prefixCls } = this.props;
  679. const positionAll = [
  680. `${prefixCls}-scroll-position-both`,
  681. `${prefixCls}-scroll-position-middle`,
  682. `${prefixCls}-scroll-position-left`,
  683. `${prefixCls}-scroll-position-right`,
  684. ];
  685. this.scrollPosition = position;
  686. const tableNode = this.wrapRef.current;
  687. if (tableNode && tableNode.nodeType) {
  688. if (position === 'both') {
  689. const acceptPosition = [`${prefixCls}-scroll-position-left`, `${prefixCls}-scroll-position-right`];
  690. tableNode.classList.remove(...difference(positionAll, acceptPosition));
  691. tableNode.classList.add(...acceptPosition);
  692. } else {
  693. const acceptPosition = [`${prefixCls}-scroll-position-${position}`];
  694. tableNode.classList.remove(...difference(positionAll, acceptPosition));
  695. tableNode.classList.add(...acceptPosition);
  696. }
  697. }
  698. };
  699. setScrollPositionClassName = () => {
  700. const node = this.bodyWrapRef.current;
  701. if (node && node.children && node.children.length) {
  702. const scrollToLeft = node.scrollLeft === 0;
  703. const scrollToRight =
  704. node.scrollLeft + 1 >=
  705. node.children[0].getBoundingClientRect().width - node.getBoundingClientRect().width;
  706. if (scrollToLeft && scrollToRight) {
  707. this.setScrollPosition('both');
  708. } else if (scrollToLeft) {
  709. this.setScrollPosition('left');
  710. } else if (scrollToRight) {
  711. this.setScrollPosition('right');
  712. } else if (this.scrollPosition !== 'middle') {
  713. this.setScrollPosition('middle');
  714. }
  715. }
  716. };
  717. syncTableWidth = () => {
  718. if (this.rootWrapRef && this.rootWrapRef.current) {
  719. this.setState({ tableWidth: this.rootWrapRef.current.getBoundingClientRect().width });
  720. }
  721. };
  722. renderSelection = (record: RecordType = {} as RecordType, inHeader = false): React.ReactNode => {
  723. const { rowSelection, disabledRowKeysSet } = this.state;
  724. if (rowSelection && typeof rowSelection === 'object') {
  725. const { selectedRowKeys = [], selectedRowKeysSet = new Set(), getCheckboxProps, disabled } = rowSelection;
  726. if (inHeader) {
  727. const columnKey = get(rowSelection, 'key', strings.DEFAULT_KEY_COLUMN_SELECTION);
  728. const allRowKeys = this.cachedFilteredSortedRowKeys;
  729. const allRowKeysSet = this.cachedFilteredSortedRowKeysSet;
  730. const allIsSelected = this.foundation.allIsSelected(selectedRowKeysSet, disabledRowKeysSet, allRowKeys);
  731. const hasRowSelected = this.foundation.hasRowSelected(selectedRowKeys, allRowKeysSet);
  732. return (
  733. <ColumnSelection
  734. aria-label={`${allIsSelected ? 'Deselect' : 'Select'} all rows`}
  735. disabled={disabled}
  736. key={columnKey}
  737. selected={allIsSelected}
  738. indeterminate={hasRowSelected && !allIsSelected}
  739. onChange={(status, e) => {
  740. this.toggleSelectAllRow(status, e);
  741. }}
  742. />
  743. );
  744. } else {
  745. const key = this.foundation.getRecordKey(record);
  746. const selected = selectedRowKeysSet.has(key);
  747. const checkboxPropsFn = () => (typeof getCheckboxProps === 'function' ? getCheckboxProps(record) : {});
  748. return (
  749. <ColumnSelection
  750. aria-label={`${selected ? 'Deselect' : 'Select'} this row`}
  751. getCheckboxProps={checkboxPropsFn}
  752. selected={selected}
  753. onChange={(status, e) => this.toggleSelectRow(status, key, e)}
  754. />
  755. );
  756. }
  757. }
  758. return null;
  759. };
  760. renderRowSelectionCallback = (text: string, record: RecordType = {} as RecordType) => this.renderSelection(record);
  761. renderTitleSelectionCallback = () => this.renderSelection(null, true);
  762. normalizeSelectionColumn = (props: { rowSelection?: TableStateRowSelection<RecordType>; prefixCls?: string } = {}) => {
  763. const { rowSelection, prefixCls } = props;
  764. let column: ColumnProps = {};
  765. if (rowSelection) {
  766. const needOmitSelectionKey = ['selectedRowKeys', 'selectedRowKeysSet'];
  767. column = { key: strings.DEFAULT_KEY_COLUMN_SELECTION };
  768. if (isObject(rowSelection)) {
  769. column = { ...column, ...omit(rowSelection, needOmitSelectionKey) };
  770. }
  771. column.className = classnames(column.className, `${prefixCls}-column-selection`);
  772. column.title = this.renderTitleSelectionCallback;
  773. column.render = this.renderRowSelectionCallback;
  774. }
  775. return column;
  776. };
  777. // If there is a scroll bar, manually construct a column and insert it into the header
  778. normalizeScrollbarColumn = (props: { scrollbarWidth?: number } = {}): { key: 'column-scrollbar'; width: number; fixed: 'right' } => {
  779. const { scrollbarWidth = 0 } = props;
  780. return {
  781. key: strings.DEFAULT_KEY_COLUMN_SCROLLBAR as 'column-scrollbar',
  782. width: scrollbarWidth,
  783. fixed: 'right',
  784. };
  785. };
  786. /**
  787. * render expand icon
  788. * @param {Object} record
  789. * @param {Boolean} isNested
  790. * @param {String} groupKey
  791. * @returns {ReactNode}
  792. */
  793. renderExpandIcon = (record = {}, isNested = false, groupKey: string | number = null) => {
  794. const { expandedRowKeys } = this.state;
  795. const { expandIcon } = this.props;
  796. const key =
  797. typeof groupKey === 'string' || typeof groupKey === 'number' ?
  798. groupKey :
  799. this.foundation.getRecordKey(record as RecordType);
  800. return (
  801. <ExpandedIcon
  802. key={key}
  803. componentType={isNested ? 'tree' : 'expand'}
  804. expanded={includes(expandedRowKeys, key)}
  805. expandIcon={expandIcon}
  806. onClick={(expanded, e) => this.handleRowExpanded(expanded, key, e)}
  807. />
  808. );
  809. };
  810. // @ts-ignore
  811. handleRowExpanded = (...args: any[]) => this.foundation.handleRowExpanded(...args);
  812. normalizeExpandColumn = (props: { prefixCls?: string; expandCellFixed?: ArrayElement<typeof strings.FIXED_SET>; expandIcon?: ExpandIcon } = {}) => {
  813. let column: ColumnProps = null;
  814. const { prefixCls, expandCellFixed, expandIcon } = props;
  815. column = { fixed: expandCellFixed, key: strings.DEFAULT_KEY_COLUMN_EXPAND };
  816. column.className = classnames(column.className, `${prefixCls}-column-expand`);
  817. column.render =
  818. expandIcon !== false ?
  819. (text = '', record, index) =>
  820. (this.adapter.mergedRowExpandable(record) ? this.renderExpandIcon(record) : null) :
  821. () => null;
  822. return column;
  823. };
  824. /**
  825. * Add sorting, filtering, and rendering functions to columns, and add column event handling
  826. * Title support function, passing parameters as {filter: node, sorter: node, selection: node}
  827. * @param {*} column
  828. */
  829. addFnsInColumn = (column: ColumnProps = {}) => {
  830. if (column && (column.sorter || column.filters || column.useFullRender)) {
  831. const { dataIndex, title: rawTitle, useFullRender } = column;
  832. const curQuery = this.foundation.getQuery(dataIndex);
  833. const titleMap: ColumnTitleProps = {};
  834. const titleArr = [];
  835. // useFullRender adds select buttons to each column
  836. if (useFullRender) {
  837. titleMap.selection = this.renderSelection(null, true);
  838. }
  839. const stateSortOrder = get(curQuery, 'sortOrder');
  840. const defaultSortOrder = get(curQuery, 'defaultSortOrder', false);
  841. const sortOrder = this.foundation.isSortOrderValid(stateSortOrder) ? stateSortOrder : defaultSortOrder;
  842. if (typeof column.sorter === 'function' || column.sorter === true) {
  843. const sorter = (
  844. <ColumnSorter
  845. key={strings.DEFAULT_KEY_COLUMN_SORTER}
  846. sortOrder={sortOrder}
  847. onClick={e => this.foundation.handleSort(column, e)}
  848. />
  849. );
  850. useFullRender && (titleMap.sorter = sorter);
  851. titleArr.push(sorter);
  852. }
  853. const stateFilteredValue = get(curQuery, 'filteredValue');
  854. const defaultFilteredValue = get(curQuery, 'defaultFilteredValue');
  855. const filteredValue = stateFilteredValue ? stateFilteredValue : defaultFilteredValue;
  856. if ((Array.isArray(column.filters) && column.filters.length) || isValidElement(column.filterDropdown)) {
  857. const filter = (
  858. <ColumnFilter
  859. key={strings.DEFAULT_KEY_COLUMN_FILTER}
  860. {...curQuery}
  861. filteredValue={filteredValue}
  862. onFilterDropdownVisibleChange={(visible: boolean) => this.foundation.toggleShowFilter(dataIndex, visible)}
  863. onSelect={(data: OnSelectData) => this.foundation.handleFilterSelect(dataIndex, data)}
  864. />
  865. );
  866. useFullRender && (titleMap.filter = filter);
  867. titleArr.push(filter);
  868. }
  869. const newTitle =
  870. typeof rawTitle === 'function' ?
  871. () => rawTitle(titleMap) :
  872. titleArr.unshift(
  873. <React.Fragment key={strings.DEFAULT_KEY_COLUMN_TITLE}>{rawTitle}</React.Fragment>
  874. ) && titleArr;
  875. column = { ...column, title: newTitle };
  876. }
  877. return column;
  878. };
  879. toggleSelectRow = (selected: boolean, realKey: string | number, e: TableSelectionCellEvent) => {
  880. this.foundation.handleSelectRow(realKey, selected, e);
  881. };
  882. toggleSelectAllRow = (status: boolean, e: TableSelectionCellEvent) => {
  883. this.foundation.handleSelectAllRow(status, e);
  884. };
  885. /**
  886. * render pagination
  887. * @param {object} pagination
  888. * @param {object} propRenderPagination
  889. */
  890. renderPagination = (pagination: TablePaginationProps, propRenderPagination: RenderPagination) => {
  891. if (!pagination) {
  892. return null;
  893. }
  894. // use memoized pagination
  895. const mergedPagination = this.foundation.memoizedPagination(pagination);
  896. return (
  897. <LocaleConsumer componentName="Table">
  898. {(locale: TableLocale) => {
  899. const info = this.foundation.formatPaginationInfo(mergedPagination, locale.pageText);
  900. return <TablePagination info={info} pagination={mergedPagination} renderPagination={propRenderPagination} />;
  901. }}
  902. </LocaleConsumer>
  903. );
  904. };
  905. renderTitle = (props: { title?: ReactNode; prefixCls?: string; dataSource?: any[] } = {}) => {
  906. let { title } = props;
  907. const { prefixCls, dataSource } = props;
  908. if (typeof title === 'function') {
  909. title = title(dataSource);
  910. }
  911. return isValidElement(title) || typeof title === 'string' ? (
  912. <div className={`${prefixCls}-title`}>{title}</div>
  913. ) : null;
  914. };
  915. renderEmpty = (props: { prefixCls?: string; empty?: ReactNode; dataSource?: RecordType[] } = {}) => {
  916. const { prefixCls, empty, dataSource } = props;
  917. const wrapCls = `${prefixCls}-placeholder`;
  918. const isEmpty = this.foundation.isEmpty(dataSource);
  919. if (!isEmpty) {
  920. return null;
  921. }
  922. return (
  923. <LocaleConsumer componentName="Table" key={'emptyText'}>
  924. {(locale: TableLocale, localeCode: string) => (
  925. <div className={wrapCls}>
  926. <div className={`${prefixCls}-empty`}>{empty || locale.emptyText}</div>
  927. </div>
  928. )}
  929. </LocaleConsumer>
  930. );
  931. };
  932. renderFooter = (props: { footer?: ReactNode; prefixCls?: string; dataSource?: RecordType[] } = {}) => {
  933. let { footer } = props;
  934. const { prefixCls, dataSource } = props;
  935. if (typeof footer === 'function') {
  936. footer = footer(dataSource);
  937. }
  938. return isValidElement(footer) || typeof footer === 'string' ? (
  939. <div className={`${prefixCls}-footer`} key="footer">
  940. {footer}
  941. </div>
  942. ) : null;
  943. };
  944. renderMainTable = (props: any) => {
  945. const useFixedHeader = this.adapter.useFixedHeader();
  946. const emptySlot = this.renderEmpty(props);
  947. const table = [
  948. this.renderTable({
  949. ...props,
  950. fixed: false,
  951. useFixedHeader,
  952. headerRef: this._cacheHeaderRef,
  953. bodyRef: this.bodyWrapRef,
  954. includeHeader: !useFixedHeader,
  955. }),
  956. emptySlot,
  957. this.renderFooter(props),
  958. ];
  959. return table;
  960. };
  961. renderTable = (props: RenderTableProps<RecordType>) => {
  962. const {
  963. columns,
  964. filteredColumns,
  965. fixed,
  966. useFixedHeader,
  967. scroll,
  968. prefixCls,
  969. anyColumnFixed,
  970. includeHeader,
  971. showHeader,
  972. components,
  973. headerRef,
  974. bodyRef,
  975. rowSelection,
  976. dataSource,
  977. bodyHasScrollBar,
  978. disabledRowKeysSet,
  979. } = props;
  980. const selectedRowKeysSet = get(rowSelection, 'selectedRowKeysSet', new Set());
  981. const headTable =
  982. fixed || useFixedHeader ? (
  983. <HeadTable
  984. key="head"
  985. anyColumnFixed={anyColumnFixed}
  986. ref={headerRef}
  987. columns={filteredColumns}
  988. prefixCls={prefixCls}
  989. fixed={fixed}
  990. handleBodyScroll={this.handleBodyScrollLeft}
  991. components={components}
  992. scroll={scroll}
  993. showHeader={showHeader}
  994. selectedRowKeysSet={selectedRowKeysSet}
  995. dataSource={dataSource}
  996. bodyHasScrollBar={bodyHasScrollBar}
  997. />
  998. ) : null;
  999. const bodyTable = (
  1000. <BodyTable
  1001. {...omit(props, ['rowSelection', 'headWidths']) as any}
  1002. key="body"
  1003. ref={bodyRef}
  1004. columns={filteredColumns}
  1005. fixed={fixed}
  1006. prefixCls={prefixCls}
  1007. handleWheel={this.handleWheel}
  1008. handleBodyScroll={this.handleBodyScroll}
  1009. anyColumnFixed={anyColumnFixed}
  1010. includeHeader={includeHeader}
  1011. showHeader={showHeader}
  1012. scroll={scroll}
  1013. components={components}
  1014. store={this.store}
  1015. selectedRowKeysSet={selectedRowKeysSet}
  1016. disabledRowKeysSet={disabledRowKeysSet}
  1017. />
  1018. );
  1019. return [headTable, bodyTable];
  1020. };
  1021. /**
  1022. * When columns change, call this function to get the latest withFnsColumns
  1023. * In addition to changes in columns, these props changes must be recalculated
  1024. * - hideExpandedColumn
  1025. * -rowSelection changes from trusy to falsy or rowSelection.hidden changes
  1026. * -isAnyFixedRight(columns) || get(scroll,'y') changes
  1027. *
  1028. * columns变化时,调用此函数获取最新的withFnsColumns
  1029. * 除了 columns 变化,这些 props 变化也要重新计算
  1030. * - hideExpandedColumn
  1031. * - rowSelection 从 trusy 变为 falsy 或 rowSelection.hidden 发生变化
  1032. * - isAnyFixedRight(columns) || get(scroll, 'y') 发生变化
  1033. *
  1034. * @param {Array} queries
  1035. * @param {Array} cachedColumns
  1036. * @returns columns after adding extended functions
  1037. */
  1038. handleColumns = (queries: ColumnProps<RecordType>[], cachedColumns: ColumnProps<RecordType>[]) => {
  1039. const { hideExpandedColumn, scroll, prefixCls, expandCellFixed, expandIcon, rowSelection } = this.props;
  1040. const childrenColumnName = 'children';
  1041. let columns: ColumnProps<RecordType>[] = cloneDeep(cachedColumns);
  1042. // eslint-disable-next-line @typescript-eslint/no-shadow
  1043. const addFns = (columns: ColumnProps<RecordType>[] = []) => {
  1044. if (Array.isArray(columns) && columns.length) {
  1045. each(columns, (column, index, originColumns) => {
  1046. const newColumn = this.addFnsInColumn(column);
  1047. const children = column[childrenColumnName];
  1048. if (Array.isArray(children) && children.length) {
  1049. const newChildren = [...children];
  1050. addFns(newChildren);
  1051. newColumn[childrenColumnName] = newChildren;
  1052. }
  1053. originColumns[index] = newColumn;
  1054. });
  1055. }
  1056. };
  1057. addFns(columns);
  1058. // hideExpandedColumn=false render expand column separately
  1059. if (!hideExpandedColumn) {
  1060. const column = this.normalizeExpandColumn({ prefixCls, expandCellFixed, expandIcon });
  1061. const destIndex = findIndex(columns, item => item.key === strings.DEFAULT_KEY_COLUMN_EXPAND);
  1062. if (column) {
  1063. if (destIndex > -1) {
  1064. columns[destIndex] = { ...column, ...columns[destIndex] };
  1065. } else if (column.fixed === 'right') {
  1066. columns = [...columns, column];
  1067. } else {
  1068. columns = [column, ...columns];
  1069. }
  1070. }
  1071. }
  1072. // selection column
  1073. if (rowSelection && !get(rowSelection, 'hidden')) {
  1074. const destIndex = findIndex(columns, item => item.key === strings.DEFAULT_KEY_COLUMN_SELECTION);
  1075. const column = this.normalizeSelectionColumn({ rowSelection, prefixCls });
  1076. if (destIndex > -1) {
  1077. columns[destIndex] = { ...column, ...columns[destIndex] };
  1078. } else if (column.fixed === 'right') {
  1079. columns = [...columns, column];
  1080. } else {
  1081. columns = [column, ...columns];
  1082. }
  1083. }
  1084. assignColumnKeys(columns);
  1085. return columns;
  1086. };
  1087. /**
  1088. * Convert children to columns object
  1089. * @param {Array} columns
  1090. * @param {ReactNode} children
  1091. * @returns {Array}
  1092. */
  1093. normalizeColumns = (columns: ColumnProps<RecordType>[], children: ReactNode) => {
  1094. const normalColumns = cloneDeep(this.getColumns(columns, children));
  1095. return normalColumns;
  1096. };
  1097. /**
  1098. * Combine pagination and table paging processing functions
  1099. */
  1100. mergePagination = (pagination: TablePaginationProps) => {
  1101. const newPagination = { onChange: this.foundation.setPage, ...pagination };
  1102. return newPagination;
  1103. };
  1104. render() {
  1105. let {
  1106. scroll,
  1107. prefixCls,
  1108. className,
  1109. style: wrapStyle = {},
  1110. bordered,
  1111. id,
  1112. pagination: propPagination,
  1113. virtualized,
  1114. size,
  1115. renderPagination: propRenderPagination,
  1116. getVirtualizedListRef,
  1117. loading,
  1118. hideExpandedColumn,
  1119. rowSelection: propRowSelection,
  1120. ...rest
  1121. } = this.props;
  1122. let {
  1123. rowSelection,
  1124. expandedRowKeys,
  1125. headWidths,
  1126. tableWidth,
  1127. pagination,
  1128. dataSource,
  1129. queries,
  1130. cachedColumns,
  1131. bodyHasScrollBar,
  1132. } = this.state;
  1133. wrapStyle = { ...wrapStyle };
  1134. let columns: ColumnProps<RecordType>[];
  1135. /**
  1136. * As state.queries will change, the columns should be refreshed as a whole at this time
  1137. * The scene of changes in queries
  1138. * 1. Filter
  1139. * 2. Pagination
  1140. *
  1141. * useFullRender needs to be passed to the user selection ReactNode, so columns need to be recalculated every time the selectedRowKeys changes
  1142. * TODO: In the future, the selection passed to the user can be changed to the function type, allowing the user to execute the function to obtain the real-time status of the selection title
  1143. *
  1144. * 由于state.queries会发生变化,此时columns应该整体刷新
  1145. * queries变化的场景
  1146. * 1. 筛选
  1147. * 2. 分页
  1148. * useFullRender需要传给用户selection ReactNode,因此需要每次selectedRowKeys变化时重新计算columns
  1149. * TODO: 未来可以将传给用户的selection改为函数类型,让用户执行函数获取selection title的实时状态
  1150. */
  1151. if (!this.adapter.isAnyColumnUseFullRender(queries)) {
  1152. const rowSelectionUpdate: boolean = propRowSelection && !get(propRowSelection, 'hidden');
  1153. columns = this.foundation.memoizedWithFnsColumns(
  1154. queries,
  1155. cachedColumns,
  1156. rowSelectionUpdate,
  1157. hideExpandedColumn,
  1158. // Update the columns after the body scrollbar changes to ensure that the head and body are aligned
  1159. bodyHasScrollBar
  1160. );
  1161. } else {
  1162. columns = this.handleColumns(queries, cachedColumns);
  1163. }
  1164. const filteredColumns: ColumnProps<RecordType>[] = this.foundation.memoizedFilterColumns(columns);
  1165. const flattenFnsColumns: ColumnProps<RecordType>[] = this.foundation.memoizedFlattenFnsColumns(columns);
  1166. const anyColumnFixed = this.adapter.isAnyColumnFixed(columns);
  1167. /**
  1168. * - If it is the first page break, you need to calculate the current page
  1169. * - If it is manual paging, call foundation to modify the state
  1170. *
  1171. * TODO: After merging issue 1007, you can place it in the constructor to complete
  1172. * The reason is that #1007 exposes the parameters required by getCurrentPageData in the constructor
  1173. */
  1174. if (isNull(dataSource)) {
  1175. const pageData: BasePageData<RecordType> = this.foundation.getCurrentPageData(this.props.dataSource);
  1176. dataSource = pageData.dataSource;
  1177. pagination = pageData.pagination;
  1178. }
  1179. const props = {
  1180. ...rest,
  1181. ...this.state,
  1182. // props not in rest
  1183. virtualized,
  1184. scroll,
  1185. prefixCls,
  1186. size,
  1187. hideExpandedColumn,
  1188. // renamed state
  1189. columns,
  1190. // calculated value
  1191. anyColumnFixed,
  1192. rowExpandable: this.mergedRowExpandable,
  1193. pagination,
  1194. dataSource,
  1195. rowSelection,
  1196. expandedRowKeys,
  1197. renderExpandIcon: this.renderExpandIcon,
  1198. filteredColumns,
  1199. };
  1200. const x = get(scroll, 'x');
  1201. const y = get(scroll, 'y');
  1202. if (virtualized) {
  1203. if (typeof wrapStyle.width !== 'number') {
  1204. wrapStyle.width = x;
  1205. }
  1206. }
  1207. const wrapCls = classnames({
  1208. [`${prefixCls}-${strings.SIZE_SMALL}`]: size === strings.SIZE_SMALL,
  1209. [`${prefixCls}-${strings.SIZE_MIDDLE}`]: size === strings.SIZE_MIDDLE,
  1210. [`${prefixCls}-virtualized`]: Boolean(virtualized),
  1211. [`${prefixCls}-bordered`]: bordered,
  1212. [`${prefixCls}-fixed-header`]: Boolean(y),
  1213. [`${prefixCls}-scroll-position-left`]: ['both', 'left'].includes(this.position),
  1214. [`${prefixCls}-scroll-position-right`]: ['both', 'right'].includes(this.position),
  1215. });
  1216. // pagination
  1217. const tablePagination = pagination && propPagination ? this.renderPagination(pagination as TablePaginationProps, propRenderPagination) : null;
  1218. const paginationPosition = get(propPagination, 'position', 'bottom');
  1219. const tableContextValue: TableContextProps = {
  1220. ...this.context,
  1221. headWidths,
  1222. tableWidth,
  1223. anyColumnFixed,
  1224. flattenedColumns: flattenFnsColumns,
  1225. renderExpandIcon: this.renderExpandIcon,
  1226. renderSelection: this.renderSelection,
  1227. setHeadWidths: this.setHeadWidths,
  1228. getHeadWidths: this.getHeadWidths,
  1229. getCellWidths: this.getCellWidths,
  1230. handleRowExpanded: this.handleRowExpanded,
  1231. getVirtualizedListRef,
  1232. setBodyHasScrollbar: this.setBodyHasScrollbar,
  1233. };
  1234. return (
  1235. <div
  1236. ref={this.rootWrapRef}
  1237. className={classnames(className, `${prefixCls}-wrapper`)}
  1238. data-column-fixed={anyColumnFixed}
  1239. style={wrapStyle}
  1240. id={id}
  1241. >
  1242. <TableContextProvider {...tableContextValue}>
  1243. <Spin spinning={loading} size="large">
  1244. <div ref={this.wrapRef} className={wrapCls}>
  1245. <React.Fragment key={'pagination-top'}>
  1246. {['top', 'both'].includes(paginationPosition) ? tablePagination : null}
  1247. </React.Fragment>
  1248. {this.renderTitle({ title: (props as any).title, dataSource: props.dataSource, prefixCls: props.prefixCls })}
  1249. <div className={`${prefixCls}-container`}>{this.renderMainTable({ ...props })}</div>
  1250. <React.Fragment key={'pagination-bottom'}>
  1251. {['bottom', 'both'].includes(paginationPosition) ? tablePagination : null}
  1252. </React.Fragment>
  1253. </div>
  1254. </Spin>
  1255. </TableContextProvider>
  1256. </div>
  1257. );
  1258. }
  1259. }
  1260. export default Table;