Table.tsx 56 KB

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