BaseRow.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. constructor(props: BaseRowProps) {
  148. super(props);
  149. this.foundation = new TableRowFoundation(this.adapter);
  150. }
  151. componentDidMount() {
  152. // fix #745
  153. // didmount/willUnmount may be called twice when React.StrictMode is true in React 18, we need to ensure that this.cache.customRowProps is correct
  154. const {
  155. onRow,
  156. index,
  157. record,
  158. } = this.props;
  159. const customRowProps = this.adapter.getCache('customRowProps');
  160. if (typeof customRowProps === 'undefined') {
  161. const { className: customClassName, style: customStyle, ...rowProps } = onRow(record, index) || {};
  162. this.adapter.setCache('customRowProps', { ...rowProps });
  163. }
  164. }
  165. shouldComponentUpdate(nextProps: BaseRowProps) {
  166. /**
  167. * Shallow comparison of incoming props to simulate PureComponent
  168. * Deep comparison cellWidths
  169. *
  170. * 浅层对比传入的 props,模拟 PureComponent
  171. * 深比较 cellWidths
  172. */
  173. const omitProps = ['cellWidths'];
  174. const isPropsShallowEqual = shallowEqualObjects(omit(nextProps, omitProps), omit(this.props, omitProps));
  175. if (!isPropsShallowEqual || !isEqual(pick(nextProps, omitProps), pick(this.props, omitProps))) {
  176. return true;
  177. }
  178. return false;
  179. }
  180. // Pass true to render the tree-shaped expand button
  181. renderExpandIcon = (record: Record<string, any>) => {
  182. const { renderExpandIcon } = this.props;
  183. return renderExpandIcon(record, true);
  184. };
  185. renderCells() {
  186. const {
  187. columns,
  188. record,
  189. index,
  190. prefixCls,
  191. fixed,
  192. components,
  193. expandableRow,
  194. level,
  195. expandIcon,
  196. rowExpandable,
  197. isSection,
  198. expandedRow,
  199. virtualized,
  200. indentSize,
  201. hideExpandedColumn,
  202. cellWidths,
  203. selected,
  204. expanded,
  205. disabled,
  206. onDidUpdate,
  207. } = this.props;
  208. const BodyCell = get(components, 'body.cell', strings.DEFAULT_COMPONENTS.body.cell);
  209. const cells: ReactNode[] = [];
  210. const displayExpandedColumn = rowExpandable(record);
  211. let firstIndex = 0;
  212. // const dataColumns = getDataColumns(columns);
  213. each(columns, (column, columnIndex) => {
  214. const columnKey = get(column, 'key');
  215. const expandableProps: { renderExpandIcon?: (record: Record<string, any>) => ReactNode; expandIcon?: ExpandIcon; indent?: number } = {};
  216. if (fixed !== 'right') {
  217. if (isInnerColumnKey(columnKey)) {
  218. firstIndex++;
  219. }
  220. if (expandableRow && columnIndex === firstIndex) {
  221. expandableProps.renderExpandIcon = this.renderExpandIcon;
  222. if (hideExpandedColumn || isSection) {
  223. expandableProps.expandIcon = expandIcon != null ? expandIcon : true;
  224. }
  225. }
  226. // Only the first data row will be indented
  227. if (level != null && columnIndex === firstIndex) {
  228. expandableProps.indent = level;
  229. const isBool = typeof expandIcon === 'boolean';
  230. const hasExpandIcon = expandIcon !== false || !isBool && expandIcon !== null;
  231. // 如果 expandIcon 为空,不需要 indent
  232. if (!expandableRow && hideExpandedColumn && hasExpandIcon) {
  233. expandableProps.indent = level + 1;
  234. }
  235. }
  236. }
  237. if (isExpandedColumn(column) && !displayExpandedColumn) {
  238. cells.push(<TableCell key={columnIndex} colIndex={columnIndex} isSection={isSection} />);
  239. } else if (!isScrollbarColumn(column)) {
  240. const diyProps: { width?: number } = {};
  241. if (BodyCell !== strings.DEFAULT_COMPONENTS.body.cell && virtualized && !expandedRow) {
  242. diyProps.width = get(cellWidths, columnIndex);
  243. }
  244. cells.push(
  245. <TableCell
  246. colIndex={columnIndex}
  247. {...expandableProps}
  248. {...diyProps}
  249. hideExpandedColumn={hideExpandedColumn}
  250. indentSize={indentSize}
  251. isSection={isSection}
  252. prefixCls={`${prefixCls}`}
  253. column={column}
  254. key={columnIndex}
  255. index={index}
  256. record={record}
  257. component={BodyCell}
  258. fixedLeft={isFixedLeft(column) && arrayAdd(cellWidths, 0, columnIndex)}
  259. lastFixedLeft={isLastLeftFixed(columns, column)}
  260. fixedRight={isFixedRight(column) && arrayAdd(cellWidths, columnIndex + 1)}
  261. firstFixedRight={isFirstFixedRight(columns, column)}
  262. selected={selected}
  263. expanded={expanded}
  264. disabled={disabled}
  265. onDidUpdate={onDidUpdate}
  266. />
  267. );
  268. }
  269. });
  270. return cells;
  271. }
  272. handleMouseEnter = (e: React.MouseEvent) => {
  273. this.foundation.handleMouseEnter(e);
  274. const customRowProps = this.adapter.getCache('customRowProps');
  275. if (typeof customRowProps?.onMouseEnter === 'function') {
  276. customRowProps.onMouseEnter(e);
  277. }
  278. };
  279. handleMouseLeave = (e: React.MouseEvent) => {
  280. this.foundation.handleMouseLeave(e);
  281. const customRowProps = this.adapter.getCache('customRowProps');
  282. if (typeof customRowProps?.onMouseLeave === 'function') {
  283. customRowProps.onMouseLeave(e);
  284. }
  285. };
  286. handleClick = (e: React.MouseEvent) => {
  287. this.foundation.handleClick(e);
  288. const customRowProps = this.adapter.getCache('customRowProps');
  289. if (customRowProps && typeof customRowProps.onClick === 'function') {
  290. customRowProps.onClick(e);
  291. }
  292. };
  293. render() {
  294. const { style } = this.props;
  295. const {
  296. components,
  297. prefixCls,
  298. selected,
  299. onRow,
  300. index,
  301. className,
  302. replaceClassName,
  303. record,
  304. hovered,
  305. expanded,
  306. displayNone,
  307. expandableRow,
  308. level,
  309. expandedRow,
  310. isSection,
  311. rowKey
  312. } = this.props;
  313. const BodyRow = components.body.row;
  314. const { className: customClassName, style: customStyle, ...rowProps } = onRow(record, index) || {};
  315. this.adapter.setCache('customRowProps', { ...rowProps });
  316. const baseRowStyle = { ...style, ...customStyle };
  317. const rowCls =
  318. typeof replaceClassName === 'string' && replaceClassName.length
  319. ? classnames(replaceClassName, customClassName)
  320. : classnames(
  321. className,
  322. `${prefixCls}-row`,
  323. {
  324. [`${prefixCls}-row-selected`]: selected,
  325. [`${prefixCls}-row-expanded`]: expanded,
  326. [`${prefixCls}-row-hovered`]: hovered,
  327. [`${prefixCls}-row-hidden`]: displayNone,
  328. },
  329. customClassName
  330. );
  331. const ariaProps = {};
  332. if (typeof index === 'number') {
  333. ariaProps['aria-rowindex'] = index + 1;
  334. }
  335. if (expandableRow) {
  336. ariaProps['aria-expanded'] = expanded;
  337. }
  338. // if row is expandedRow, set it's level to 2
  339. if (expanded || expandedRow) {
  340. ariaProps['aria-level'] = 2;
  341. }
  342. if (typeof level === 'number') {
  343. ariaProps['aria-level'] = level + 1;
  344. }
  345. if (isSection) {
  346. ariaProps['aria-level'] = 1;
  347. }
  348. return (
  349. <BodyRow
  350. role="row"
  351. {...ariaProps}
  352. {...rowProps}
  353. style={baseRowStyle}
  354. className={rowCls}
  355. // used for dnd-kit sortable
  356. data-row-key={rowKey}
  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;