Table.tsx 61 KB

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