BaseRow.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import React, { createRef, ReactNode } from 'react';
  2. import classnames from 'classnames';
  3. import PropTypes from 'prop-types';
  4. import { each, noop, get, stubTrue, omit, isEqual, pick } from 'lodash';
  5. import { strings, cssClasses } from '@douyinfe/semi-foundation/table/constants';
  6. import shallowEqualObjects from '@douyinfe/semi-foundation/utils/shallowEqualObjects';
  7. import TableRowFoundation, { TableRowAdapter } from '@douyinfe/semi-foundation/table/tableRowFoundation';
  8. import {
  9. isLastLeftFixed,
  10. arrayAdd,
  11. isFixedLeft,
  12. isFixedRight,
  13. isScrollbarColumn,
  14. isFirstFixedRight,
  15. isInnerColumnKey,
  16. isExpandedColumn
  17. } from '@douyinfe/semi-foundation/table/utils';
  18. import Store from '@douyinfe/semi-foundation/utils/Store';
  19. import { BaseRowKeyType } from '@douyinfe/semi-foundation/table/foundation';
  20. import BaseComponent from '../../_base/baseComponent';
  21. import TableCell from '../TableCell';
  22. import { ColumnProps, Fixed, TableComponents, Virtualized, ExpandIcon, OnRow, RowExpandable } from '../interface';
  23. export interface BaseRowProps {
  24. anyColumnFixed?: boolean;
  25. cellWidths?: number[];
  26. className?: string;
  27. columns: ColumnProps[]; // required
  28. components?: TableComponents; // required
  29. disabled?: boolean;
  30. expandIcon?: ExpandIcon;
  31. expandableRow?: boolean;
  32. expanded?: boolean;
  33. expandedRow?: boolean;
  34. fixed?: Fixed;
  35. height?: string | number;
  36. hideExpandedColumn?: boolean;
  37. hovered: boolean; // required
  38. indent?: number;
  39. indentSize?: number;
  40. index?: number;
  41. isSection?: boolean;
  42. level?: number;
  43. onDidUpdate?: (ref: React.MutableRefObject<any>) => void;
  44. onHover?: (mouseEnter: boolean, rowKey: string | number) => void;
  45. onRow?: OnRow<any>;
  46. onRowClick?: (rowKey: BaseRowKeyType, e: React.MouseEvent, expand: boolean) => void;
  47. onRowDoubleClick?: (record: Record<string, any>, e: React.MouseEvent) => void;
  48. onRowMouseEnter?: (record: Record<string, any>, e: React.MouseEvent) => void;
  49. onRowMouseLeave?: (record: Record<string, any>, e: React.MouseEvent) => void;
  50. prefixCls?: string;
  51. record?: Record<string, any>;
  52. renderExpandIcon?: RenderExpandIcon;
  53. replaceClassName?: string;
  54. rowExpandable?: RowExpandable<any>;
  55. rowKey?: string | number; // required, this place rowKey is a real key of the row
  56. selected?: boolean;
  57. store?: Store;
  58. style?: React.CSSProperties;
  59. virtualized?: Virtualized;
  60. visible: boolean; // required
  61. /** whether display none */
  62. displayNone?: boolean
  63. }
  64. /**
  65. * avoid affected by https://www.npmjs.com/package/babel-plugin-transform-react-remove-prop-types
  66. */
  67. export const baseRowPropTypes = {
  68. anyColumnFixed: PropTypes.bool,
  69. cellWidths: PropTypes.array.isRequired,
  70. className: PropTypes.string,
  71. columns: PropTypes.array.isRequired,
  72. components: PropTypes.object.isRequired,
  73. disabled: PropTypes.bool,
  74. expandIcon: PropTypes.oneOfType([PropTypes.bool, PropTypes.func, PropTypes.node]),
  75. expandableRow: PropTypes.bool,
  76. expanded: PropTypes.bool,
  77. displayNone: PropTypes.bool,
  78. expandedRow: PropTypes.bool,
  79. fixed: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
  80. height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  81. hideExpandedColumn: PropTypes.bool,
  82. hovered: PropTypes.bool.isRequired,
  83. indent: PropTypes.number,
  84. indentSize: PropTypes.number,
  85. index: PropTypes.number,
  86. isSection: PropTypes.bool,
  87. level: PropTypes.number,
  88. onDidUpdate: PropTypes.func,
  89. onHover: PropTypes.func,
  90. onRow: PropTypes.func,
  91. onRowClick: PropTypes.func,
  92. onRowContextMenu: PropTypes.func,
  93. onRowDoubleClick: PropTypes.func,
  94. onRowMouseEnter: PropTypes.func,
  95. onRowMouseLeave: PropTypes.func,
  96. prefixCls: PropTypes.string,
  97. record: PropTypes.object,
  98. renderExpandIcon: PropTypes.func,
  99. replaceClassName: PropTypes.string,
  100. rowExpandable: PropTypes.func,
  101. rowKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, // real key of the row
  102. selected: PropTypes.bool,
  103. store: PropTypes.object,
  104. style: PropTypes.object,
  105. virtualized: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
  106. visible: PropTypes.bool.isRequired,
  107. };
  108. export default class TableRow extends BaseComponent<BaseRowProps, Record<string, any>> {
  109. static propTypes = baseRowPropTypes;
  110. static defaultProps = {
  111. columns: [] as [],
  112. rowExpandable: stubTrue,
  113. components: {
  114. body: {
  115. row: 'tr',
  116. cell: 'td',
  117. },
  118. },
  119. prefixCls: cssClasses.PREFIX,
  120. onRow: noop,
  121. onRowClick: noop,
  122. onRowDoubleClick: noop,
  123. onRowMouseEnter: noop,
  124. onRowMouseLeave: noop,
  125. onHover: noop,
  126. onDidUpdate: noop,
  127. visible: true,
  128. hovered: false,
  129. selected: false,
  130. disabled: false,
  131. };
  132. get adapter(): TableRowAdapter<BaseRowProps> {
  133. return {
  134. ...super.adapter,
  135. notifyClick: (...args) => this.props.onRowClick(...args),
  136. notifyDoubleClick: (...args) => this.props.onRowDoubleClick(...args),
  137. notifyMouseLeave: (...args) => {
  138. this.props.onHover(false, this.props.rowKey);
  139. this.props.onRowMouseEnter(...args);
  140. },
  141. notifyMouseEnter: (...args) => {
  142. this.props.onHover(true, this.props.rowKey);
  143. this.props.onRowMouseEnter(...args);
  144. },
  145. };
  146. }
  147. ref: React.MutableRefObject<any>;
  148. constructor(props: BaseRowProps) {
  149. super(props);
  150. this.ref = createRef();
  151. this.foundation = new TableRowFoundation(this.adapter);
  152. }
  153. componentDidMount() {
  154. // fix #745
  155. // didmount/willUnmount may be called twice when React.StrictMode is true in React 18, we need to ensure that this.cache.customRowProps is correct
  156. const {
  157. onRow,
  158. index,
  159. record,
  160. } = this.props;
  161. const customRowProps = this.adapter.getCache('customRowProps');
  162. if (typeof customRowProps === 'undefined') {
  163. const { className: customClassName, style: customStyle, ...rowProps } = onRow(record, index) || {};
  164. this.adapter.setCache('customRowProps', { ...rowProps });
  165. }
  166. }
  167. shouldComponentUpdate(nextProps: BaseRowProps) {
  168. /**
  169. * Shallow comparison of incoming props to simulate PureComponent
  170. * Deep comparison cellWidths
  171. *
  172. * 浅层对比传入的 props,模拟 PureComponent
  173. * 深比较 cellWidths
  174. */
  175. const omitProps = ['cellWidths'];
  176. const isPropsShallowEqual = shallowEqualObjects(omit(nextProps, omitProps), omit(this.props, omitProps));
  177. if (!isPropsShallowEqual || !isEqual(pick(nextProps, omitProps), pick(this.props, omitProps))) {
  178. return true;
  179. }
  180. return false;
  181. }
  182. _cacheNode = (node: any) => {
  183. this.ref.current = node;
  184. };
  185. // Pass true to render the tree-shaped expand button
  186. renderExpandIcon = (record: Record<string, any>) => {
  187. const { renderExpandIcon } = this.props;
  188. return renderExpandIcon(record, true);
  189. };
  190. renderCells() {
  191. const {
  192. columns,
  193. record,
  194. index,
  195. prefixCls,
  196. fixed,
  197. components,
  198. expandableRow,
  199. level,
  200. expandIcon,
  201. rowExpandable,
  202. isSection,
  203. expandedRow,
  204. virtualized,
  205. indentSize,
  206. hideExpandedColumn,
  207. cellWidths,
  208. selected,
  209. expanded,
  210. disabled,
  211. onDidUpdate,
  212. } = this.props;
  213. const BodyCell = get(components, 'body.cell', strings.DEFAULT_COMPONENTS.body.cell);
  214. const cells: ReactNode[] = [];
  215. const displayExpandedColumn = rowExpandable(record);
  216. let firstIndex = 0;
  217. // const dataColumns = getDataColumns(columns);
  218. each(columns, (column, columnIndex) => {
  219. const columnKey = get(column, 'key');
  220. const expandableProps: { renderExpandIcon?: (record: Record<string, any>) => ReactNode; expandIcon?: ExpandIcon; indent?: number } = {};
  221. if (fixed !== 'right') {
  222. if (isInnerColumnKey(columnKey)) {
  223. firstIndex++;
  224. }
  225. if (expandableRow && columnIndex === firstIndex) {
  226. expandableProps.renderExpandIcon = this.renderExpandIcon;
  227. if (hideExpandedColumn || isSection) {
  228. expandableProps.expandIcon = expandIcon != null ? expandIcon : true;
  229. }
  230. }
  231. // Only the first data row will be indented
  232. if (level != null && columnIndex === firstIndex) {
  233. expandableProps.indent = level;
  234. if (!expandableRow && hideExpandedColumn) {
  235. expandableProps.indent = level + 1;
  236. }
  237. }
  238. }
  239. if (isExpandedColumn(column) && !displayExpandedColumn) {
  240. cells.push(<TableCell key={columnIndex} colIndex={columnIndex} isSection={isSection} />);
  241. } else if (!isScrollbarColumn(column)) {
  242. const diyProps: { width?: number } = {};
  243. if (BodyCell !== strings.DEFAULT_COMPONENTS.body.cell && virtualized && !expandedRow) {
  244. diyProps.width = get(cellWidths, columnIndex);
  245. }
  246. cells.push(
  247. <TableCell
  248. colIndex={columnIndex}
  249. {...expandableProps}
  250. {...diyProps}
  251. hideExpandedColumn={hideExpandedColumn}
  252. indentSize={indentSize}
  253. isSection={isSection}
  254. prefixCls={`${prefixCls}`}
  255. column={column}
  256. key={columnIndex}
  257. index={index}
  258. record={record}
  259. component={BodyCell}
  260. fixedLeft={isFixedLeft(column) && arrayAdd(cellWidths, 0, columnIndex)}
  261. lastFixedLeft={isLastLeftFixed(columns, column)}
  262. fixedRight={isFixedRight(column) && arrayAdd(cellWidths, columnIndex + 1)}
  263. firstFixedRight={isFirstFixedRight(columns, column)}
  264. selected={selected}
  265. expanded={expanded}
  266. disabled={disabled}
  267. onDidUpdate={onDidUpdate}
  268. />
  269. );
  270. }
  271. });
  272. return cells;
  273. }
  274. handleMouseEnter = (e: React.MouseEvent) => {
  275. this.foundation.handleMouseEnter(e);
  276. const customRowProps = this.adapter.getCache('customRowProps');
  277. if (typeof customRowProps?.onMouseEnter === 'function') {
  278. customRowProps.onMouseEnter(e);
  279. }
  280. };
  281. handleMouseLeave = (e: React.MouseEvent) => {
  282. this.foundation.handleMouseLeave(e);
  283. const customRowProps = this.adapter.getCache('customRowProps');
  284. if (typeof customRowProps?.onMouseLeave === 'function') {
  285. customRowProps.onMouseLeave(e);
  286. }
  287. };
  288. handleClick = (e: React.MouseEvent) => {
  289. this.foundation.handleClick(e);
  290. const customRowProps = this.adapter.getCache('customRowProps');
  291. if (customRowProps && typeof customRowProps.onClick === 'function') {
  292. customRowProps.onClick(e);
  293. }
  294. };
  295. render() {
  296. const { style } = this.props;
  297. const {
  298. components,
  299. prefixCls,
  300. selected,
  301. onRow,
  302. index,
  303. className,
  304. replaceClassName,
  305. record,
  306. hovered,
  307. expanded,
  308. displayNone,
  309. expandableRow,
  310. level,
  311. expandedRow,
  312. isSection
  313. } = this.props;
  314. const BodyRow: any = components.body.row;
  315. const { className: customClassName, style: customStyle, ...rowProps } = onRow(record, index) || {};
  316. this.adapter.setCache('customRowProps', { ...rowProps });
  317. const baseRowStyle = { ...style, ...customStyle };
  318. const rowCls =
  319. typeof replaceClassName === 'string' && replaceClassName.length ?
  320. replaceClassName :
  321. classnames(
  322. className,
  323. `${prefixCls}-row`,
  324. {
  325. [`${prefixCls}-row-selected`]: selected,
  326. [`${prefixCls}-row-expanded`]: expanded,
  327. [`${prefixCls}-row-hovered`]: hovered,
  328. [`${prefixCls}-row-hidden`]: displayNone,
  329. },
  330. customClassName
  331. );
  332. const ariaProps = {};
  333. if (typeof index === 'number') {
  334. ariaProps['aria-rowindex'] = index + 1;
  335. }
  336. if (expandableRow) {
  337. ariaProps['aria-expanded'] = expanded;
  338. }
  339. // if row is expandedRow, set it's level to 2
  340. if (expanded || expandedRow) {
  341. ariaProps['aria-level'] = 2;
  342. }
  343. if (typeof level === 'number') {
  344. ariaProps['aria-level'] = level + 1;
  345. }
  346. if (isSection) {
  347. ariaProps['aria-level'] = 1;
  348. }
  349. return (
  350. <BodyRow
  351. role="row"
  352. {...ariaProps}
  353. {...rowProps}
  354. style={baseRowStyle}
  355. className={rowCls}
  356. ref={this._cacheNode}
  357. onMouseEnter={this.handleMouseEnter}
  358. onMouseLeave={this.handleMouseLeave}
  359. onClick={this.handleClick}
  360. >
  361. {this.renderCells()}
  362. </BodyRow>
  363. );
  364. }
  365. }
  366. export type RenderExpandIcon = (record: Record<string, any>, isNested: boolean) => ReactNode | null;