Table.tsx 56 KB

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