index.tsx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. import React, { ReactNode } from 'react';
  2. import PropTypes from 'prop-types';
  3. import { get, size, isMap, each, isEqual, pick, isNull, isFunction } from 'lodash';
  4. import classnames from 'classnames';
  5. import { VariableSizeList as List } from 'react-window';
  6. import {
  7. arrayAdd,
  8. getRecordKey,
  9. isExpanded,
  10. isSelected,
  11. isDisabled,
  12. getRecord,
  13. genExpandedRowKey,
  14. getDefaultVirtualizedRowConfig,
  15. isTreeTable
  16. } from '@douyinfe/semi-foundation/table/utils';
  17. import BodyFoundation, { BodyAdapter, FlattenData, GroupFlattenData } from '@douyinfe/semi-foundation/table/bodyFoundation';
  18. import { strings } from '@douyinfe/semi-foundation/table/constants';
  19. import Store from '@douyinfe/semi-foundation/utils/Store';
  20. import BaseComponent, { BaseProps } from '../../_base/baseComponent';
  21. import { logger } from '../utils';
  22. import ColGroup from '../ColGroup';
  23. import BaseRow, { baseRowPropTypes } from './BaseRow';
  24. import ExpandedRow from './ExpandedRow';
  25. import SectionRow, { sectionRowPropTypes } from './SectionRow';
  26. import TableHeader from '../TableHeader';
  27. import ConfigContext from '../../configProvider/context';
  28. import TableContext, { TableContextProps } from '../table-context';
  29. import type {
  30. ExpandedRowRender,
  31. Virtualized,
  32. VirtualizedItemSize,
  33. GetVirtualizedListRef,
  34. ColumnProps,
  35. Size,
  36. BodyScrollEvent,
  37. Scroll,
  38. Fixed,
  39. TableComponents,
  40. RowExpandable,
  41. VirtualizedOnScroll,
  42. Direction,
  43. RowKey
  44. } from '../interface';
  45. export interface BodyProps extends BaseProps {
  46. tableLayout?: 'fixed' | 'auto';
  47. anyColumnFixed?: boolean;
  48. columns?: ColumnProps[];
  49. dataSource?: Record<string, any>[];
  50. disabledRowKeysSet: Set<any>; // required
  51. emptySlot?: ReactNode;
  52. expandedRowKeys?: (string | number)[];
  53. expandedRowRender?: ExpandedRowRender<Record<string, any>>;
  54. fixed?: Fixed;
  55. forwardedRef?: React.MutableRefObject<HTMLDivElement> | ((instance: any) => void);
  56. handleBodyScroll?: (e: BodyScrollEvent) => void;
  57. handleWheel?: (e: React.WheelEvent<HTMLDivElement>) => void;
  58. includeHeader?: boolean;
  59. prefixCls?: string;
  60. scroll?: Scroll;
  61. selectedRowKeysSet: Set<any>; // required
  62. showHeader?: boolean;
  63. size?: Size;
  64. virtualized?: Virtualized;
  65. components?: TableComponents;
  66. store: Store;
  67. groups?: Map<string, Record<string, any>[]>[];
  68. rowKey?: RowKey<Record<string, any>>;
  69. childrenRecordName?: string;
  70. rowExpandable?: RowExpandable<Record<string, any>>;
  71. renderExpandIcon: (record: Record<string, any>, isNested: boolean) => ReactNode | null;
  72. headerRef?: React.MutableRefObject<HTMLDivElement> | ((instance: any) => void);
  73. onScroll?: VirtualizedOnScroll;
  74. keepDOM?: boolean
  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/en-US/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) as VirtualizedItemSize;
  239. let realSize = itemSize as number;
  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: undefined | ((props?: any) => void) = 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. const { key, parentKeys, expandedRow, sectionRow, ...rest } = virtualizedItem;
  291. const rowWidth = this.getVirtualizedRowWidth();
  292. const expandBtnShouldInRow = cachedExpandBtnShouldInRow;
  293. const props = {
  294. ...this.props,
  295. style: {
  296. ...style,
  297. width: rowWidth,
  298. },
  299. ...rest,
  300. columns: flattenedColumns,
  301. index,
  302. expandBtnShouldInRow,
  303. };
  304. return sectionRow ?
  305. this.renderSectionRow(props) :
  306. expandedRow ?
  307. this.renderExpandedRow(props) :
  308. this.renderBaseRow(props);
  309. };
  310. // virtualized List innerElementType
  311. renderTbody = React.forwardRef<HTMLDivElement, any>((props: any = {}, ref: React.MutableRefObject<HTMLDivElement> | ((instance: HTMLDivElement) => void)) => (
  312. <div
  313. {...props}
  314. onScroll={(...args) => {
  315. if (props.onScroll) {
  316. props.onScroll(...args);
  317. }
  318. }}
  319. // eslint-disable-next-line react/no-this-in-sfc,react/destructuring-assignment
  320. className={classnames(props.className, `${this.props.prefixCls}-tbody`)}
  321. style={{ ...props.style }}
  322. ref={ref}
  323. />
  324. ));
  325. // virtualized List outerElementType
  326. renderOuter = React.forwardRef<HTMLDivElement, any>((props: any, ref: React.MutableRefObject<HTMLDivElement> | ((instance: HTMLDivElement) => void)) => {
  327. const { children, ...rest } = props;
  328. const { handleWheel, prefixCls, emptySlot, dataSource } = this.props;
  329. const tableWidth = this.getVirtualizedRowWidth();
  330. const tableCls = classnames(`${prefixCls}`, `${prefixCls}-fixed`);
  331. return (
  332. <div
  333. {...rest}
  334. ref={ref}
  335. onWheel={(...args) => {
  336. if (handleWheel) {
  337. handleWheel(...args);
  338. }
  339. if (rest.onWheel) {
  340. rest.onWheel(...args);
  341. }
  342. }}
  343. onScroll={(...args) => {
  344. this.handleVirtualizedBodyScroll(...args);
  345. if (rest.onScroll) {
  346. rest.onScroll(...args);
  347. }
  348. }}
  349. >
  350. <div style={{ width: tableWidth }} className={tableCls}>
  351. {children}
  352. </div>
  353. {size(dataSource) === 0 && emptySlot}
  354. </div>
  355. );
  356. });
  357. onItemsRendered = (props: { overscanStartIndex: number; overscanStopIndex: number; visibleStartIndex: number; visibleStopIndex: number }) => {
  358. if (this.state.cache.virtualizedScrollLeft && this.ref.current) {
  359. this.ref.current.scrollLeft = this.state.cache.virtualizedScrollLeft;
  360. }
  361. };
  362. renderVirtualizedBody = (direction?: Direction) => {
  363. const { scroll, prefixCls, virtualized, columns } = this.props;
  364. const { virtualizedData } = this.state;
  365. const { getCellWidths } = this.context;
  366. const cellWidths = getCellWidths(columns);
  367. if (!size(cellWidths)) {
  368. return null;
  369. }
  370. const rawY = get(scroll, 'y');
  371. const yIsNumber = typeof rawY === 'number';
  372. const y = yIsNumber ? rawY : 600;
  373. if (!yIsNumber) {
  374. logger.warn('You have to specific "scroll.y" which must be a number for table virtualization!');
  375. }
  376. const listStyle = {
  377. width: '100%',
  378. height: virtualizedData?.length ? y : null,
  379. overflowX: 'auto',
  380. overflowY: 'auto',
  381. } as const;
  382. const wrapCls = classnames(`${prefixCls}-body`);
  383. return (
  384. <List<Array<FlattenData | GroupFlattenData>>
  385. {...(typeof virtualized === 'object' ? virtualized : {})}
  386. initialScrollOffset={this.state.cache.virtualizedScrollTop}
  387. onScroll={this.handleVirtualizedScroll}
  388. onItemsRendered={this.onItemsRendered}
  389. ref={this.listRef}
  390. className={wrapCls}
  391. outerRef={this.forwardRef}
  392. height={virtualizedData?.length ? y : 0}
  393. width={listStyle.width}
  394. itemData={virtualizedData}
  395. itemSize={this.itemSize}
  396. itemCount={virtualizedData.length}
  397. itemKey={this.itemKey}
  398. innerElementType={this.renderTbody}
  399. outerElementType={this.renderOuter}
  400. style={{ ...listStyle, direction }}
  401. direction={direction}
  402. >
  403. {this.renderVirtualizedRow}
  404. </List>
  405. );
  406. };
  407. /**
  408. * render group title
  409. * @param {*} props
  410. */
  411. renderSectionRow = (props: RenderSectionRowProps = { groupKey: undefined }) => {
  412. const { dataSource, rowKey, group, groupKey, index } = props;
  413. const sectionRowPickKeys = Object.keys(sectionRowPropTypes);
  414. const sectionRowProps: any = pick(props, sectionRowPickKeys);
  415. const { handleRowExpanded } = this.context;
  416. return (
  417. <SectionRow
  418. {...sectionRowProps}
  419. record={{
  420. groupKey,
  421. records: [...group].map(recordKey => getRecord(dataSource, recordKey, rowKey)),
  422. }}
  423. index={index}
  424. onExpand={handleRowExpanded}
  425. data={dataSource}
  426. key={groupKey || index}
  427. />
  428. );
  429. };
  430. renderExpandedRow = (props: RenderExpandedRowProps = { renderExpandIcon: () => null }) => {
  431. const {
  432. style,
  433. components,
  434. renderExpandIcon,
  435. expandedRowRender,
  436. record,
  437. columns,
  438. expanded,
  439. index,
  440. rowKey,
  441. virtualized,
  442. displayNone
  443. } = props;
  444. let key = getRecordKey(record, rowKey);
  445. if (key == null) {
  446. key = index;
  447. }
  448. const { flattenedColumns, getCellWidths } = this.context;
  449. // we use memoized cellWidths to avoid re-render expanded row (fix #686)
  450. if (flattenedColumns !== this.flattenedColumns) {
  451. this.flattenedColumns = flattenedColumns;
  452. this.cellWidths = getCellWidths(flattenedColumns);
  453. }
  454. return (
  455. <ExpandedRow
  456. style={style}
  457. components={components}
  458. renderExpandIcon={renderExpandIcon}
  459. expandedRowRender={expandedRowRender}
  460. record={record}
  461. columns={columns}
  462. expanded={expanded}
  463. index={index}
  464. virtualized={virtualized}
  465. key={genExpandedRowKey(key)}
  466. cellWidths={this.cellWidths}
  467. displayNone={displayNone}
  468. />
  469. );
  470. };
  471. /**
  472. * render base row
  473. * @param {*} props
  474. * @returns
  475. */
  476. renderBaseRow(props: any = {}) {
  477. const {
  478. rowKey,
  479. columns,
  480. expandedRowKeys,
  481. rowExpandable,
  482. record,
  483. index,
  484. level,
  485. expandBtnShouldInRow, // effect the display of the indent span
  486. selectedRowKeysSet,
  487. disabledRowKeysSet,
  488. expandRowByClick,
  489. } = props;
  490. const baseRowPickKeys = Object.keys(baseRowPropTypes);
  491. const baseRowProps: Record<string, any> = pick(props, baseRowPickKeys);
  492. let key = getRecordKey(record, rowKey);
  493. if (key == null) {
  494. key = index;
  495. }
  496. const expanded = isExpanded(expandedRowKeys, key);
  497. const expandable = rowExpandable && rowExpandable(record);
  498. const expandableProps: {
  499. level?: number;
  500. expanded?: boolean;
  501. expandableRow?: boolean;
  502. onRowClick?: (...args: any[]) => void
  503. } = {
  504. level: undefined,
  505. expanded,
  506. };
  507. if (expandable || expandBtnShouldInRow) {
  508. expandableProps.level = level;
  509. expandableProps.expandableRow = expandable;
  510. if (expandRowByClick) {
  511. expandableProps.onRowClick = this.handleRowClick;
  512. }
  513. }
  514. const selectionProps = {
  515. selected: isSelected(selectedRowKeysSet, key),
  516. disabled: isDisabled(disabledRowKeysSet, key),
  517. };
  518. const { getCellWidths } = this.context;
  519. const cellWidths = getCellWidths(columns, null, true);
  520. return (
  521. <BaseRow
  522. {...baseRowProps}
  523. {...expandableProps}
  524. {...selectionProps}
  525. key={key}
  526. rowKey={key}
  527. cellWidths={cellWidths}
  528. />
  529. );
  530. }
  531. /**
  532. * render grouped rows
  533. * @returns {ReactNode[]} renderedRows
  534. */
  535. renderGroupedRows = () => {
  536. const { groups, dataSource: data, rowKey, expandedRowKeys, keepDOM } = this.props;
  537. const { flattenedColumns } = this.context;
  538. const groupsInData = new Map();
  539. const renderedRows: ReactNode[] = [];
  540. if (groups != null && Array.isArray(data) && data.length) {
  541. data.forEach(record => {
  542. const recordKey = getRecordKey(record, rowKey);
  543. groups.forEach((group: Map<string, Record<string, any>[]>, key: number) => {
  544. if (group.has(recordKey)) {
  545. if (!groupsInData.has(key)) {
  546. groupsInData.set(key, new Set([]));
  547. }
  548. groupsInData.get(key).add(recordKey);
  549. return false;
  550. }
  551. return undefined;
  552. });
  553. });
  554. }
  555. let index = -1;
  556. groupsInData.forEach((group, groupKey) => {
  557. // Calculate the expanded state of the group
  558. const expanded = isExpanded(expandedRowKeys, groupKey);
  559. // Render the title of the group
  560. renderedRows.push(
  561. this.renderSectionRow({
  562. ...this.props,
  563. columns: flattenedColumns,
  564. index: ++index,
  565. group,
  566. groupKey,
  567. expanded,
  568. })
  569. );
  570. // Render the grouped content when the group is expanded
  571. if (expanded || keepDOM) {
  572. const dataInGroup: any[] = [];
  573. group.forEach((recordKey: string) => {
  574. const record = getRecord(data, recordKey, rowKey);
  575. if (record != null) {
  576. dataInGroup.push(record);
  577. }
  578. });
  579. /**
  580. * Render the contents of the group row
  581. */
  582. renderedRows.push(this.renderBodyRows(dataInGroup, undefined, [], !expanded));
  583. }
  584. });
  585. return renderedRows;
  586. };
  587. renderBodyRows(data: Record<string, any>[] = [], level = 0, renderedRows: ReactNode[] = [], displayNone = false) {
  588. const {
  589. rowKey,
  590. expandedRowRender,
  591. expandedRowKeys,
  592. childrenRecordName,
  593. rowExpandable,
  594. keepDOM
  595. } = this.props;
  596. const hasExpandedRowRender = typeof expandedRowRender === 'function';
  597. const expandBtnShouldInRow = this.state.cachedExpandBtnShouldInRow;
  598. const { flattenedColumns } = this.context;
  599. each(data, (record, index) => {
  600. let key = getRecordKey(record, rowKey);
  601. if (key == null) {
  602. key = index;
  603. }
  604. const recordChildren = get(record, childrenRecordName);
  605. const recordHasChildren = Boolean(Array.isArray(recordChildren) && recordChildren.length);
  606. renderedRows.push(
  607. this.renderBaseRow({
  608. ...this.props,
  609. columns: flattenedColumns,
  610. expandBtnShouldInRow,
  611. displayNone,
  612. record,
  613. key,
  614. level,
  615. index,
  616. })
  617. );
  618. // render expand row
  619. const expanded = isExpanded(expandedRowKeys, key);
  620. const shouldRenderExpandedRows = expanded || keepDOM;
  621. if (hasExpandedRowRender && rowExpandable && rowExpandable(record) && shouldRenderExpandedRows) {
  622. const currentExpandRow = this.renderExpandedRow({
  623. ...this.props,
  624. columns: flattenedColumns,
  625. level,
  626. index,
  627. record,
  628. expanded,
  629. displayNone: displayNone || !expanded,
  630. });
  631. /**
  632. * If expandedRowRender returns falsy, this expanded row will not be rendered
  633. * Render an empty div before v1.19.7
  634. */
  635. if (!isNull(currentExpandRow)) {
  636. renderedRows.push(currentExpandRow);
  637. }
  638. }
  639. // render tree data
  640. if (recordHasChildren && shouldRenderExpandedRows) {
  641. const nestedRows = this.renderBodyRows(recordChildren, level + 1, [], displayNone || !expanded);
  642. renderedRows.push(...nestedRows);
  643. }
  644. });
  645. return renderedRows;
  646. }
  647. renderBody = (direction?: Direction) => {
  648. const {
  649. scroll,
  650. prefixCls,
  651. columns,
  652. components,
  653. fixed,
  654. handleWheel,
  655. headerRef,
  656. handleBodyScroll,
  657. anyColumnFixed,
  658. showHeader,
  659. emptySlot,
  660. includeHeader,
  661. dataSource,
  662. onScroll,
  663. groups,
  664. expandedRowRender,
  665. tableLayout,
  666. } = this.props;
  667. const x = get(scroll, 'x');
  668. const y = get(scroll, 'y');
  669. const bodyStyle: {
  670. maxHeight?: string | number;
  671. overflow?: string;
  672. WebkitTransform?: string
  673. } = {};
  674. const tableStyle: {
  675. width?: string | number
  676. } = {};
  677. const Table = get(components, 'body.outer', 'table') as unknown as typeof React.Component;
  678. const BodyWrapper = (get(components, 'body.wrapper') || 'tbody') as unknown as typeof React.Component;
  679. if (y) {
  680. bodyStyle.maxHeight = y;
  681. }
  682. if (x) {
  683. tableStyle.width = x;
  684. }
  685. if (anyColumnFixed && size(dataSource)) {
  686. // Auto is better than scroll. For example, when there is only scrollY, the scroll axis is not displayed horizontally.
  687. bodyStyle.overflow = 'auto';
  688. // Fix weird webkit render bug
  689. bodyStyle.WebkitTransform = 'translate3d (0, 0, 0)';
  690. }
  691. const colgroup = <ColGroup components={get(components, 'body')} columns={columns} prefixCls={prefixCls} />;
  692. // const tableBody = this.renderBody();
  693. const wrapCls = `${prefixCls}-body`;
  694. const baseTable = (
  695. <div
  696. key="bodyTable"
  697. className={wrapCls}
  698. style={bodyStyle}
  699. ref={this.forwardRef}
  700. onWheel={handleWheel}
  701. onScroll={handleBodyScroll}
  702. >
  703. <Table
  704. role={isMap(groups) || isFunction(expandedRowRender) || isTreeTable({ dataSource }) ? 'treegrid' : 'grid'}
  705. aria-rowcount={dataSource && dataSource.length}
  706. aria-colcount={columns && columns.length}
  707. style={tableStyle}
  708. className={classnames(prefixCls, {
  709. [`${prefixCls}-fixed`]: tableLayout === 'fixed',
  710. })}
  711. >
  712. {colgroup}
  713. {includeHeader && showHeader ? (
  714. <TableHeader {...this.props} ref={headerRef} components={components} columns={columns} />
  715. ) : null}
  716. <BodyWrapper className={`${prefixCls}-tbody`} onScroll={onScroll}>
  717. {isMap(groups) ? this.renderGroupedRows() : this.renderBodyRows(dataSource)}
  718. </BodyWrapper>
  719. </Table>
  720. {emptySlot}
  721. </div>
  722. );
  723. if (fixed && columns.length) {
  724. return (
  725. <div key="bodyTable" className={`${prefixCls}-body-outer`}>
  726. {baseTable}
  727. </div>
  728. );
  729. }
  730. return baseTable;
  731. };
  732. render() {
  733. const { virtualized } = this.props;
  734. const { direction } = this.context;
  735. return virtualized ? this.renderVirtualizedBody(direction) : this.renderBody(direction);
  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. keepDOM?: boolean;
  754. displayNone?: boolean
  755. }
  756. export interface RenderSectionRowProps {
  757. dataSource?: Record<string, any>[];
  758. columns?: ColumnProps[];
  759. rowKey?: RowKey<Record<string, any>>;
  760. group?: any;
  761. groupKey: string | number;
  762. index?: number;
  763. expanded?: boolean
  764. }