Table.tsx 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  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. if ((Array.isArray(column.filters) && column.filters.length) || isValidElement(column.filterDropdown)) {
  854. const filter = (
  855. <ColumnFilter
  856. key={strings.DEFAULT_KEY_COLUMN_FILTER}
  857. {...curQuery}
  858. onFilterDropdownVisibleChange={(visible: boolean) => this.foundation.toggleShowFilter(dataIndex, visible)}
  859. onSelect={(data: OnSelectData) => this.foundation.handleFilterSelect(dataIndex, data)}
  860. />
  861. );
  862. useFullRender && (titleMap.filter = filter);
  863. titleArr.push(filter);
  864. }
  865. const newTitle =
  866. typeof rawTitle === 'function' ?
  867. () => rawTitle(titleMap) :
  868. titleArr.unshift(
  869. <React.Fragment key={strings.DEFAULT_KEY_COLUMN_TITLE}>{rawTitle}</React.Fragment>
  870. ) && titleArr;
  871. column = { ...column, title: newTitle };
  872. }
  873. return column;
  874. };
  875. toggleSelectRow = (selected: boolean, realKey: string | number, e: TableSelectionCellEvent) => {
  876. this.foundation.handleSelectRow(realKey, selected, e);
  877. };
  878. toggleSelectAllRow = (status: boolean, e: TableSelectionCellEvent) => {
  879. this.foundation.handleSelectAllRow(status, e);
  880. };
  881. /**
  882. * render pagination
  883. * @param {object} pagination
  884. * @param {object} propRenderPagination
  885. */
  886. renderPagination = (pagination: TablePaginationProps, propRenderPagination: RenderPagination) => {
  887. if (!pagination) {
  888. return null;
  889. }
  890. // use memoized pagination
  891. const mergedPagination = this.foundation.memoizedPagination(pagination);
  892. return (
  893. <LocaleConsumer componentName="Table">
  894. {(locale: TableLocale) => {
  895. const info = this.foundation.formatPaginationInfo(mergedPagination, locale.pageText);
  896. return <TablePagination info={info} pagination={mergedPagination} renderPagination={propRenderPagination} />;
  897. }}
  898. </LocaleConsumer>
  899. );
  900. };
  901. renderTitle = (props: { title?: ReactNode; prefixCls?: string; dataSource?: any[] } = {}) => {
  902. let { title } = props;
  903. const { prefixCls, dataSource } = props;
  904. if (typeof title === 'function') {
  905. title = title(dataSource);
  906. }
  907. return isValidElement(title) || typeof title === 'string' ? (
  908. <div className={`${prefixCls}-title`}>{title}</div>
  909. ) : null;
  910. };
  911. renderEmpty = (props: { prefixCls?: string; empty?: ReactNode; dataSource?: RecordType[] } = {}) => {
  912. const { prefixCls, empty, dataSource } = props;
  913. const wrapCls = `${prefixCls}-placeholder`;
  914. const isEmpty = this.foundation.isEmpty(dataSource);
  915. if (!isEmpty) {
  916. return null;
  917. }
  918. return (
  919. <LocaleConsumer componentName="Table" key={'emptyText'}>
  920. {(locale: TableLocale, localeCode: string) => (
  921. <div className={wrapCls}>
  922. <div className={`${prefixCls}-empty`}>{empty || locale.emptyText}</div>
  923. </div>
  924. )}
  925. </LocaleConsumer>
  926. );
  927. };
  928. renderFooter = (props: { footer?: ReactNode; prefixCls?: string; dataSource?: RecordType[] } = {}) => {
  929. let { footer } = props;
  930. const { prefixCls, dataSource } = props;
  931. if (typeof footer === 'function') {
  932. footer = footer(dataSource);
  933. }
  934. return isValidElement(footer) || typeof footer === 'string' ? (
  935. <div className={`${prefixCls}-footer`} key="footer">
  936. {footer}
  937. </div>
  938. ) : null;
  939. };
  940. renderMainTable = (props: any) => {
  941. const useFixedHeader = this.adapter.useFixedHeader();
  942. const emptySlot = this.renderEmpty(props);
  943. const table = [
  944. this.renderTable({
  945. ...props,
  946. fixed: false,
  947. useFixedHeader,
  948. headerRef: this._cacheHeaderRef,
  949. bodyRef: this.bodyWrapRef,
  950. includeHeader: !useFixedHeader,
  951. }),
  952. emptySlot,
  953. this.renderFooter(props),
  954. ];
  955. return table;
  956. };
  957. renderTable = (props: RenderTableProps<RecordType>) => {
  958. const {
  959. columns,
  960. filteredColumns,
  961. fixed,
  962. useFixedHeader,
  963. scroll,
  964. prefixCls,
  965. anyColumnFixed,
  966. includeHeader,
  967. showHeader,
  968. components,
  969. headerRef,
  970. bodyRef,
  971. rowSelection,
  972. dataSource,
  973. bodyHasScrollBar,
  974. disabledRowKeysSet,
  975. } = props;
  976. const selectedRowKeysSet = get(rowSelection, 'selectedRowKeysSet', new Set());
  977. const headTable =
  978. fixed || useFixedHeader ? (
  979. <HeadTable
  980. key="head"
  981. anyColumnFixed={anyColumnFixed}
  982. ref={headerRef}
  983. columns={filteredColumns}
  984. prefixCls={prefixCls}
  985. fixed={fixed}
  986. handleBodyScroll={this.handleBodyScrollLeft}
  987. components={components}
  988. scroll={scroll}
  989. showHeader={showHeader}
  990. selectedRowKeysSet={selectedRowKeysSet}
  991. dataSource={dataSource}
  992. bodyHasScrollBar={bodyHasScrollBar}
  993. />
  994. ) : null;
  995. const bodyTable = (
  996. <BodyTable
  997. {...omit(props, ['rowSelection', 'headWidths']) as any}
  998. key="body"
  999. ref={bodyRef}
  1000. columns={filteredColumns}
  1001. fixed={fixed}
  1002. prefixCls={prefixCls}
  1003. handleWheel={this.handleWheel}
  1004. handleBodyScroll={this.handleBodyScroll}
  1005. anyColumnFixed={anyColumnFixed}
  1006. includeHeader={includeHeader}
  1007. showHeader={showHeader}
  1008. scroll={scroll}
  1009. components={components}
  1010. store={this.store}
  1011. selectedRowKeysSet={selectedRowKeysSet}
  1012. disabledRowKeysSet={disabledRowKeysSet}
  1013. />
  1014. );
  1015. return [headTable, bodyTable];
  1016. };
  1017. /**
  1018. * When columns change, call this function to get the latest withFnsColumns
  1019. * In addition to changes in columns, these props changes must be recalculated
  1020. * - hideExpandedColumn
  1021. * -rowSelection changes from trusy to falsy or rowSelection.hidden changes
  1022. * -isAnyFixedRight(columns) || get(scroll,'y') changes
  1023. *
  1024. * columns变化时,调用此函数获取最新的withFnsColumns
  1025. * 除了 columns 变化,这些 props 变化也要重新计算
  1026. * - hideExpandedColumn
  1027. * - rowSelection 从 trusy 变为 falsy 或 rowSelection.hidden 发生变化
  1028. * - isAnyFixedRight(columns) || get(scroll, 'y') 发生变化
  1029. *
  1030. * @param {Array} queries
  1031. * @param {Array} cachedColumns
  1032. * @returns columns after adding extended functions
  1033. */
  1034. handleColumns = (queries: ColumnProps<RecordType>[], cachedColumns: ColumnProps<RecordType>[]) => {
  1035. const { hideExpandedColumn, scroll, prefixCls, expandCellFixed, expandIcon, rowSelection } = this.props;
  1036. const childrenColumnName = 'children';
  1037. let columns: ColumnProps<RecordType>[] = cloneDeep(cachedColumns);
  1038. // eslint-disable-next-line @typescript-eslint/no-shadow
  1039. const addFns = (columns: ColumnProps<RecordType>[] = []) => {
  1040. if (Array.isArray(columns) && columns.length) {
  1041. each(columns, (column, index, originColumns) => {
  1042. const newColumn = this.addFnsInColumn(column);
  1043. const children = column[childrenColumnName];
  1044. if (Array.isArray(children) && children.length) {
  1045. const newChildren = [...children];
  1046. addFns(newChildren);
  1047. newColumn[childrenColumnName] = newChildren;
  1048. }
  1049. originColumns[index] = newColumn;
  1050. });
  1051. }
  1052. };
  1053. addFns(columns);
  1054. // hideExpandedColumn=false render expand column separately
  1055. if (!hideExpandedColumn) {
  1056. const column = this.normalizeExpandColumn({ prefixCls, expandCellFixed, expandIcon });
  1057. const destIndex = findIndex(columns, item => item.key === strings.DEFAULT_KEY_COLUMN_EXPAND);
  1058. if (column) {
  1059. if (destIndex > -1) {
  1060. columns[destIndex] = { ...column, ...columns[destIndex] };
  1061. } else if (column.fixed === 'right') {
  1062. columns = [...columns, column];
  1063. } else {
  1064. columns = [column, ...columns];
  1065. }
  1066. }
  1067. }
  1068. // selection column
  1069. if (rowSelection && !get(rowSelection, 'hidden')) {
  1070. const destIndex = findIndex(columns, item => item.key === strings.DEFAULT_KEY_COLUMN_SELECTION);
  1071. const column = this.normalizeSelectionColumn({ rowSelection, prefixCls });
  1072. if (destIndex > -1) {
  1073. columns[destIndex] = { ...column, ...columns[destIndex] };
  1074. } else if (column.fixed === 'right') {
  1075. columns = [...columns, column];
  1076. } else {
  1077. columns = [column, ...columns];
  1078. }
  1079. }
  1080. assignColumnKeys(columns);
  1081. return columns;
  1082. };
  1083. /**
  1084. * Convert children to columns object
  1085. * @param {Array} columns
  1086. * @param {ReactNode} children
  1087. * @returns {Array}
  1088. */
  1089. normalizeColumns = (columns: ColumnProps<RecordType>[], children: ReactNode) => {
  1090. const normalColumns = cloneDeep(this.getColumns(columns, children));
  1091. return normalColumns;
  1092. };
  1093. /**
  1094. * Combine pagination and table paging processing functions
  1095. */
  1096. mergePagination = (pagination: TablePaginationProps) => {
  1097. const newPagination = { onChange: this.foundation.setPage, ...pagination };
  1098. return newPagination;
  1099. };
  1100. render() {
  1101. let {
  1102. scroll,
  1103. prefixCls,
  1104. className,
  1105. style: wrapStyle = {},
  1106. bordered,
  1107. id,
  1108. pagination: propPagination,
  1109. virtualized,
  1110. size,
  1111. renderPagination: propRenderPagination,
  1112. getVirtualizedListRef,
  1113. loading,
  1114. hideExpandedColumn,
  1115. rowSelection: propRowSelection,
  1116. ...rest
  1117. } = this.props;
  1118. let {
  1119. rowSelection,
  1120. expandedRowKeys,
  1121. headWidths,
  1122. tableWidth,
  1123. pagination,
  1124. dataSource,
  1125. queries,
  1126. cachedColumns,
  1127. bodyHasScrollBar,
  1128. } = this.state;
  1129. wrapStyle = { ...wrapStyle };
  1130. let columns: ColumnProps<RecordType>[];
  1131. /**
  1132. * As state.queries will change, the columns should be refreshed as a whole at this time
  1133. * The scene of changes in queries
  1134. * 1. Filter
  1135. * 2. Pagination
  1136. *
  1137. * useFullRender needs to be passed to the user selection ReactNode, so columns need to be recalculated every time the selectedRowKeys changes
  1138. * 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
  1139. *
  1140. * 由于state.queries会发生变化,此时columns应该整体刷新
  1141. * queries变化的场景
  1142. * 1. 筛选
  1143. * 2. 分页
  1144. * useFullRender需要传给用户selection ReactNode,因此需要每次selectedRowKeys变化时重新计算columns
  1145. * TODO: 未来可以将传给用户的selection改为函数类型,让用户执行函数获取selection title的实时状态
  1146. */
  1147. if (!this.adapter.isAnyColumnUseFullRender(queries)) {
  1148. const rowSelectionUpdate: boolean = propRowSelection && !get(propRowSelection, 'hidden');
  1149. columns = this.foundation.memoizedWithFnsColumns(
  1150. queries,
  1151. cachedColumns,
  1152. rowSelectionUpdate,
  1153. hideExpandedColumn,
  1154. // Update the columns after the body scrollbar changes to ensure that the head and body are aligned
  1155. bodyHasScrollBar
  1156. );
  1157. } else {
  1158. columns = this.handleColumns(queries, cachedColumns);
  1159. }
  1160. const filteredColumns: ColumnProps<RecordType>[] = this.foundation.memoizedFilterColumns(columns);
  1161. const flattenFnsColumns: ColumnProps<RecordType>[] = this.foundation.memoizedFlattenFnsColumns(columns);
  1162. const anyColumnFixed = this.adapter.isAnyColumnFixed(columns);
  1163. /**
  1164. * - If it is the first page break, you need to calculate the current page
  1165. * - If it is manual paging, call foundation to modify the state
  1166. *
  1167. * TODO: After merging issue 1007, you can place it in the constructor to complete
  1168. * The reason is that #1007 exposes the parameters required by getCurrentPageData in the constructor
  1169. */
  1170. if (isNull(dataSource)) {
  1171. const pageData: BasePageData<RecordType> = this.foundation.getCurrentPageData(this.props.dataSource);
  1172. dataSource = pageData.dataSource;
  1173. pagination = pageData.pagination;
  1174. }
  1175. const props = {
  1176. ...rest,
  1177. ...this.state,
  1178. // props not in rest
  1179. virtualized,
  1180. scroll,
  1181. prefixCls,
  1182. size,
  1183. hideExpandedColumn,
  1184. // renamed state
  1185. columns,
  1186. // calculated value
  1187. anyColumnFixed,
  1188. rowExpandable: this.mergedRowExpandable,
  1189. pagination,
  1190. dataSource,
  1191. rowSelection,
  1192. expandedRowKeys,
  1193. renderExpandIcon: this.renderExpandIcon,
  1194. filteredColumns,
  1195. };
  1196. const x = get(scroll, 'x');
  1197. const y = get(scroll, 'y');
  1198. if (virtualized) {
  1199. if (typeof wrapStyle.width !== 'number') {
  1200. wrapStyle.width = x;
  1201. }
  1202. }
  1203. const wrapCls = classnames({
  1204. [`${prefixCls}-${strings.SIZE_SMALL}`]: size === strings.SIZE_SMALL,
  1205. [`${prefixCls}-${strings.SIZE_MIDDLE}`]: size === strings.SIZE_MIDDLE,
  1206. [`${prefixCls}-virtualized`]: Boolean(virtualized),
  1207. [`${prefixCls}-bordered`]: bordered,
  1208. [`${prefixCls}-fixed-header`]: Boolean(y),
  1209. [`${prefixCls}-scroll-position-left`]: ['both', 'left'].includes(this.position),
  1210. [`${prefixCls}-scroll-position-right`]: ['both', 'right'].includes(this.position),
  1211. });
  1212. // pagination
  1213. const tablePagination = pagination && propPagination ? this.renderPagination(pagination as TablePaginationProps, propRenderPagination) : null;
  1214. const paginationPosition = get(propPagination, 'position', 'bottom');
  1215. const tableContextValue: TableContextProps = {
  1216. ...this.context,
  1217. headWidths,
  1218. tableWidth,
  1219. anyColumnFixed,
  1220. flattenedColumns: flattenFnsColumns,
  1221. renderExpandIcon: this.renderExpandIcon,
  1222. renderSelection: this.renderSelection,
  1223. setHeadWidths: this.setHeadWidths,
  1224. getHeadWidths: this.getHeadWidths,
  1225. getCellWidths: this.getCellWidths,
  1226. handleRowExpanded: this.handleRowExpanded,
  1227. getVirtualizedListRef,
  1228. setBodyHasScrollbar: this.setBodyHasScrollbar,
  1229. };
  1230. return (
  1231. <div
  1232. ref={this.rootWrapRef}
  1233. className={classnames(className, `${prefixCls}-wrapper`)}
  1234. style={wrapStyle}
  1235. id={id}
  1236. >
  1237. <TableContextProvider {...tableContextValue}>
  1238. <Spin spinning={loading} size="large">
  1239. <div ref={this.wrapRef} className={wrapCls}>
  1240. <React.Fragment key={'pagination-top'}>
  1241. {['top', 'both'].includes(paginationPosition) ? tablePagination : null}
  1242. </React.Fragment>
  1243. {this.renderTitle({ title: (props as any).title, dataSource: props.dataSource, prefixCls: props.prefixCls })}
  1244. <div className={`${prefixCls}-container`}>{this.renderMainTable({ ...props })}</div>
  1245. <React.Fragment key={'pagination-bottom'}>
  1246. {['bottom', 'both'].includes(paginationPosition) ? tablePagination : null}
  1247. </React.Fragment>
  1248. </div>
  1249. </Spin>
  1250. </TableContextProvider>
  1251. </div>
  1252. );
  1253. }
  1254. }
  1255. export default Table;