1
0

Table.tsx 60 KB

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