1
0

Table.tsx 63 KB

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