index.tsx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. /* eslint-disable eqeqeq */
  2. /* eslint-disable @typescript-eslint/member-ordering */
  3. /* eslint-disable max-len */
  4. import React, { ReactNode } from 'react';
  5. import PropTypes from 'prop-types';
  6. import { get, size, isMap, each, isEqual, pick, isNull, isFunction } from 'lodash';
  7. import classnames from 'classnames';
  8. import { VariableSizeList as List } from 'react-window';
  9. import {
  10. arrayAdd,
  11. getRecordKey,
  12. isExpanded,
  13. isSelected,
  14. isDisabled,
  15. getRecord,
  16. genExpandedRowKey,
  17. getDefaultVirtualizedRowConfig,
  18. isTreeTable
  19. } from '@douyinfe/semi-foundation/table/utils';
  20. import BodyFoundation, { BodyAdapter, FlattenData, GroupFlattenData } from '@douyinfe/semi-foundation/table/bodyFoundation';
  21. import { strings } from '@douyinfe/semi-foundation/table/constants';
  22. import Store from '@douyinfe/semi-foundation/utils/Store';
  23. import BaseComponent, { BaseProps } from '../../_base/baseComponent';
  24. import { logger } from '../utils';
  25. import ColGroup from '../ColGroup';
  26. import BaseRow from './BaseRow';
  27. import ExpandedRow from './ExpandedRow';
  28. import SectionRow from './SectionRow';
  29. import TableHeader from '../TableHeader';
  30. import ConfigContext from '../../configProvider/context';
  31. import TableContext, { TableContextProps } from '../table-context';
  32. import {
  33. ExpandedRowRender,
  34. Virtualized,
  35. GetVirtualizedListRef,
  36. ColumnProps,
  37. Size,
  38. BodyScrollEvent,
  39. Scroll,
  40. Fixed,
  41. TableComponents,
  42. RowExpandable,
  43. VirtualizedOnScroll,
  44. Direction,
  45. RowKey
  46. } from '../interface';
  47. export interface BodyProps extends BaseProps {
  48. anyColumnFixed?: boolean;
  49. columns?: ColumnProps[];
  50. dataSource?: Record<string, any>[];
  51. disabledRowKeysSet: Set<any>; // required
  52. emptySlot?: ReactNode;
  53. expandedRowKeys?: (string | number)[];
  54. expandedRowRender?: ExpandedRowRender<Record<string, any>>;
  55. fixed?: Fixed;
  56. forwardedRef?: React.MutableRefObject<HTMLDivElement> | ((instance: any) => void);
  57. handleBodyScroll?: (e: BodyScrollEvent) => void;
  58. handleWheel?: (e: React.WheelEvent<HTMLDivElement>) => void;
  59. includeHeader?: boolean;
  60. prefixCls?: string;
  61. scroll?: Scroll;
  62. selectedRowKeysSet: Set<any>; // required
  63. showHeader?: boolean;
  64. size?: Size;
  65. virtualized?: Virtualized;
  66. components?: TableComponents;
  67. store: Store;
  68. groups?: Map<string, Record<string, any>[]>[];
  69. rowKey?: RowKey<Record<string, any>>;
  70. childrenRecordName?: string;
  71. rowExpandable?: RowExpandable<Record<string, any>>;
  72. renderExpandIcon: (record: Record<string, any>, isNested: boolean) => ReactNode | null;
  73. headerRef?: React.MutableRefObject<HTMLDivElement> | ((instance: any) => void);
  74. onScroll?: VirtualizedOnScroll;
  75. }
  76. export interface BodyState {
  77. virtualizedData?: Array<FlattenData | GroupFlattenData>;
  78. cache?: {
  79. virtualizedScrollTop?: number;
  80. virtualizedScrollLeft?: number;
  81. };
  82. cachedExpandBtnShouldInRow?: boolean;
  83. cachedExpandRelatedProps?: any[];
  84. }
  85. export interface BodyContext {
  86. getVirtualizedListRef: GetVirtualizedListRef;
  87. flattenedColumns: ColumnProps[];
  88. getCellWidths: (flattenedColumns: ColumnProps[]) => number[];
  89. }
  90. class Body extends BaseComponent<BodyProps, BodyState> {
  91. static contextType = TableContext;
  92. static propTypes = {
  93. anyColumnFixed: PropTypes.bool,
  94. childrenRecordName: PropTypes.string,
  95. columns: PropTypes.array,
  96. components: PropTypes.object,
  97. dataSource: PropTypes.array,
  98. disabledRowKeysSet: PropTypes.instanceOf(Set).isRequired,
  99. emptySlot: PropTypes.node,
  100. expandRowByClick: PropTypes.bool,
  101. expandedRowKeys: PropTypes.array,
  102. expandedRowRender: PropTypes.func,
  103. fixed: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
  104. forwardedRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
  105. groups: PropTypes.instanceOf(Map),
  106. handleBodyScroll: PropTypes.func,
  107. handleWheel: PropTypes.func,
  108. headerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
  109. includeHeader: PropTypes.bool,
  110. onScroll: PropTypes.func,
  111. prefixCls: PropTypes.string,
  112. renderExpandIcon: PropTypes.func,
  113. rowExpandable: PropTypes.func,
  114. rowKey: PropTypes.oneOfType([PropTypes.string, PropTypes.bool, PropTypes.func]),
  115. scroll: PropTypes.object,
  116. selectedRowKeysSet: PropTypes.instanceOf(Set).isRequired,
  117. showHeader: PropTypes.bool,
  118. size: PropTypes.string,
  119. store: PropTypes.object,
  120. virtualized: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
  121. };
  122. ref: React.MutableRefObject<any>;
  123. listRef: React.MutableRefObject<any>;
  124. observer: ResizeObserver;
  125. foundation: BodyFoundation;
  126. cellWidths: number[];
  127. flattenedColumns: ColumnProps[];
  128. context: TableContextProps;
  129. constructor(props: BodyProps, context: BodyContext) {
  130. super(props);
  131. this.ref = React.createRef();
  132. this.state = {
  133. virtualizedData: [],
  134. cache: {
  135. virtualizedScrollTop: null,
  136. virtualizedScrollLeft: null,
  137. },
  138. cachedExpandBtnShouldInRow: null,
  139. cachedExpandRelatedProps: [],
  140. };
  141. this.listRef = React.createRef();
  142. const { getVirtualizedListRef, flattenedColumns, getCellWidths } = context;
  143. if (getVirtualizedListRef) {
  144. if (props.virtualized) {
  145. getVirtualizedListRef(this.listRef);
  146. } else {
  147. console.warn('getVirtualizedListRef only works with virtualized. ' +
  148. 'See https://semi.design/zh-CN/show/table for more information.');
  149. }
  150. }
  151. this.foundation = new BodyFoundation(this.adapter);
  152. this.flattenedColumns = flattenedColumns;
  153. this.cellWidths = getCellWidths(flattenedColumns);
  154. this.observer = null;
  155. }
  156. get adapter(): BodyAdapter<BodyProps, BodyState> {
  157. return {
  158. ...super.adapter,
  159. setVirtualizedData: (virtualizedData, cb) => this.setState({ virtualizedData }, cb),
  160. setCachedExpandBtnShouldInRow: cachedExpandBtnShouldInRow => this.setState({ cachedExpandBtnShouldInRow }),
  161. setCachedExpandRelatedProps: cachedExpandRelatedProps => this.setState({ cachedExpandRelatedProps }),
  162. observeBodyResize: (bodyWrapDOM: HTMLDivElement) => {
  163. const { setBodyHasScrollbar } = this.context;
  164. // Callback when the size of the body dom content changes, notifying Table.jsx whether the bodyHasScrollBar exists
  165. const resizeCallback = () => {
  166. const update = () => {
  167. const { offsetWidth, clientWidth } = bodyWrapDOM;
  168. const bodyHasScrollBar = clientWidth < offsetWidth;
  169. setBodyHasScrollbar(bodyHasScrollBar);
  170. };
  171. const requestAnimationFrame = window.requestAnimationFrame || window.setTimeout;
  172. requestAnimationFrame(update);
  173. };
  174. // Monitor body dom resize
  175. if (bodyWrapDOM) {
  176. if (get(window, 'ResizeObserver')) {
  177. if (this.observer) {
  178. this.observer.unobserve(bodyWrapDOM);
  179. this.observer = null;
  180. }
  181. this.observer = new ResizeObserver(resizeCallback);
  182. this.observer.observe(bodyWrapDOM);
  183. } else {
  184. logger.warn(
  185. 'The current browser does not support ResizeObserver,' +
  186. 'and the table may be misaligned after plugging and unplugging the mouse and keyboard.' +
  187. 'You can try to refresh it.'
  188. );
  189. }
  190. }
  191. },
  192. unobserveBodyResize: () => {
  193. const bodyWrapDOM = this.ref.current;
  194. if (this.observer) {
  195. this.observer.unobserve(bodyWrapDOM);
  196. this.observer = null;
  197. }
  198. },
  199. };
  200. }
  201. componentDidUpdate(prevProps: BodyProps, prevState: BodyState) {
  202. const { virtualized, dataSource, expandedRowKeys, columns, scroll } = this.props;
  203. if (virtualized) {
  204. if (
  205. prevProps.dataSource !== dataSource ||
  206. prevProps.expandedRowKeys !== expandedRowKeys ||
  207. prevProps.columns !== columns
  208. ) {
  209. this.foundation.initVirtualizedData();
  210. }
  211. }
  212. const expandRelatedProps = strings.EXPAND_RELATED_PROPS;
  213. const newExpandRelatedProps = expandRelatedProps.map(key => get(this.props, key, undefined));
  214. if (!isEqual(newExpandRelatedProps, prevState.cachedExpandRelatedProps)) {
  215. this.foundation.initExpandBtnShouldInRow(newExpandRelatedProps);
  216. }
  217. const scrollY = get(scroll, 'y');
  218. const bodyWrapDOM = this.ref.current;
  219. if (scrollY && scrollY !== get(prevProps, 'scroll.y')) {
  220. this.foundation.observeBodyResize(bodyWrapDOM);
  221. }
  222. }
  223. forwardRef = (node: HTMLDivElement) => {
  224. const { forwardedRef } = this.props;
  225. this.ref.current = node;
  226. this.foundation.observeBodyResize(node);
  227. if (typeof forwardedRef === 'function') {
  228. forwardedRef(node);
  229. } else if (forwardedRef && typeof forwardedRef === 'object') {
  230. forwardedRef.current = node;
  231. }
  232. };
  233. itemSize = (index: number) => {
  234. const { virtualized, size: tableSize } = this.props;
  235. const { virtualizedData } = this.state;
  236. const virtualizedItem = get(virtualizedData, index);
  237. const defaultConfig = getDefaultVirtualizedRowConfig(tableSize, virtualizedItem.sectionRow);
  238. const itemSize = get(virtualized, 'itemSize', defaultConfig.height);
  239. let realSize = itemSize;
  240. if (typeof itemSize === 'function') {
  241. realSize = itemSize(index, {
  242. expandedRow: get(virtualizedItem, 'expandedRow', false),
  243. sectionRow: get(virtualizedItem, 'sectionRow', false),
  244. });
  245. }
  246. if (realSize < defaultConfig.minHeight) {
  247. logger.warn(`The computed real \`itemSize\` cannot be less than ${defaultConfig.minHeight}`);
  248. }
  249. return realSize;
  250. };
  251. itemKey = (index: number, data: Array<FlattenData | GroupFlattenData>) => get(data, [index, 'key'], index);
  252. handleRowClick = (rowKey: RowKey<any>, e: React.MouseEvent<HTMLElement>, expand: boolean) => {
  253. const { handleRowExpanded } = this.context;
  254. handleRowExpanded(!expand, rowKey, e);
  255. };
  256. handleVirtualizedScroll = (props = {}) => {
  257. const onScroll = get(this.props.virtualized, 'onScroll');
  258. if (typeof onScroll === 'function') {
  259. onScroll(props);
  260. }
  261. };
  262. /**
  263. * @param {MouseEvent<HTMLDivElement>} e
  264. */
  265. handleVirtualizedBodyScroll = (e: BodyScrollEvent) => {
  266. const { handleBodyScroll } = this.props;
  267. const newScrollLeft = get(e, 'nativeEvent.target.scrollLeft');
  268. const newScrollTop = get(e, 'nativeEvent.target.scrollTop');
  269. if (newScrollTop === this.state.cache.virtualizedScrollTop) {
  270. this.handleVirtualizedScroll({ horizontalScrolling: true });
  271. }
  272. this.state.cache.virtualizedScrollLeft = newScrollLeft;
  273. this.state.cache.virtualizedScrollTop = newScrollTop;
  274. if (typeof handleBodyScroll === 'function') {
  275. handleBodyScroll(e);
  276. }
  277. };
  278. getVirtualizedRowWidth = () => {
  279. const { getCellWidths } = this.context;
  280. const { columns } = this.props;
  281. const cellWidths = getCellWidths(columns);
  282. const rowWidth = arrayAdd(cellWidths, 0, size(columns));
  283. return rowWidth;
  284. };
  285. renderVirtualizedRow = (options: { index?: number; style?: React.CSSProperties; isScrolling?: boolean }) => {
  286. const { index, style } = options;
  287. const { virtualizedData, cachedExpandBtnShouldInRow } = this.state;
  288. const { flattenedColumns } = this.context;
  289. const virtualizedItem: any = get(virtualizedData, [index], {});
  290. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  291. const { key, parentKeys, expandedRow, sectionRow, ...rest } = virtualizedItem;
  292. const rowWidth = this.getVirtualizedRowWidth();
  293. const expandBtnShouldInRow = cachedExpandBtnShouldInRow;
  294. const props = {
  295. ...this.props,
  296. style: {
  297. ...style,
  298. width: rowWidth,
  299. },
  300. ...rest,
  301. columns: flattenedColumns,
  302. index,
  303. expandBtnShouldInRow,
  304. };
  305. // eslint-disable-next-line no-nested-ternary
  306. return sectionRow ?
  307. this.renderSectionRow(props) :
  308. expandedRow ?
  309. this.renderExpandedRow(props) :
  310. this.renderBaseRow(props);
  311. };
  312. // virtualized List innerElementType
  313. renderTbody = React.forwardRef<HTMLDivElement, any>((props: any = {}, ref: React.MutableRefObject<HTMLDivElement> | ((instance: HTMLDivElement) => void)) => (
  314. <div
  315. {...props}
  316. onScroll={(...args) => {
  317. if (props.onScroll) {
  318. props.onScroll(...args);
  319. }
  320. }}
  321. // eslint-disable-next-line react/no-this-in-sfc,react/destructuring-assignment
  322. className={classnames(props.className, `${this.props.prefixCls}-tbody`)}
  323. style={{ ...props.style }}
  324. ref={ref}
  325. />
  326. ));
  327. // virtualized List outerElementType
  328. renderOuter = React.forwardRef<HTMLDivElement, any>((props: any, ref: React.MutableRefObject<HTMLDivElement> | ((instance: HTMLDivElement) => void)) => {
  329. const { children, ...rest } = props;
  330. // eslint-disable-next-line react/no-this-in-sfc
  331. const { handleWheel, prefixCls, emptySlot, dataSource } = this.props;
  332. // eslint-disable-next-line react/no-this-in-sfc
  333. const tableWidth = this.getVirtualizedRowWidth();
  334. const tableCls = classnames(`${prefixCls}`, `${prefixCls}-fixed`);
  335. return (
  336. <div
  337. {...rest}
  338. ref={ref}
  339. onWheel={(...args) => {
  340. if (handleWheel) {
  341. handleWheel(...args);
  342. }
  343. if (rest.onWheel) {
  344. rest.onWheel(...args);
  345. }
  346. }}
  347. onScroll={(...args) => {
  348. // eslint-disable-next-line react/no-this-in-sfc
  349. this.handleVirtualizedBodyScroll(...args);
  350. if (rest.onScroll) {
  351. rest.onScroll(...args);
  352. }
  353. }}
  354. >
  355. <div style={{ width: tableWidth }} className={tableCls}>
  356. {size(dataSource) === 0 ? emptySlot : children}
  357. </div>
  358. </div>
  359. );
  360. });
  361. onItemsRendered = (props: { overscanStartIndex: number; overscanStopIndex: number; visibleStartIndex: number; visibleStopIndex: number }) => {
  362. if (this.state.cache.virtualizedScrollLeft && this.ref.current) {
  363. this.ref.current.scrollLeft = this.state.cache.virtualizedScrollLeft;
  364. }
  365. };
  366. renderVirtualizedBody = (direction?: Direction) => {
  367. const { scroll, prefixCls, virtualized, anyColumnFixed, columns } = this.props;
  368. const { virtualizedData } = this.state;
  369. const { getCellWidths } = this.context;
  370. const cellWidths = getCellWidths(columns);
  371. if (!size(cellWidths)) {
  372. return null;
  373. }
  374. const rawY = get(scroll, 'y');
  375. const yIsNumber = typeof rawY === 'number';
  376. const y = yIsNumber ? rawY : 600;
  377. if (!yIsNumber) {
  378. logger.warn('You have to specific "scroll.y" which must be a number for table virtualization!');
  379. }
  380. const listStyle = {
  381. width: '100%',
  382. height: y,
  383. overflowX: 'auto',
  384. overflowY: 'auto',
  385. } as const;
  386. const wrapCls = classnames(`${prefixCls}-body`);
  387. return (
  388. <List<Array<FlattenData | GroupFlattenData>>
  389. {...virtualized}
  390. initialScrollOffset={this.state.cache.virtualizedScrollTop}
  391. onScroll={this.handleVirtualizedScroll}
  392. onItemsRendered={this.onItemsRendered}
  393. ref={this.listRef}
  394. className={wrapCls}
  395. outerRef={this.forwardRef}
  396. height={listStyle.height}
  397. width={listStyle.width}
  398. itemData={virtualizedData}
  399. itemSize={this.itemSize}
  400. itemCount={virtualizedData.length}
  401. itemKey={this.itemKey}
  402. innerElementType={this.renderTbody}
  403. outerElementType={this.renderOuter}
  404. style={{ ...listStyle, direction }}
  405. direction={direction}
  406. >
  407. {this.renderVirtualizedRow}
  408. </List>
  409. );
  410. };
  411. /**
  412. * render group title
  413. * @param {*} props
  414. */
  415. renderSectionRow = (props: RenderSectionRowProps = { groupKey: undefined }) => {
  416. const { dataSource, rowKey, group, groupKey, index } = props;
  417. const sectionRowPickKeys = Object.keys(SectionRow.propTypes);
  418. const sectionRowProps: any = pick(props, sectionRowPickKeys);
  419. const { handleRowExpanded } = this.context;
  420. return (
  421. <SectionRow
  422. {...sectionRowProps}
  423. record={{
  424. groupKey,
  425. records: [...group].map(recordKey => getRecord(dataSource, recordKey, rowKey)),
  426. }}
  427. index={index}
  428. onExpand={handleRowExpanded}
  429. data={dataSource}
  430. key={groupKey || index}
  431. />
  432. );
  433. };
  434. renderExpandedRow = (props: RenderExpandedRowProps = { renderExpandIcon: () => null }) => {
  435. const {
  436. style,
  437. components,
  438. renderExpandIcon,
  439. expandedRowRender,
  440. record,
  441. columns,
  442. expanded,
  443. index,
  444. rowKey,
  445. virtualized,
  446. } = props;
  447. let key = getRecordKey(record, rowKey);
  448. if (key == null) {
  449. key = index;
  450. }
  451. const { flattenedColumns, getCellWidths } = this.context;
  452. // we use memoized cellWidths to avoid re-render expanded row (fix #686)
  453. if (flattenedColumns !== this.flattenedColumns) {
  454. this.flattenedColumns = flattenedColumns;
  455. this.cellWidths = getCellWidths(flattenedColumns);
  456. }
  457. return (
  458. <ExpandedRow
  459. style={style}
  460. components={components}
  461. renderExpandIcon={renderExpandIcon}
  462. expandedRowRender={expandedRowRender}
  463. record={record}
  464. columns={columns}
  465. expanded={expanded}
  466. index={index}
  467. virtualized={virtualized}
  468. key={genExpandedRowKey(key)}
  469. cellWidths={this.cellWidths}
  470. />
  471. );
  472. };
  473. /**
  474. * render base row
  475. * @param {*} props
  476. * @returns
  477. */
  478. renderBaseRow(props: any = {}) {
  479. const {
  480. rowKey,
  481. columns,
  482. expandedRowKeys,
  483. rowExpandable,
  484. record,
  485. index,
  486. level,
  487. expandBtnShouldInRow, // effect the display of the indent span
  488. selectedRowKeysSet,
  489. disabledRowKeysSet,
  490. expandRowByClick,
  491. } = props;
  492. const baseRowPickKeys = Object.keys(BaseRow.propTypes);
  493. const baseRowProps: Record<string, any> = pick(props, baseRowPickKeys);
  494. let key = getRecordKey(record, rowKey);
  495. if (key == null) {
  496. key = index;
  497. }
  498. const expanded = isExpanded(expandedRowKeys, key);
  499. const expandable = rowExpandable && rowExpandable(record);
  500. const expandableProps: {
  501. level?: number;
  502. expanded?: boolean;
  503. expandableRow?: boolean;
  504. onRowClick?: (...args: any[]) => void;
  505. } = {
  506. level: undefined,
  507. expanded,
  508. };
  509. if (expandable || expandBtnShouldInRow) {
  510. expandableProps.level = level;
  511. expandableProps.expandableRow = expandable;
  512. if (expandRowByClick) {
  513. expandableProps.onRowClick = this.handleRowClick;
  514. }
  515. }
  516. const selectionProps = {
  517. selected: isSelected(selectedRowKeysSet, key),
  518. disabled: isDisabled(disabledRowKeysSet, key),
  519. };
  520. const { getCellWidths } = this.context;
  521. const cellWidths = getCellWidths(columns, null, true);
  522. return (
  523. <BaseRow
  524. {...baseRowProps}
  525. {...expandableProps}
  526. {...selectionProps}
  527. key={key}
  528. rowKey={key}
  529. cellWidths={cellWidths}
  530. />
  531. );
  532. }
  533. /**
  534. * render grouped rows
  535. * @returns {ReactNode[]} renderedRows
  536. */
  537. renderGroupedRows = () => {
  538. const { groups, dataSource: data, rowKey, expandedRowKeys } = this.props;
  539. const { flattenedColumns } = this.context;
  540. const groupsInData = new Map();
  541. const renderedRows: ReactNode[] = [];
  542. if (groups != null && Array.isArray(data) && data.length) {
  543. data.forEach(record => {
  544. const recordKey = getRecordKey(record, rowKey);
  545. groups.forEach((group: Map<string, Record<string, any>[]>, key: number) => {
  546. if (group.has(recordKey)) {
  547. if (!groupsInData.has(key)) {
  548. groupsInData.set(key, new Set([]));
  549. }
  550. groupsInData.get(key).add(recordKey);
  551. return false;
  552. }
  553. return undefined;
  554. });
  555. });
  556. }
  557. let index = -1;
  558. groupsInData.forEach((group, groupKey) => {
  559. // Calculate the expanded state of the group
  560. const expanded = isExpanded(expandedRowKeys, groupKey);
  561. // Render the title of the group
  562. renderedRows.push(
  563. this.renderSectionRow({
  564. ...this.props,
  565. columns: flattenedColumns,
  566. index: ++index,
  567. group,
  568. groupKey,
  569. expanded,
  570. })
  571. );
  572. // Render the grouped content when the group is expanded
  573. if (expanded) {
  574. const dataInGroup: any[] = [];
  575. group.forEach((recordKey: string) => {
  576. const record = getRecord(data, recordKey, rowKey);
  577. if (record != null) {
  578. dataInGroup.push(record);
  579. }
  580. });
  581. /**
  582. * Render the contents of the group row
  583. */
  584. renderedRows.push(this.renderBodyRows(dataInGroup));
  585. }
  586. });
  587. return renderedRows;
  588. };
  589. renderBodyRows(data: Record<string, any>[] = [], level = 0, renderedRows: ReactNode[] = []) {
  590. const {
  591. rowKey,
  592. expandedRowRender,
  593. expandedRowKeys,
  594. childrenRecordName,
  595. rowExpandable,
  596. } = this.props;
  597. const hasExpandedRowRender = typeof expandedRowRender === 'function';
  598. const expandBtnShouldInRow = this.state.cachedExpandBtnShouldInRow;
  599. const { flattenedColumns } = this.context;
  600. each(data, (record, index) => {
  601. let key = getRecordKey(record, rowKey);
  602. if (key == null) {
  603. key = index;
  604. }
  605. const recordChildren = get(record, childrenRecordName);
  606. const recordHasChildren = Boolean(Array.isArray(recordChildren) && recordChildren.length);
  607. renderedRows.push(
  608. this.renderBaseRow({
  609. ...this.props,
  610. columns: flattenedColumns,
  611. expandBtnShouldInRow,
  612. record,
  613. key,
  614. level,
  615. index,
  616. })
  617. );
  618. // render expand row
  619. const expanded = isExpanded(expandedRowKeys, key);
  620. if (hasExpandedRowRender && rowExpandable && rowExpandable(record) && expanded) {
  621. const currentExpandRow = this.renderExpandedRow({
  622. ...this.props,
  623. columns: flattenedColumns,
  624. level,
  625. index,
  626. record,
  627. expanded,
  628. });
  629. /**
  630. * If expandedRowRender returns falsy, this expanded row will not be rendered
  631. * Render an empty div before v1.19.7
  632. */
  633. if (!isNull(currentExpandRow)) {
  634. renderedRows.push(currentExpandRow);
  635. }
  636. }
  637. // render tree data
  638. if (recordHasChildren && expanded) {
  639. const nestedRows = this.renderBodyRows(recordChildren, level + 1);
  640. renderedRows.push(...nestedRows);
  641. }
  642. });
  643. return renderedRows;
  644. }
  645. renderBody = (direction?: Direction) => {
  646. const {
  647. scroll,
  648. prefixCls,
  649. columns,
  650. components,
  651. fixed,
  652. handleWheel,
  653. headerRef,
  654. handleBodyScroll,
  655. anyColumnFixed,
  656. showHeader,
  657. emptySlot,
  658. includeHeader,
  659. dataSource,
  660. onScroll,
  661. groups,
  662. expandedRowRender,
  663. } = this.props;
  664. const x = get(scroll, 'x');
  665. const y = get(scroll, 'y');
  666. const bodyStyle: {
  667. maxHeight?: string | number;
  668. overflow?: string;
  669. WebkitTransform?: string;
  670. } = {};
  671. const tableStyle: {
  672. width?: string | number;
  673. } = {};
  674. const Table = get(components, 'body.outer', 'table');
  675. const BodyWrapper = get(components, 'body.wrapper') || 'tbody';
  676. if (y) {
  677. bodyStyle.maxHeight = y;
  678. }
  679. if (x) {
  680. tableStyle.width = x;
  681. }
  682. if (anyColumnFixed && size(dataSource)) {
  683. // Auto is better than scroll. For example, when there is only scrollY, the scroll axis is not displayed horizontally.
  684. bodyStyle.overflow = 'auto';
  685. // Fix weird webkit render bug
  686. bodyStyle.WebkitTransform = 'translate3d (0, 0, 0)';
  687. }
  688. const colgroup = <ColGroup components={get(components, 'body')} columns={columns} prefixCls={prefixCls} />;
  689. // const tableBody = this.renderBody();
  690. const wrapCls = `${prefixCls}-body`;
  691. const baseTable = (
  692. <div
  693. key="bodyTable"
  694. className={wrapCls}
  695. style={bodyStyle}
  696. ref={this.forwardRef}
  697. onWheel={handleWheel}
  698. onScroll={handleBodyScroll}
  699. >
  700. <Table
  701. role={ isMap(groups) || isFunction(expandedRowRender) || isTreeTable({ dataSource }) ? 'treegrid' : 'grid'}
  702. aria-rowcount={dataSource && dataSource.length}
  703. aria-colcount={columns && columns.length}
  704. style={tableStyle}
  705. className={classnames(prefixCls, {
  706. [`${prefixCls}-fixed`]: anyColumnFixed,
  707. })}
  708. >
  709. {colgroup}
  710. {includeHeader && showHeader ? (
  711. <TableHeader {...this.props} ref={headerRef} components={components} columns={columns} />
  712. ) : null}
  713. <BodyWrapper className={`${prefixCls}-tbody`} onScroll={onScroll}>
  714. {isMap(groups) ? this.renderGroupedRows() : this.renderBodyRows(dataSource)}
  715. </BodyWrapper>
  716. </Table>
  717. {emptySlot}
  718. </div>
  719. );
  720. if (fixed && columns.length) {
  721. return (
  722. <div key="bodyTable" className={`${prefixCls}-body-outer`}>
  723. {baseTable}
  724. </div>
  725. );
  726. }
  727. return baseTable;
  728. };
  729. render() {
  730. const { virtualized } = this.props;
  731. return (
  732. <ConfigContext.Consumer>
  733. {({ direction }: { direction?: Direction }) => (virtualized ? this.renderVirtualizedBody(direction) : this.renderBody(direction))}
  734. </ConfigContext.Consumer>
  735. );
  736. }
  737. }
  738. export default React.forwardRef<HTMLDivElement, Omit<BodyProps, 'forwardedRef'>>(function TableBody(props, ref) {
  739. return <Body {...props} forwardedRef={ref} />;
  740. });
  741. export interface RenderExpandedRowProps {
  742. style?: React.CSSProperties;
  743. components?: TableComponents;
  744. renderExpandIcon: (record?: Record<string, any>, isNested?: boolean) => ReactNode | null;
  745. expandedRowRender?: ExpandedRowRender<Record<string, any>>;
  746. record?: Record<string, any>;
  747. columns?: ColumnProps[];
  748. expanded?: boolean;
  749. index?: number;
  750. rowKey?: RowKey<Record<string, any>>;
  751. virtualized?: Virtualized;
  752. level?: number;
  753. }
  754. export interface RenderSectionRowProps {
  755. dataSource?: Record<string, any>[];
  756. columns?: ColumnProps[];
  757. rowKey?: RowKey<Record<string, any>>;
  758. group?: any;
  759. groupKey: string | number;
  760. index?: number;
  761. expanded?: boolean;
  762. }