Table.tsx 59 KB

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