Table.tsx 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  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 newNestedColumns = getColumns(props.children);
  404. const newFlattenColumns = flattenColumns(newNestedColumns);
  405. const columns = mergeColumns(state.queries, newFlattenColumns, null, false);
  406. willUpdateStates.flattenColumns = newFlattenColumns;
  407. willUpdateStates.queries = [...columns];
  408. willUpdateStates.cachedColumns = [...newNestedColumns];
  409. willUpdateStates.cachedChildren = props.children;
  410. }
  411. // Update controlled selection column
  412. if (rowSelection !== state.prePropRowSelection) {
  413. let newSelectionStates: TableStateRowSelection = {};
  414. if (isObject(state.rowSelection)) {
  415. newSelectionStates = { ...newSelectionStates, ...state.rowSelection };
  416. }
  417. if (isObject(rowSelection)) {
  418. newSelectionStates = { ...newSelectionStates, ...rowSelection };
  419. }
  420. const selectedRowKeys = get(rowSelection, 'selectedRowKeys');
  421. const getCheckboxProps = get(rowSelection, 'getCheckboxProps');
  422. if (selectedRowKeys && Array.isArray(selectedRowKeys)) {
  423. newSelectionStates.selectedRowKeysSet = new Set(selectedRowKeys);
  424. }
  425. // The return value of getCheckboxProps affects the disabled rows
  426. if (isFunction(getCheckboxProps)) {
  427. const disabledRowKeys = getAllDisabledRowKeys({ dataSource, getCheckboxProps, childrenRecordName, rowKey });
  428. willUpdateStates.disabledRowKeys = disabledRowKeys;
  429. willUpdateStates.disabledRowKeysSet = new Set(disabledRowKeys);
  430. }
  431. willUpdateStates.rowSelection = newSelectionStates;
  432. willUpdateStates.prePropRowSelection = rowSelection;
  433. }
  434. if (pagination !== state.prePagination) {
  435. let newPagination: Pagination = {};
  436. if (isObject(state.pagination)) {
  437. newPagination = { ...newPagination, ...state.pagination };
  438. }
  439. if (isObject(pagination)) {
  440. newPagination = { ...newPagination, ...pagination };
  441. }
  442. willUpdateStates.pagination = newPagination;
  443. willUpdateStates.prePagination = pagination;
  444. }
  445. return willUpdateStates;
  446. }
  447. componentDidMount() {
  448. super.componentDidMount();
  449. if (this.adapter.isAnyColumnFixed() || (this.props.showHeader && this.adapter.useFixedHeader())) {
  450. this.handleWindowResize();
  451. window.addEventListener('resize', this.debouncedWindowResize);
  452. }
  453. }
  454. // TODO: Extract the setState operation to the adapter or getDerivedStateFromProps function
  455. componentDidUpdate(prevProps: NormalTableProps<RecordType>, prevState: NormalTableState<RecordType>) {
  456. const {
  457. dataSource,
  458. expandedRowKeys,
  459. expandAllRows,
  460. expandAllGroupRows,
  461. virtualized,
  462. components,
  463. pagination: propsPagination
  464. } = this.props;
  465. const {
  466. pagination: statePagination,
  467. queries: stateQueries,
  468. cachedColumns: stateCachedColumns,
  469. cachedChildren: stateCachedChildren,
  470. groups: stateGroups,
  471. } = this.state;
  472. /**
  473. * State related to paging
  474. *
  475. * @param dataSource
  476. * @param groups
  477. * @param pagination
  478. * @param disabledRowKeys
  479. * @param allRowKeys
  480. * @param queries
  481. */
  482. const states: Partial<NormalTableState<RecordType>> = {};
  483. this._warnIfNoKey();
  484. /**
  485. * The state that needs to be updated after props changes
  486. */
  487. // Update controlled expand column
  488. if (Array.isArray(expandedRowKeys) && expandedRowKeys !== prevProps.expandedRowKeys) {
  489. this.setState({ expandedRowKeys });
  490. }
  491. // Update components
  492. if (components !== prevProps.components || virtualized !== prevProps.virtualized) {
  493. this.setState({ components: mergeComponents(components, virtualized) });
  494. }
  495. // Update the default expanded column
  496. if (
  497. expandAllRows !== prevProps.expandAllRows ||
  498. expandAllGroupRows !== prevProps.expandAllGroupRows
  499. ) {
  500. this.foundation.initExpandedRowKeys({ groups: stateGroups });
  501. }
  502. /**
  503. * After dataSource is updated || (cachedColumns || cachedChildren updated)
  504. * 1. Cache filtered sorted data and a collection of data rows, stored in this
  505. * 2. Update pager and group, stored in state
  506. */
  507. if (dataSource !== prevProps.dataSource || stateCachedColumns !== prevState.cachedColumns || stateCachedChildren !== prevState.cachedChildren) {
  508. // TODO: foundation.getFilteredSortedDataSource has side effects and will be modified to the dataSource reference
  509. // Temporarily use _dataSource=[...dataSource] for processing
  510. const _dataSource = [...dataSource];
  511. const filteredSortedDataSource = this.foundation.getFilteredSortedDataSource(_dataSource, stateQueries);
  512. this.foundation.setCachedFilteredSortedDataSource(filteredSortedDataSource);
  513. states.dataSource = filteredSortedDataSource;
  514. if (this.props.groupBy) {
  515. states.groups = null;
  516. }
  517. }
  518. // when dataSource has change, should reset currentPage
  519. if (dataSource !== prevProps.dataSource) {
  520. states.pagination = isObject(statePagination) ? {
  521. ...statePagination,
  522. currentPage: isObject(propsPagination) && propsPagination.currentPage ? propsPagination.currentPage : 1,
  523. } : statePagination;
  524. }
  525. if (Object.keys(states).length) {
  526. const {
  527. // eslint-disable-next-line @typescript-eslint/no-shadow
  528. pagination: mergedStatePagination = null,
  529. queries: stateQueries = null,
  530. dataSource: stateDataSource = null,
  531. } = states;
  532. const handledProps: Partial<NormalTableState<RecordType>> = this.foundation.getCurrentPageData(stateDataSource, mergedStatePagination as TablePaginationProps, stateQueries);
  533. // After the pager is updated, reset allRowKeys of the current page
  534. this.adapter.setAllRowKeys(handledProps.allRowKeys);
  535. this.adapter.setDisabledRowKeys(handledProps.disabledRowKeys);
  536. if ('dataSource' in states) {
  537. if (this.props.defaultExpandAllRows && handledProps.groups && handledProps.groups.size ||
  538. this.props.expandAllRows ||
  539. this.props.expandAllGroupRows
  540. ) {
  541. this.foundation.initExpandedRowKeys(handledProps);
  542. }
  543. }
  544. // Centrally update paging related state
  545. const statesKeys: any[] = Object.keys(states);
  546. for (const k of statesKeys) {
  547. this.setState({ [k]: handledProps[k] });
  548. }
  549. }
  550. if (this.adapter.isAnyColumnFixed() || (this.props.showHeader && this.adapter.useFixedHeader())) {
  551. if (!this.debouncedWindowResize) {
  552. window.addEventListener('resize', this.debouncedWindowResize);
  553. }
  554. }
  555. }
  556. componentWillUnmount() {
  557. super.componentWillUnmount();
  558. if (this.debouncedWindowResize) {
  559. window.removeEventListener('resize', this.debouncedWindowResize);
  560. (this.debouncedWindowResize as any).cancel();
  561. this.debouncedWindowResize = null;
  562. }
  563. }
  564. // TODO: notify when data don't have key
  565. _warnIfNoKey = () => {
  566. if (
  567. (this.props.rowSelection || this.props.expandedRowRender) &&
  568. some(this.props.dataSource, record => this.foundation.getRecordKey(record) == null)
  569. ) {
  570. logger.error(
  571. 'You must specify a key for each element in the dataSource or use "rowKey" to specify an attribute name as the primary key!'
  572. );
  573. }
  574. };
  575. _invokeRowSelection = (funcName: string, ...args: any[]) => {
  576. const func = get(this.state, ['rowSelection', funcName]);
  577. if (typeof func === 'function') {
  578. func(...args);
  579. }
  580. };
  581. _invokeColumnFn = (key: string, funcName: string, ...args: any[]) => {
  582. if (key && funcName) {
  583. const column = this.foundation.getQuery(key);
  584. const func = get(column, funcName, null);
  585. if (typeof func === 'function') {
  586. func(...args);
  587. }
  588. }
  589. };
  590. _cacheHeaderRef = (node: HTMLDivElement) => {
  591. this.headerWrapRef.current = node;
  592. };
  593. getCurrentPageData = () => {
  594. const pageData = this.foundation.getCurrentPageData();
  595. const retObj = ['dataSource', 'groups'].reduce((result, key) => {
  596. if (pageData[key]) {
  597. result[key] = pageData[key];
  598. }
  599. return result;
  600. }, {});
  601. return cloneDeep(retObj);
  602. };
  603. getColumns = (columns: ColumnProps<RecordType>[], children: ReactNode) => (!Array.isArray(columns) || !columns || !columns.length ? getColumns(children) : columns);
  604. // @ts-ignore
  605. getCellWidths = (...args: any[]) => this.foundation.getCellWidths(...args);
  606. // @ts-ignore
  607. setHeadWidths = (...args: any[]) => this.foundation.setHeadWidths(...args);
  608. // @ts-ignore
  609. getHeadWidths = (...args: any[]) => this.foundation.getHeadWidths(...args);
  610. // @ts-ignore
  611. mergedRowExpandable = (...args: any[]) => this.foundation.mergedRowExpandable(...args);
  612. // @ts-ignore
  613. setBodyHasScrollbar = (...args: any[]) => this.foundation.setBodyHasScrollbar(...args);
  614. handleWheel = (event: React.WheelEvent<HTMLDivElement>) => {
  615. const { scroll = {} } = this.props;
  616. if (window.navigator.userAgent.match(/Trident\/7\./) && scroll.y) {
  617. event.preventDefault();
  618. const wd = event.deltaY;
  619. const { target } = event;
  620. // const { bodyTable, fixedColumnsBodyLeft, fixedColumnsBodyRight } = this;
  621. const bodyTable = this.bodyWrapRef.current;
  622. let scrollTop = 0;
  623. if (this.lastScrollTop) {
  624. scrollTop = this.lastScrollTop + wd;
  625. } else {
  626. scrollTop = wd;
  627. }
  628. if (bodyTable && target !== bodyTable) {
  629. bodyTable.scrollTop = scrollTop;
  630. }
  631. }
  632. };
  633. handleBodyScrollLeft = (e: BodyScrollEvent) => {
  634. if (e.currentTarget !== e.target) {
  635. return;
  636. }
  637. const { target } = e;
  638. // const { headTable, bodyTable } = this;
  639. const headTable = this.headerWrapRef.current;
  640. const bodyTable = this.bodyWrapRef.current;
  641. if (target.scrollLeft !== this.lastScrollLeft) {
  642. if (target === bodyTable && headTable) {
  643. headTable.scrollLeft = target.scrollLeft;
  644. } else if (target === headTable && bodyTable) {
  645. bodyTable.scrollLeft = target.scrollLeft;
  646. }
  647. this.setScrollPositionClassName();
  648. }
  649. // Remember last scrollLeft for scroll direction detecting.
  650. this.lastScrollLeft = target.scrollLeft;
  651. };
  652. handleWindowResize = () => {
  653. this.syncTableWidth();
  654. this.setScrollPositionClassName();
  655. };
  656. handleBodyScrollTop = (e: BodyScrollEvent) => {
  657. const { target } = e;
  658. if (e.currentTarget !== target) {
  659. return;
  660. }
  661. const { scroll = {} } = this.props;
  662. // const { headTable, bodyTable, fixedColumnsBodyLeft, fixedColumnsBodyRight } = this;
  663. const headTable = this.headerWrapRef.current;
  664. const bodyTable = this.bodyWrapRef.current;
  665. if (target.scrollTop !== this.lastScrollTop && scroll.y && target !== headTable) {
  666. const { scrollTop } = target;
  667. if (bodyTable && target !== bodyTable) {
  668. bodyTable.scrollTop = scrollTop;
  669. }
  670. }
  671. // Remember last scrollTop for scroll direction detecting.
  672. this.lastScrollTop = target.scrollTop;
  673. };
  674. handleBodyScroll = (e: BodyScrollEvent) => {
  675. this.handleBodyScrollLeft(e);
  676. this.handleBodyScrollTop(e);
  677. };
  678. setScrollPosition = (position: BodyScrollPosition) => {
  679. const { prefixCls } = this.props;
  680. const positionAll = [
  681. `${prefixCls}-scroll-position-both`,
  682. `${prefixCls}-scroll-position-middle`,
  683. `${prefixCls}-scroll-position-left`,
  684. `${prefixCls}-scroll-position-right`,
  685. ];
  686. this.scrollPosition = position;
  687. const tableNode = this.wrapRef.current;
  688. if (tableNode && tableNode.nodeType) {
  689. if (position === 'both') {
  690. const acceptPosition = [`${prefixCls}-scroll-position-left`, `${prefixCls}-scroll-position-right`];
  691. tableNode.classList.remove(...difference(positionAll, acceptPosition));
  692. tableNode.classList.add(...acceptPosition);
  693. } else {
  694. const acceptPosition = [`${prefixCls}-scroll-position-${position}`];
  695. tableNode.classList.remove(...difference(positionAll, acceptPosition));
  696. tableNode.classList.add(...acceptPosition);
  697. }
  698. }
  699. };
  700. setScrollPositionClassName = () => {
  701. const node = this.bodyWrapRef.current;
  702. if (node && node.children && node.children.length) {
  703. const scrollToLeft = node.scrollLeft === 0;
  704. const scrollToRight =
  705. node.scrollLeft + 1 >=
  706. node.children[0].getBoundingClientRect().width - node.getBoundingClientRect().width;
  707. if (scrollToLeft && scrollToRight) {
  708. this.setScrollPosition('both');
  709. } else if (scrollToLeft) {
  710. this.setScrollPosition('left');
  711. } else if (scrollToRight) {
  712. this.setScrollPosition('right');
  713. } else if (this.scrollPosition !== 'middle') {
  714. this.setScrollPosition('middle');
  715. }
  716. }
  717. };
  718. syncTableWidth = () => {
  719. if (this.rootWrapRef && this.rootWrapRef.current) {
  720. this.setState({ tableWidth: this.rootWrapRef.current.getBoundingClientRect().width });
  721. }
  722. };
  723. renderSelection = (record: RecordType = {} as RecordType, inHeader = false): React.ReactNode => {
  724. const { rowSelection, disabledRowKeysSet } = this.state;
  725. if (rowSelection && typeof rowSelection === 'object') {
  726. const { selectedRowKeys = [], selectedRowKeysSet = new Set(), getCheckboxProps, disabled } = rowSelection;
  727. if (inHeader) {
  728. const columnKey = get(rowSelection, 'key', strings.DEFAULT_KEY_COLUMN_SELECTION);
  729. const allRowKeys = this.cachedFilteredSortedRowKeys;
  730. const allRowKeysSet = this.cachedFilteredSortedRowKeysSet;
  731. const allIsSelected = this.foundation.allIsSelected(selectedRowKeysSet, disabledRowKeysSet, allRowKeys);
  732. const hasRowSelected = this.foundation.hasRowSelected(selectedRowKeys, allRowKeysSet);
  733. return (
  734. <ColumnSelection
  735. aria-label={`${allIsSelected ? 'Deselect' : 'Select'} all rows`}
  736. disabled={disabled}
  737. key={columnKey}
  738. selected={allIsSelected}
  739. indeterminate={hasRowSelected && !allIsSelected}
  740. onChange={(status, e) => {
  741. this.toggleSelectAllRow(status, e);
  742. }}
  743. />
  744. );
  745. } else {
  746. const key = this.foundation.getRecordKey(record);
  747. const selected = selectedRowKeysSet.has(key);
  748. const checkboxPropsFn = () => (typeof getCheckboxProps === 'function' ? getCheckboxProps(record) : {});
  749. return (
  750. <ColumnSelection
  751. aria-label={`${selected ? 'Deselect' : 'Select'} this row`}
  752. getCheckboxProps={checkboxPropsFn}
  753. selected={selected}
  754. onChange={(status, e) => this.toggleSelectRow(status, key, e)}
  755. />
  756. );
  757. }
  758. }
  759. return null;
  760. };
  761. renderRowSelectionCallback = (text: string, record: RecordType = {} as RecordType) => this.renderSelection(record);
  762. renderTitleSelectionCallback = () => this.renderSelection(null, true);
  763. normalizeSelectionColumn = (props: { rowSelection?: TableStateRowSelection<RecordType>; prefixCls?: string } = {}) => {
  764. const { rowSelection, prefixCls } = props;
  765. let column: ColumnProps = {};
  766. if (rowSelection) {
  767. const needOmitSelectionKey = ['selectedRowKeys', 'selectedRowKeysSet'];
  768. column = { key: strings.DEFAULT_KEY_COLUMN_SELECTION };
  769. if (isObject(rowSelection)) {
  770. column = { ...column, ...omit(rowSelection, needOmitSelectionKey) };
  771. }
  772. column.className = classnames(column.className, `${prefixCls}-column-selection`);
  773. column.title = this.renderTitleSelectionCallback;
  774. column.render = this.renderRowSelectionCallback;
  775. }
  776. return column;
  777. };
  778. // If there is a scroll bar, manually construct a column and insert it into the header
  779. normalizeScrollbarColumn = (props: { scrollbarWidth?: number } = {}): { key: 'column-scrollbar'; width: number; fixed: 'right' } => {
  780. const { scrollbarWidth = 0 } = props;
  781. return {
  782. key: strings.DEFAULT_KEY_COLUMN_SCROLLBAR as 'column-scrollbar',
  783. width: scrollbarWidth,
  784. fixed: 'right',
  785. };
  786. };
  787. /**
  788. * render expand icon
  789. * @param {Object} record
  790. * @param {Boolean} isNested
  791. * @param {String} groupKey
  792. * @returns {ReactNode}
  793. */
  794. renderExpandIcon = (record = {}, isNested = false, groupKey: string | number = null) => {
  795. const { expandedRowKeys } = this.state;
  796. const { expandIcon } = this.props;
  797. const key =
  798. typeof groupKey === 'string' || typeof groupKey === 'number' ?
  799. groupKey :
  800. this.foundation.getRecordKey(record as RecordType);
  801. return (
  802. <ExpandedIcon
  803. key={key}
  804. componentType={isNested ? 'tree' : 'expand'}
  805. expanded={includes(expandedRowKeys, key)}
  806. expandIcon={expandIcon}
  807. onClick={(expanded, e) => this.handleRowExpanded(expanded, key, e)}
  808. />
  809. );
  810. };
  811. // @ts-ignore
  812. handleRowExpanded = (...args: any[]) => this.foundation.handleRowExpanded(...args);
  813. normalizeExpandColumn = (props: { prefixCls?: string; expandCellFixed?: ArrayElement<typeof strings.FIXED_SET>; expandIcon?: ExpandIcon } = {}) => {
  814. let column: ColumnProps = null;
  815. const { prefixCls, expandCellFixed, expandIcon } = props;
  816. column = { fixed: expandCellFixed, key: strings.DEFAULT_KEY_COLUMN_EXPAND };
  817. column.className = classnames(column.className, `${prefixCls}-column-expand`);
  818. column.render =
  819. expandIcon !== false ?
  820. (text = '', record, index) =>
  821. (this.adapter.mergedRowExpandable(record) ? this.renderExpandIcon(record) : null) :
  822. () => null;
  823. return column;
  824. };
  825. /**
  826. * Add sorting, filtering, and rendering functions to columns, and add column event handling
  827. * Title support function, passing parameters as {filter: node, sorter: node, selection: node}
  828. * @param {*} column
  829. */
  830. addFnsInColumn = (column: ColumnProps = {}) => {
  831. if (column && (column.sorter || column.filters || column.useFullRender)) {
  832. const { dataIndex, title: rawTitle, useFullRender } = column;
  833. const curQuery = this.foundation.getQuery(dataIndex);
  834. const titleMap: ColumnTitleProps = {};
  835. const titleArr = [];
  836. // useFullRender adds select buttons to each column
  837. if (useFullRender) {
  838. titleMap.selection = this.renderSelection(null, true);
  839. }
  840. const stateSortOrder = get(curQuery, 'sortOrder');
  841. const defaultSortOrder = get(curQuery, 'defaultSortOrder', false);
  842. const sortOrder = this.foundation.isSortOrderValid(stateSortOrder) ? stateSortOrder : defaultSortOrder;
  843. if (typeof column.sorter === 'function' || column.sorter === true) {
  844. const sorter = (
  845. <ColumnSorter
  846. key={strings.DEFAULT_KEY_COLUMN_SORTER}
  847. sortOrder={sortOrder}
  848. onClick={e => this.foundation.handleSort(column, e)}
  849. />
  850. );
  851. useFullRender && (titleMap.sorter = sorter);
  852. titleArr.push(sorter);
  853. }
  854. const stateFilteredValue = get(curQuery, 'filteredValue');
  855. const defaultFilteredValue = get(curQuery, 'defaultFilteredValue');
  856. const filteredValue = stateFilteredValue ? stateFilteredValue : defaultFilteredValue;
  857. if ((Array.isArray(column.filters) && column.filters.length) || isValidElement(column.filterDropdown)) {
  858. const filter = (
  859. <ColumnFilter
  860. key={strings.DEFAULT_KEY_COLUMN_FILTER}
  861. {...curQuery}
  862. filteredValue={filteredValue}
  863. onFilterDropdownVisibleChange={(visible: boolean) => this.foundation.toggleShowFilter(dataIndex, visible)}
  864. onSelect={(data: OnSelectData) => this.foundation.handleFilterSelect(dataIndex, data)}
  865. />
  866. );
  867. useFullRender && (titleMap.filter = filter);
  868. titleArr.push(filter);
  869. }
  870. const newTitle =
  871. typeof rawTitle === 'function' ?
  872. () => rawTitle(titleMap) :
  873. titleArr.unshift(
  874. <React.Fragment key={strings.DEFAULT_KEY_COLUMN_TITLE}>{rawTitle}</React.Fragment>
  875. ) && titleArr;
  876. column = { ...column, title: newTitle };
  877. }
  878. return column;
  879. };
  880. toggleSelectRow = (selected: boolean, realKey: string | number, e: TableSelectionCellEvent) => {
  881. this.foundation.handleSelectRow(realKey, selected, e);
  882. };
  883. toggleSelectAllRow = (status: boolean, e: TableSelectionCellEvent) => {
  884. this.foundation.handleSelectAllRow(status, e);
  885. };
  886. /**
  887. * render pagination
  888. * @param {object} pagination
  889. * @param {object} propRenderPagination
  890. */
  891. renderPagination = (pagination: TablePaginationProps, propRenderPagination: RenderPagination) => {
  892. if (!pagination) {
  893. return null;
  894. }
  895. // use memoized pagination
  896. const mergedPagination = this.foundation.memoizedPagination(pagination);
  897. return (
  898. <LocaleConsumer componentName="Table">
  899. {(locale: TableLocale) => {
  900. const info = this.foundation.formatPaginationInfo(mergedPagination, locale.pageText);
  901. return <TablePagination info={info} pagination={mergedPagination} renderPagination={propRenderPagination} />;
  902. }}
  903. </LocaleConsumer>
  904. );
  905. };
  906. renderTitle = (props: { title?: ReactNode; prefixCls?: string; dataSource?: any[] } = {}) => {
  907. let { title } = props;
  908. const { prefixCls, dataSource } = props;
  909. if (typeof title === 'function') {
  910. title = title(dataSource);
  911. }
  912. return isValidElement(title) || typeof title === 'string' ? (
  913. <div className={`${prefixCls}-title`}>{title}</div>
  914. ) : null;
  915. };
  916. renderEmpty = (props: { prefixCls?: string; empty?: ReactNode; dataSource?: RecordType[] } = {}) => {
  917. const { prefixCls, empty, dataSource } = props;
  918. const wrapCls = `${prefixCls}-placeholder`;
  919. const isEmpty = this.foundation.isEmpty(dataSource);
  920. if (!isEmpty) {
  921. return null;
  922. }
  923. return (
  924. <LocaleConsumer componentName="Table" key={'emptyText'}>
  925. {(locale: TableLocale, localeCode: string) => (
  926. <div className={wrapCls}>
  927. <div className={`${prefixCls}-empty`}>{empty || locale.emptyText}</div>
  928. </div>
  929. )}
  930. </LocaleConsumer>
  931. );
  932. };
  933. renderFooter = (props: { footer?: ReactNode; prefixCls?: string; dataSource?: RecordType[] } = {}) => {
  934. let { footer } = props;
  935. const { prefixCls, dataSource } = props;
  936. if (typeof footer === 'function') {
  937. footer = footer(dataSource);
  938. }
  939. return isValidElement(footer) || typeof footer === 'string' ? (
  940. <div className={`${prefixCls}-footer`} key="footer">
  941. {footer}
  942. </div>
  943. ) : null;
  944. };
  945. renderMainTable = (props: any) => {
  946. const useFixedHeader = this.adapter.useFixedHeader();
  947. const emptySlot = this.renderEmpty(props);
  948. const table = [
  949. this.renderTable({
  950. ...props,
  951. fixed: false,
  952. useFixedHeader,
  953. headerRef: this._cacheHeaderRef,
  954. bodyRef: this.bodyWrapRef,
  955. includeHeader: !useFixedHeader,
  956. }),
  957. emptySlot,
  958. this.renderFooter(props),
  959. ];
  960. return table;
  961. };
  962. renderTable = (props: RenderTableProps<RecordType>) => {
  963. const {
  964. columns,
  965. filteredColumns,
  966. fixed,
  967. useFixedHeader,
  968. scroll,
  969. prefixCls,
  970. anyColumnFixed,
  971. includeHeader,
  972. showHeader,
  973. components,
  974. headerRef,
  975. bodyRef,
  976. rowSelection,
  977. dataSource,
  978. bodyHasScrollBar,
  979. disabledRowKeysSet,
  980. } = props;
  981. const selectedRowKeysSet = get(rowSelection, 'selectedRowKeysSet', new Set());
  982. const headTable =
  983. fixed || useFixedHeader ? (
  984. <HeadTable
  985. key="head"
  986. anyColumnFixed={anyColumnFixed}
  987. ref={headerRef}
  988. columns={filteredColumns}
  989. prefixCls={prefixCls}
  990. fixed={fixed}
  991. handleBodyScroll={this.handleBodyScrollLeft}
  992. components={components}
  993. scroll={scroll}
  994. showHeader={showHeader}
  995. selectedRowKeysSet={selectedRowKeysSet}
  996. dataSource={dataSource}
  997. bodyHasScrollBar={bodyHasScrollBar}
  998. />
  999. ) : null;
  1000. const bodyTable = (
  1001. <BodyTable
  1002. {...omit(props, ['rowSelection', 'headWidths']) as any}
  1003. key="body"
  1004. ref={bodyRef}
  1005. columns={filteredColumns}
  1006. fixed={fixed}
  1007. prefixCls={prefixCls}
  1008. handleWheel={this.handleWheel}
  1009. handleBodyScroll={this.handleBodyScroll}
  1010. anyColumnFixed={anyColumnFixed}
  1011. includeHeader={includeHeader}
  1012. showHeader={showHeader}
  1013. scroll={scroll}
  1014. components={components}
  1015. store={this.store}
  1016. selectedRowKeysSet={selectedRowKeysSet}
  1017. disabledRowKeysSet={disabledRowKeysSet}
  1018. />
  1019. );
  1020. return [headTable, bodyTable];
  1021. };
  1022. /**
  1023. * When columns change, call this function to get the latest withFnsColumns
  1024. * In addition to changes in columns, these props changes must be recalculated
  1025. * - hideExpandedColumn
  1026. * -rowSelection changes from trusy to falsy or rowSelection.hidden changes
  1027. * -isAnyFixedRight(columns) || get(scroll,'y') changes
  1028. *
  1029. * columns变化时,调用此函数获取最新的withFnsColumns
  1030. * 除了 columns 变化,这些 props 变化也要重新计算
  1031. * - hideExpandedColumn
  1032. * - rowSelection 从 trusy 变为 falsy 或 rowSelection.hidden 发生变化
  1033. * - isAnyFixedRight(columns) || get(scroll, 'y') 发生变化
  1034. *
  1035. * @param {Array} queries
  1036. * @param {Array} cachedColumns
  1037. * @returns columns after adding extended functions
  1038. */
  1039. handleColumns = (queries: ColumnProps<RecordType>[], cachedColumns: ColumnProps<RecordType>[]) => {
  1040. const { hideExpandedColumn, scroll, prefixCls, expandCellFixed, expandIcon, rowSelection } = this.props;
  1041. const childrenColumnName = 'children';
  1042. let columns: ColumnProps<RecordType>[] = cloneDeep(cachedColumns);
  1043. // eslint-disable-next-line @typescript-eslint/no-shadow
  1044. const addFns = (columns: ColumnProps<RecordType>[] = []) => {
  1045. if (Array.isArray(columns) && columns.length) {
  1046. each(columns, (column, index, originColumns) => {
  1047. const newColumn = this.addFnsInColumn(column);
  1048. const children = column[childrenColumnName];
  1049. if (Array.isArray(children) && children.length) {
  1050. const newChildren = [...children];
  1051. addFns(newChildren);
  1052. newColumn[childrenColumnName] = newChildren;
  1053. }
  1054. originColumns[index] = newColumn;
  1055. });
  1056. }
  1057. };
  1058. addFns(columns);
  1059. // hideExpandedColumn=false render expand column separately
  1060. if (!hideExpandedColumn) {
  1061. const column = this.normalizeExpandColumn({ prefixCls, expandCellFixed, expandIcon });
  1062. const destIndex = findIndex(columns, item => item.key === strings.DEFAULT_KEY_COLUMN_EXPAND);
  1063. if (column) {
  1064. if (destIndex > -1) {
  1065. columns[destIndex] = { ...column, ...columns[destIndex] };
  1066. } else if (column.fixed === 'right') {
  1067. columns = [...columns, column];
  1068. } else {
  1069. columns = [column, ...columns];
  1070. }
  1071. }
  1072. }
  1073. // selection column
  1074. if (rowSelection && !get(rowSelection, 'hidden')) {
  1075. const destIndex = findIndex(columns, item => item.key === strings.DEFAULT_KEY_COLUMN_SELECTION);
  1076. const column = this.normalizeSelectionColumn({ rowSelection, prefixCls });
  1077. if (destIndex > -1) {
  1078. columns[destIndex] = { ...column, ...columns[destIndex] };
  1079. } else if (column.fixed === 'right') {
  1080. columns = [...columns, column];
  1081. } else {
  1082. columns = [column, ...columns];
  1083. }
  1084. }
  1085. assignColumnKeys(columns);
  1086. return columns;
  1087. };
  1088. /**
  1089. * Convert children to columns object
  1090. * @param {Array} columns
  1091. * @param {ReactNode} children
  1092. * @returns {Array}
  1093. */
  1094. normalizeColumns = (columns: ColumnProps<RecordType>[], children: ReactNode) => {
  1095. const normalColumns = cloneDeep(this.getColumns(columns, children));
  1096. return normalColumns;
  1097. };
  1098. /**
  1099. * Combine pagination and table paging processing functions
  1100. */
  1101. mergePagination = (pagination: TablePaginationProps) => {
  1102. const newPagination = { onChange: this.foundation.setPage, ...pagination };
  1103. return newPagination;
  1104. };
  1105. render() {
  1106. let {
  1107. scroll,
  1108. prefixCls,
  1109. className,
  1110. style: wrapStyle = {},
  1111. bordered,
  1112. id,
  1113. pagination: propPagination,
  1114. virtualized,
  1115. size,
  1116. renderPagination: propRenderPagination,
  1117. getVirtualizedListRef,
  1118. loading,
  1119. hideExpandedColumn,
  1120. rowSelection: propRowSelection,
  1121. ...rest
  1122. } = this.props;
  1123. let {
  1124. rowSelection,
  1125. expandedRowKeys,
  1126. headWidths,
  1127. tableWidth,
  1128. pagination,
  1129. dataSource,
  1130. queries,
  1131. cachedColumns,
  1132. bodyHasScrollBar,
  1133. } = this.state;
  1134. wrapStyle = { ...wrapStyle };
  1135. let columns: ColumnProps<RecordType>[];
  1136. /**
  1137. * As state.queries will change, the columns should be refreshed as a whole at this time
  1138. * The scene of changes in queries
  1139. * 1. Filter
  1140. * 2. Pagination
  1141. *
  1142. * useFullRender needs to be passed to the user selection ReactNode, so columns need to be recalculated every time the selectedRowKeys changes
  1143. * 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
  1144. *
  1145. * 由于state.queries会发生变化,此时columns应该整体刷新
  1146. * queries变化的场景
  1147. * 1. 筛选
  1148. * 2. 分页
  1149. * useFullRender需要传给用户selection ReactNode,因此需要每次selectedRowKeys变化时重新计算columns
  1150. * TODO: 未来可以将传给用户的selection改为函数类型,让用户执行函数获取selection title的实时状态
  1151. */
  1152. if (!this.adapter.isAnyColumnUseFullRender(queries)) {
  1153. const rowSelectionUpdate: boolean = propRowSelection && !get(propRowSelection, 'hidden');
  1154. columns = this.foundation.memoizedWithFnsColumns(
  1155. queries,
  1156. cachedColumns,
  1157. rowSelectionUpdate,
  1158. hideExpandedColumn,
  1159. // Update the columns after the body scrollbar changes to ensure that the head and body are aligned
  1160. bodyHasScrollBar
  1161. );
  1162. } else {
  1163. columns = this.handleColumns(queries, cachedColumns);
  1164. }
  1165. const filteredColumns: ColumnProps<RecordType>[] = this.foundation.memoizedFilterColumns(columns);
  1166. const flattenFnsColumns: ColumnProps<RecordType>[] = this.foundation.memoizedFlattenFnsColumns(columns);
  1167. const anyColumnFixed = this.adapter.isAnyColumnFixed(columns);
  1168. /**
  1169. * - If it is the first page break, you need to calculate the current page
  1170. * - If it is manual paging, call foundation to modify the state
  1171. *
  1172. * TODO: After merging issue 1007, you can place it in the constructor to complete
  1173. * The reason is that #1007 exposes the parameters required by getCurrentPageData in the constructor
  1174. */
  1175. if (isNull(dataSource)) {
  1176. const pageData: BasePageData<RecordType> = this.foundation.getCurrentPageData(this.props.dataSource);
  1177. dataSource = pageData.dataSource;
  1178. pagination = pageData.pagination;
  1179. }
  1180. const props = {
  1181. ...rest,
  1182. ...this.state,
  1183. // props not in rest
  1184. virtualized,
  1185. scroll,
  1186. prefixCls,
  1187. size,
  1188. hideExpandedColumn,
  1189. // renamed state
  1190. columns,
  1191. // calculated value
  1192. anyColumnFixed,
  1193. rowExpandable: this.mergedRowExpandable,
  1194. pagination,
  1195. dataSource,
  1196. rowSelection,
  1197. expandedRowKeys,
  1198. renderExpandIcon: this.renderExpandIcon,
  1199. filteredColumns,
  1200. };
  1201. const x = get(scroll, 'x');
  1202. const y = get(scroll, 'y');
  1203. if (virtualized) {
  1204. if (typeof wrapStyle.width !== 'number') {
  1205. wrapStyle.width = x;
  1206. }
  1207. }
  1208. const wrapCls = classnames({
  1209. [`${prefixCls}-${strings.SIZE_SMALL}`]: size === strings.SIZE_SMALL,
  1210. [`${prefixCls}-${strings.SIZE_MIDDLE}`]: size === strings.SIZE_MIDDLE,
  1211. [`${prefixCls}-virtualized`]: Boolean(virtualized),
  1212. [`${prefixCls}-bordered`]: bordered,
  1213. [`${prefixCls}-fixed-header`]: Boolean(y),
  1214. [`${prefixCls}-scroll-position-left`]: ['both', 'left'].includes(this.position),
  1215. [`${prefixCls}-scroll-position-right`]: ['both', 'right'].includes(this.position),
  1216. });
  1217. // pagination
  1218. const tablePagination = pagination && propPagination ? this.renderPagination(pagination as TablePaginationProps, propRenderPagination) : null;
  1219. const paginationPosition = get(propPagination, 'position', 'bottom');
  1220. const tableContextValue: TableContextProps = {
  1221. ...this.context,
  1222. headWidths,
  1223. tableWidth,
  1224. anyColumnFixed,
  1225. flattenedColumns: flattenFnsColumns,
  1226. renderExpandIcon: this.renderExpandIcon,
  1227. renderSelection: this.renderSelection,
  1228. setHeadWidths: this.setHeadWidths,
  1229. getHeadWidths: this.getHeadWidths,
  1230. getCellWidths: this.getCellWidths,
  1231. handleRowExpanded: this.handleRowExpanded,
  1232. getVirtualizedListRef,
  1233. setBodyHasScrollbar: this.setBodyHasScrollbar,
  1234. };
  1235. return (
  1236. <div
  1237. ref={this.rootWrapRef}
  1238. className={classnames(className, `${prefixCls}-wrapper`)}
  1239. data-column-fixed={anyColumnFixed}
  1240. style={wrapStyle}
  1241. id={id}
  1242. >
  1243. <TableContextProvider {...tableContextValue}>
  1244. <Spin spinning={loading} size="large">
  1245. <div ref={this.wrapRef} className={wrapCls}>
  1246. <React.Fragment key={'pagination-top'}>
  1247. {['top', 'both'].includes(paginationPosition) ? tablePagination : null}
  1248. </React.Fragment>
  1249. {this.renderTitle({ title: (props as any).title, dataSource: props.dataSource, prefixCls: props.prefixCls })}
  1250. <div className={`${prefixCls}-container`}>{this.renderMainTable({ ...props })}</div>
  1251. <React.Fragment key={'pagination-bottom'}>
  1252. {['bottom', 'both'].includes(paginationPosition) ? tablePagination : null}
  1253. </React.Fragment>
  1254. </div>
  1255. </Spin>
  1256. </TableContextProvider>
  1257. </div>
  1258. );
  1259. }
  1260. }
  1261. export default Table;