Table.tsx 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  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.onFilter || 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 (
  958. (Array.isArray(column.filters) && column.filters.length) ||
  959. isValidElement(column.filterDropdown) ||
  960. typeof column.renderFilterDropdown === 'function'
  961. ) {
  962. const filter = (
  963. <ColumnFilter
  964. key={strings.DEFAULT_KEY_COLUMN_FILTER}
  965. {...omit(curQuery, 'children')}
  966. filteredValue={filteredValue}
  967. onFilterDropdownVisibleChange={(visible: boolean) =>
  968. this.foundation.toggleShowFilter(dataIndex, visible)
  969. }
  970. onSelect={(data: OnSelectData) => this.foundation.handleFilterSelect(dataIndex, data)}
  971. />
  972. );
  973. useFullRender && (titleMap.filter = filter);
  974. hasSorterOrFilter = true;
  975. titleArr.push(filter);
  976. }
  977. const newTitle =
  978. typeof rawTitle === 'function' ? (
  979. () => rawTitle(titleMap)
  980. ) : hasSorterOrFilter ? (
  981. <div className={`${prefixCls}-operate-wrapper`}>{titleArr}</div>
  982. ) : (
  983. titleArr
  984. );
  985. column = { ...column, title: newTitle };
  986. }
  987. return column;
  988. };
  989. toggleSelectRow = (selected: boolean, realKey: string | number, e: TableSelectionCellEvent) => {
  990. this.foundation.handleSelectRow(realKey, selected, e);
  991. };
  992. toggleSelectAllRow = (selected: boolean, e: TableSelectionCellEvent) => {
  993. this.foundation.handleSelectAllRow(selected, e);
  994. };
  995. /**
  996. * render pagination
  997. * @param {object} pagination
  998. * @param {object} propRenderPagination
  999. */
  1000. renderPagination = (pagination: TablePaginationProps, propRenderPagination: RenderPagination) => {
  1001. if (!pagination) {
  1002. return null;
  1003. }
  1004. // use memoized pagination
  1005. const mergedPagination = this.foundation.memoizedPagination(pagination);
  1006. return (
  1007. <LocaleConsumer componentName="Table">
  1008. {(locale: TableLocale) => {
  1009. const info = this.foundation.formatPaginationInfo(mergedPagination, locale.pageText);
  1010. return <TablePagination info={info} pagination={mergedPagination} renderPagination={propRenderPagination} />;
  1011. }}
  1012. </LocaleConsumer>
  1013. );
  1014. };
  1015. renderTitle = (props: { title?: ReactNode | ((dataSource?: RecordType[]) => ReactNode); prefixCls?: string; dataSource?: any[] } = {}) => {
  1016. let { title } = props;
  1017. const { prefixCls, dataSource } = props;
  1018. if (typeof title === 'function') {
  1019. title = title(dataSource);
  1020. }
  1021. return isValidElement(title) || typeof title === 'string' ? (
  1022. <div className={`${prefixCls}-title`} x-semi-prop="title">{title}</div>
  1023. ) : null;
  1024. };
  1025. renderEmpty = (props: { prefixCls?: string; empty?: ReactNode; dataSource?: RecordType[] } = {}) => {
  1026. const { prefixCls, empty, dataSource } = props;
  1027. const wrapCls = `${prefixCls}-placeholder`;
  1028. const isEmpty = this.foundation.isEmpty(dataSource);
  1029. if (!isEmpty) {
  1030. return null;
  1031. }
  1032. return (
  1033. <LocaleConsumer componentName="Table" key={'emptyText'}>
  1034. {(locale: TableLocale, localeCode: string) => (
  1035. <div className={wrapCls}>
  1036. <div className={`${prefixCls}-empty`} x-semi-prop="empty">
  1037. {empty || locale.emptyText}
  1038. </div>
  1039. </div>
  1040. )}
  1041. </LocaleConsumer>
  1042. );
  1043. };
  1044. renderFooter = (props: { footer?: ReactNode | ((dataSource?: RecordType[]) => ReactNode); prefixCls?: string; dataSource?: RecordType[] } = {}) => {
  1045. let { footer } = props;
  1046. const { prefixCls, dataSource } = props;
  1047. if (typeof footer === 'function') {
  1048. footer = footer(dataSource);
  1049. }
  1050. return isValidElement(footer) || typeof footer === 'string' ? (
  1051. <div className={`${prefixCls}-footer`} key="footer" x-semi-prop="footer">
  1052. {footer}
  1053. </div>
  1054. ) : null;
  1055. };
  1056. renderMainTable = (props: any) => {
  1057. const useFixedHeader = this.adapter.useFixedHeader();
  1058. const emptySlot = this.renderEmpty(props);
  1059. const table = [
  1060. this.renderTable({
  1061. ...props,
  1062. fixed: false,
  1063. useFixedHeader,
  1064. headerRef: this._cacheHeaderRef,
  1065. bodyRef: this.bodyWrapRef,
  1066. includeHeader: !useFixedHeader,
  1067. emptySlot
  1068. }),
  1069. this.renderFooter(props),
  1070. ];
  1071. return table;
  1072. };
  1073. renderTable = (props: RenderTableProps<RecordType>) => {
  1074. const {
  1075. columns,
  1076. filteredColumns,
  1077. fixed,
  1078. useFixedHeader,
  1079. scroll,
  1080. prefixCls,
  1081. anyColumnFixed,
  1082. includeHeader,
  1083. showHeader,
  1084. components,
  1085. headerRef,
  1086. bodyRef,
  1087. onHeaderRow,
  1088. rowSelection,
  1089. dataSource,
  1090. bodyHasScrollBar,
  1091. disabledRowKeysSet,
  1092. sticky,
  1093. } = props;
  1094. const selectedRowKeysSet = get(rowSelection, 'selectedRowKeysSet', new Set());
  1095. const tableLayout = this.adapter.getTableLayout();
  1096. const headTable =
  1097. fixed || useFixedHeader ? (
  1098. <HeadTable
  1099. key="head"
  1100. tableLayout={tableLayout}
  1101. ref={headerRef}
  1102. columns={filteredColumns}
  1103. prefixCls={prefixCls}
  1104. fixed={fixed}
  1105. handleBodyScroll={this.handleBodyScrollLeft}
  1106. components={components}
  1107. scroll={scroll}
  1108. showHeader={showHeader}
  1109. selectedRowKeysSet={selectedRowKeysSet}
  1110. onHeaderRow={onHeaderRow}
  1111. dataSource={dataSource}
  1112. bodyHasScrollBar={bodyHasScrollBar}
  1113. sticky={sticky}
  1114. />
  1115. ) : null;
  1116. const bodyTable = (
  1117. <BodyTable
  1118. {...omit(props, ['rowSelection', 'headWidths']) as any}
  1119. key="body"
  1120. ref={bodyRef}
  1121. columns={filteredColumns}
  1122. fixed={fixed}
  1123. prefixCls={prefixCls}
  1124. handleWheel={this.handleWheel}
  1125. handleBodyScroll={this.handleBodyScroll}
  1126. anyColumnFixed={anyColumnFixed}
  1127. tableLayout={tableLayout}
  1128. includeHeader={includeHeader}
  1129. showHeader={showHeader}
  1130. scroll={scroll}
  1131. components={components}
  1132. store={this.store}
  1133. selectedRowKeysSet={selectedRowKeysSet}
  1134. disabledRowKeysSet={disabledRowKeysSet}
  1135. />
  1136. );
  1137. return [headTable, bodyTable];
  1138. };
  1139. /**
  1140. * When columns change, call this function to get the latest withFnsColumns
  1141. * In addition to changes in columns, these props changes must be recalculated
  1142. * - hideExpandedColumn
  1143. * -rowSelection changes from trusy to falsy or rowSelection.hidden changes
  1144. * -isAnyFixedRight(columns) || get(scroll,'y') changes
  1145. *
  1146. * columns变化时,调用此函数获取最新的withFnsColumns
  1147. * 除了 columns 变化,这些 props 变化也要重新计算
  1148. * - hideExpandedColumn
  1149. * - rowSelection 从 trusy 变为 falsy 或 rowSelection.hidden 发生变化
  1150. * - isAnyFixedRight(columns) || get(scroll, 'y') 发生变化
  1151. *
  1152. * @param {Array} queries
  1153. * @param {Array} cachedColumns
  1154. * @returns columns after adding extended functions
  1155. */
  1156. handleColumns = (queries: ColumnProps<RecordType>[], cachedColumns: ColumnProps<RecordType>[]) => {
  1157. const { hideExpandedColumn, scroll, prefixCls, expandCellFixed, expandIcon, rowSelection } = this.props;
  1158. const childrenColumnName = 'children';
  1159. let columns: ColumnProps<RecordType>[] = cloneDeep(cachedColumns);
  1160. const addFns = (columns: ColumnProps<RecordType>[] = []) => {
  1161. if (Array.isArray(columns) && columns.length) {
  1162. each(columns, (column, index, originColumns) => {
  1163. const newColumn = this.addFnsInColumn(column);
  1164. const children = column[childrenColumnName];
  1165. if (Array.isArray(children) && children.length) {
  1166. const newChildren = [...children];
  1167. addFns(newChildren);
  1168. newColumn[childrenColumnName] = newChildren;
  1169. }
  1170. originColumns[index] = newColumn;
  1171. });
  1172. }
  1173. };
  1174. addFns(columns);
  1175. // hideExpandedColumn=false render expand column separately
  1176. if (!hideExpandedColumn) {
  1177. const column = this.normalizeExpandColumn({ prefixCls, expandCellFixed, expandIcon });
  1178. const destIndex = findIndex(columns, item => item.key === strings.DEFAULT_KEY_COLUMN_EXPAND);
  1179. if (column) {
  1180. if (destIndex > -1) {
  1181. columns[destIndex] = { ...column, ...columns[destIndex] };
  1182. } else if (column.fixed === 'right') {
  1183. columns = [...columns, column];
  1184. } else {
  1185. columns = [column, ...columns];
  1186. }
  1187. }
  1188. }
  1189. // selection column
  1190. if (rowSelection && !get(rowSelection, 'hidden')) {
  1191. const destIndex = findIndex(columns, item => item.key === strings.DEFAULT_KEY_COLUMN_SELECTION);
  1192. const column = this.normalizeSelectionColumn({ rowSelection, prefixCls });
  1193. if (destIndex > -1) {
  1194. columns[destIndex] = { ...column, ...columns[destIndex] };
  1195. } else if (column.fixed === 'right') {
  1196. columns = [...columns, column];
  1197. } else {
  1198. columns = [column, ...columns];
  1199. }
  1200. }
  1201. assignColumnKeys(columns);
  1202. return columns;
  1203. };
  1204. /**
  1205. * Convert children to columns object
  1206. * @param {Array} columns
  1207. * @param {ReactNode} children
  1208. * @returns {Array}
  1209. */
  1210. normalizeColumns = (columns: ColumnProps<RecordType>[], children: ReactNode) => {
  1211. const normalColumns = cloneDeep(this.getColumns(columns, children));
  1212. return normalColumns;
  1213. };
  1214. /**
  1215. * Combine pagination and table paging processing functions
  1216. */
  1217. mergePagination = (pagination: TablePaginationProps) => {
  1218. const newPagination = { onChange: this.foundation.setPage, ...pagination };
  1219. return newPagination;
  1220. };
  1221. render() {
  1222. let {
  1223. scroll,
  1224. prefixCls,
  1225. className,
  1226. style: wrapStyle = {},
  1227. bordered,
  1228. id,
  1229. pagination: propPagination,
  1230. virtualized,
  1231. size,
  1232. renderPagination: propRenderPagination,
  1233. getVirtualizedListRef,
  1234. loading,
  1235. hideExpandedColumn,
  1236. rowSelection: propRowSelection,
  1237. ...rest
  1238. } = this.props;
  1239. let {
  1240. rowSelection,
  1241. expandedRowKeys,
  1242. headWidths,
  1243. tableWidth,
  1244. pagination,
  1245. dataSource,
  1246. queries,
  1247. cachedColumns,
  1248. bodyHasScrollBar,
  1249. } = this.state;
  1250. wrapStyle = { ...wrapStyle };
  1251. let columns: ColumnProps<RecordType>[];
  1252. /**
  1253. * As state.queries will change, the columns should be refreshed as a whole at this time
  1254. * The scene of changes in queries
  1255. * 1. Filter
  1256. * 2. Pagination
  1257. *
  1258. * useFullRender needs to be passed to the user selection ReactNode, so columns need to be recalculated every time the selectedRowKeys changes
  1259. * 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
  1260. *
  1261. * 由于state.queries会发生变化,此时columns应该整体刷新
  1262. * queries变化的场景
  1263. * 1. 筛选
  1264. * 2. 分页
  1265. * useFullRender需要传给用户selection ReactNode,因此需要每次selectedRowKeys变化时重新计算columns
  1266. * TODO: 未来可以将传给用户的selection改为函数类型,让用户执行函数获取selection title的实时状态
  1267. */
  1268. if (!this.adapter.isAnyColumnUseFullRender(queries)) {
  1269. const rowSelectionUpdate: boolean = propRowSelection && !get(propRowSelection, 'hidden');
  1270. columns = this.foundation.memoizedWithFnsColumns(
  1271. queries,
  1272. cachedColumns,
  1273. rowSelectionUpdate,
  1274. hideExpandedColumn,
  1275. // Update the columns after the body scrollbar changes to ensure that the head and body are aligned
  1276. bodyHasScrollBar
  1277. );
  1278. } else {
  1279. columns = this.handleColumns(queries, cachedColumns);
  1280. }
  1281. const filteredColumns: ColumnProps<RecordType>[] = this.foundation.memoizedFilterColumns(columns);
  1282. const flattenFnsColumns: ColumnProps<RecordType>[] = this.foundation.memoizedFlattenFnsColumns(columns);
  1283. const anyColumnFixed = this.adapter.isAnyColumnFixed(columns);
  1284. /**
  1285. * - If it is the first page break, you need to calculate the current page
  1286. * - If it is manual paging, call foundation to modify the state
  1287. *
  1288. * TODO: After merging issue 1007, you can place it in the constructor to complete
  1289. * The reason is that #1007 exposes the parameters required by getCurrentPageData in the constructor
  1290. */
  1291. // if (isNull(dataSource)) {
  1292. // const pageData: BasePageData<RecordType> = this.foundation.getCurrentPageData(this.props.dataSource);
  1293. // dataSource = pageData.dataSource;
  1294. // pagination = pageData.pagination;
  1295. // }
  1296. const props = {
  1297. ...rest,
  1298. ...this.state,
  1299. // props not in rest
  1300. virtualized,
  1301. scroll,
  1302. prefixCls,
  1303. size,
  1304. hideExpandedColumn,
  1305. // renamed state
  1306. columns,
  1307. // calculated value
  1308. anyColumnFixed,
  1309. rowExpandable: this.mergedRowExpandable,
  1310. pagination,
  1311. dataSource,
  1312. rowSelection,
  1313. expandedRowKeys,
  1314. renderExpandIcon: this.renderExpandIcon,
  1315. filteredColumns,
  1316. };
  1317. const x = get(scroll, 'x');
  1318. const y = get(scroll, 'y');
  1319. if (virtualized) {
  1320. if (typeof wrapStyle.width !== 'number') {
  1321. wrapStyle.width = x;
  1322. }
  1323. }
  1324. const wrapCls = classnames({
  1325. [`${prefixCls}-${strings.SIZE_SMALL}`]: size === strings.SIZE_SMALL,
  1326. [`${prefixCls}-${strings.SIZE_MIDDLE}`]: size === strings.SIZE_MIDDLE,
  1327. [`${prefixCls}-virtualized`]: Boolean(virtualized),
  1328. [`${prefixCls}-bordered`]: bordered,
  1329. [`${prefixCls}-fixed-header`]: Boolean(y),
  1330. [`${prefixCls}-scroll-position-left`]: ['both', 'left'].includes(this.position),
  1331. [`${prefixCls}-scroll-position-right`]: ['both', 'right'].includes(this.position),
  1332. });
  1333. // pagination
  1334. const tablePagination = pagination && propPagination ? this.renderPagination(pagination as TablePaginationProps, propRenderPagination) : null;
  1335. const paginationPosition = get(propPagination, 'position', 'bottom');
  1336. const tableContextValue: TableContextProps = {
  1337. ...this.context,
  1338. headWidths,
  1339. tableWidth,
  1340. anyColumnFixed,
  1341. flattenedColumns: flattenFnsColumns,
  1342. renderExpandIcon: this.renderExpandIcon,
  1343. renderSelection: this.renderSelection,
  1344. setHeadWidths: this.setHeadWidths,
  1345. getHeadWidths: this.getHeadWidths,
  1346. getCellWidths: this.getCellWidths,
  1347. handleRowExpanded: this.handleRowExpanded,
  1348. getVirtualizedListRef,
  1349. setBodyHasScrollbar: this.setBodyHasScrollbar,
  1350. };
  1351. const dataAttr = this.getDataAttr(rest);
  1352. return (
  1353. <div
  1354. ref={this.rootWrapRef}
  1355. className={classnames(className, `${prefixCls}-wrapper`, `${prefixCls}-wrapper-${props.direction}`)}
  1356. data-column-fixed={anyColumnFixed}
  1357. style={wrapStyle}
  1358. id={id}
  1359. {...dataAttr}
  1360. >
  1361. <TableContextProvider {...tableContextValue} direction={props.direction}>
  1362. <Spin spinning={loading} size="large">
  1363. <div ref={this.wrapRef} className={wrapCls}>
  1364. <React.Fragment key={'pagination-top'}>
  1365. {['top', 'both'].includes(paginationPosition) ? tablePagination : null}
  1366. </React.Fragment>
  1367. {this.renderTitle({
  1368. title: (props as any).title,
  1369. dataSource: props.dataSource,
  1370. prefixCls: props.prefixCls,
  1371. })}
  1372. <div className={`${prefixCls}-container`}>{this.renderMainTable({ ...props })}</div>
  1373. <React.Fragment key={'pagination-bottom'}>
  1374. {['bottom', 'both'].includes(paginationPosition) ? tablePagination : null}
  1375. </React.Fragment>
  1376. </div>
  1377. </Spin>
  1378. </TableContextProvider>
  1379. </div>
  1380. );
  1381. }
  1382. }
  1383. export default Table;