TableCell.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. /* eslint-disable prefer-destructuring */
  2. /* eslint-disable eqeqeq */
  3. import React, { createRef, Fragment, ReactNode } from 'react';
  4. import classnames from 'classnames';
  5. import PropTypes from 'prop-types';
  6. import { get, noop, set, omit, isEqual, merge } from 'lodash-es';
  7. import { cssClasses, numbers } from '@douyinfe/semi-foundation/table/constants';
  8. import TableCellFoundation, { TableCellAdapter } from '@douyinfe/semi-foundation/table/cellFoundation';
  9. import { isSelectionColumn, isExpandedColumn } from '@douyinfe/semi-foundation/table/utils';
  10. import BaseComponent, { BaseProps } from '../_base/baseComponent';
  11. import Context from './table-context';
  12. import { amendTableWidth } from './utils';
  13. import { Align, ColumnProps } from './interface';
  14. export interface TableCellProps extends BaseProps {
  15. record?: Record<string, any>;
  16. prefixCls?: string;
  17. index?: number; // index of dataSource
  18. fixedLeft?: boolean | number;
  19. lastFixedLeft?: boolean;
  20. fixedRight?: boolean | number;
  21. firstFixedRight?: boolean;
  22. indent?: number; // The level of the tree structure
  23. indentSize?: number; // Tree structure indent size
  24. column?: ColumnProps; // The column of the current cell
  25. /**
  26. * Does the first column include expandIcon
  27. * When hideExpandedColumn is true or isSection is true
  28. * expandIcon is a custom icon or true
  29. */
  30. expandIcon?: ReactNode | boolean;
  31. renderExpandIcon?: (record: Record<string, any>) => ReactNode;
  32. hideExpandedColumn?: boolean;
  33. component?: any;
  34. onClick?: (record: Record<string, any>, e: React.MouseEvent) => void; // callback of click cell event
  35. onDidUpdate?: (ref: React.MutableRefObject<any>) => void;
  36. isSection?: boolean; // Whether it is in group row
  37. width?: string | number; // cell width
  38. height?: string | number; // cell height
  39. selected?: boolean; // Whether the current row is selected
  40. expanded?: boolean; // Whether the current line is expanded
  41. disabled?: boolean;
  42. }
  43. function isInvalidRenderCellText(text: any) {
  44. return text && !React.isValidElement(text) && Object.prototype.toString.call(text) === '[object Object]';
  45. }
  46. export default class TableCell extends BaseComponent<TableCellProps, Record<string, any>> {
  47. static contextType = Context;
  48. static defaultProps = {
  49. indent: 0,
  50. indentSize: numbers.DEFAULT_INDENT_WIDTH,
  51. onClick: noop,
  52. prefixCls: cssClasses.PREFIX,
  53. component: 'td',
  54. onDidUpdate: noop,
  55. column: {},
  56. };
  57. static propTypes = {
  58. record: PropTypes.object,
  59. prefixCls: PropTypes.string,
  60. index: PropTypes.number,
  61. fixedLeft: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
  62. lastFixedLeft: PropTypes.bool,
  63. fixedRight: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
  64. firstFixedRight: PropTypes.bool,
  65. indent: PropTypes.number,
  66. indentSize: PropTypes.number,
  67. column: PropTypes.object,
  68. expandIcon: PropTypes.any,
  69. renderExpandIcon: PropTypes.func,
  70. hideExpandedColumn: PropTypes.bool,
  71. component: PropTypes.any,
  72. onClick: PropTypes.func,
  73. onDidUpdate: PropTypes.func,
  74. isSection: PropTypes.bool,
  75. width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  76. height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  77. selected: PropTypes.bool,
  78. expanded: PropTypes.bool,
  79. };
  80. get adapter(): TableCellAdapter {
  81. return {
  82. ...super.adapter,
  83. notifyClick: (...args) => {
  84. const { onClick } = this.props;
  85. if (typeof onClick === 'function') {
  86. onClick(...args);
  87. }
  88. },
  89. };
  90. }
  91. ref: React.MutableRefObject<any>;
  92. constructor(props: TableCellProps) {
  93. super(props);
  94. this.ref = createRef();
  95. this.foundation = new TableCellFoundation(this.adapter);
  96. }
  97. /**
  98. * Control whether to execute the render function of the cell
  99. * 1. Scenes that return true
  100. * - The cell contains the selection state, you need to calculate whether its selection state has changed during selection
  101. * - The cell contains the folding state, it needs to be calculated when the folding state has changed
  102. * 2. Scenarios that return false
  103. * - Cells without table operation operation status, only need to judge that their props have changed
  104. * At this time, the update of the table cell is controlled by the user. At this time, its update will not affect other cells
  105. *
  106. * 控制是否执行cell的render函数
  107. * 1. 返回true的场景
  108. * - cell内包含选择状态,需要在选择时计算它的选择态是否发生变化
  109. * - cell内包含折叠状态,需要在折叠时计算它的折叠态是否发生了变化
  110. * 2. 返回false的场景
  111. * - 没有table操作操作状态的cell,只需判断自己的props发生了变化
  112. * 此时table cell的更新由用户自己控制,此时它的更新不会影响其他cell
  113. *
  114. * @param {*} nextProps
  115. * @returns
  116. */
  117. shouldComponentUpdate(nextProps: TableCellProps) {
  118. const props = this.props;
  119. const { column, expandIcon } = props;
  120. const cellInSelectionColumn = isSelectionColumn(column);
  121. // The expand button may be in a separate column or in the first data column
  122. const columnHasExpandIcon = isExpandedColumn(column) || expandIcon;
  123. if ((cellInSelectionColumn || columnHasExpandIcon) && !isEqual(nextProps, this.props)) {
  124. return true;
  125. } else {
  126. const omitProps = ['selected', 'expanded', 'expandIcon', 'disabled'];
  127. const propsOmitSelected = omit(props, omitProps);
  128. const nextPropsOmitSelected = omit(nextProps, omitProps);
  129. if (!isEqual(nextPropsOmitSelected, propsOmitSelected)) {
  130. return true;
  131. }
  132. }
  133. return false;
  134. }
  135. componentDidUpdate() {
  136. this.props.onDidUpdate(this.ref);
  137. }
  138. setRef = (ref: React.MutableRefObject<any>) => (this.ref = ref);
  139. handleClick = (e: React.MouseEvent) => {
  140. this.foundation.handleClick(e);
  141. const customCellProps = this.adapter.getCache('customCellProps');
  142. if (customCellProps && typeof customCellProps.onClick === 'function') {
  143. customCellProps.onClick(e);
  144. }
  145. };
  146. getTdProps() {
  147. const {
  148. record,
  149. index,
  150. column = {},
  151. fixedLeft,
  152. fixedRight,
  153. width,
  154. height,
  155. } = this.props;
  156. let tdProps: { style?: Partial<React.CSSProperties> } = {};
  157. let customCellProps = {};
  158. const fixedLeftFlag = fixedLeft || typeof fixedLeft === 'number';
  159. const fixedRightFlag = fixedRight || typeof fixedRight === 'number';
  160. if (fixedLeftFlag) {
  161. set(tdProps, 'style.left', typeof fixedLeft === 'number' ? fixedLeft : 0);
  162. } else if (fixedRightFlag) {
  163. set(tdProps, 'style.right', typeof fixedRight === 'number' ? fixedRight : 0);
  164. }
  165. if (width != null) {
  166. set(tdProps, 'style.width', width);
  167. }
  168. if (height != null) {
  169. set(tdProps, 'style.height', height);
  170. }
  171. if (column.onCell) {
  172. customCellProps = (column as any).onCell(record, index);
  173. this.adapter.setCache('customCellProps', { ...customCellProps });
  174. tdProps = { ...tdProps, ...omit(customCellProps, ['style', 'className', 'onClick']) };
  175. const customCellStyle = get(customCellProps, 'style') || {};
  176. tdProps.style = { ...tdProps.style, ...customCellStyle };
  177. }
  178. if (column.align) {
  179. tdProps.style = { ...tdProps.style, textAlign: column.align as Align };
  180. }
  181. return { tdProps, customCellProps };
  182. }
  183. /**
  184. * We should return undefined if no dataIndex is specified, but in order to
  185. * be compatible with object-path's behavior, we return the record object instead.
  186. */
  187. renderText(tdProps: { style?: React.CSSProperties; colSpan?: number; rowSpan?: number }) {
  188. const {
  189. record,
  190. indentSize,
  191. prefixCls,
  192. indent,
  193. index,
  194. expandIcon,
  195. renderExpandIcon,
  196. column = {},
  197. } = this.props;
  198. const { dataIndex, render, useFullRender } = column;
  199. let text: any,
  200. colSpan: number,
  201. rowSpan: number;
  202. if (typeof dataIndex === 'number') {
  203. text = get(record, dataIndex);
  204. } else if (!dataIndex || dataIndex.length === 0) {
  205. text = record;
  206. } else {
  207. text = get(record, dataIndex);
  208. }
  209. const indentText = (indent && indentSize) ? (
  210. <span
  211. style={{ paddingLeft: `${indentSize * indent}px` }}
  212. className={`${prefixCls}-row-indent indent-level-${indent}`}
  213. />
  214. ) : null;
  215. // column.render
  216. const realExpandIcon = typeof renderExpandIcon === 'function' ? renderExpandIcon(record) : expandIcon;
  217. if (render) {
  218. const renderOptions = {
  219. expandIcon: realExpandIcon,
  220. };
  221. // column.useFullRender
  222. if (useFullRender) {
  223. const { renderSelection } = this.context;
  224. const realSelection = typeof renderSelection === 'function' ? renderSelection(record) : null;
  225. Object.assign(renderOptions, {
  226. selection: realSelection,
  227. indentText,
  228. });
  229. }
  230. text = render(text, record, index, renderOptions);
  231. if (isInvalidRenderCellText(text)) {
  232. // eslint-disable-next-line no-param-reassign
  233. tdProps = text.props ? merge(tdProps, text.props) : tdProps;
  234. colSpan = tdProps.colSpan;
  235. rowSpan = tdProps.rowSpan;
  236. text = text.children;
  237. }
  238. }
  239. return { text, indentText, rowSpan, colSpan, realExpandIcon, tdProps };
  240. }
  241. renderInner(text: ReactNode, indentText: ReactNode, realExpandIcon: ReactNode) {
  242. const {
  243. prefixCls,
  244. isSection,
  245. expandIcon,
  246. column = {},
  247. } = this.props;
  248. const { tableWidth, anyColumnFixed } = this.context;
  249. const { useFullRender } = column;
  250. let inner = null;
  251. if (useFullRender) {
  252. inner = text;
  253. } else {
  254. inner = [
  255. <Fragment key={'indentText'}>{indentText}</Fragment>,
  256. <Fragment key={'expandIcon'}>{expandIcon ? realExpandIcon : null}</Fragment>,
  257. <Fragment key={'text'}>{text}</Fragment>,
  258. ];
  259. }
  260. if (isSection) {
  261. inner = (
  262. <div
  263. className={classnames(`${prefixCls}-section-inner`)}
  264. style={{ width: anyColumnFixed ? amendTableWidth(tableWidth) : undefined }}
  265. >
  266. {inner}
  267. </div>
  268. );
  269. }
  270. return inner;
  271. }
  272. render() {
  273. const {
  274. prefixCls,
  275. column = {},
  276. component: BodyCell,
  277. fixedLeft,
  278. fixedRight,
  279. lastFixedLeft,
  280. firstFixedRight,
  281. } = this.props;
  282. const { className } = column;
  283. const fixedLeftFlag = fixedLeft || typeof fixedLeft === 'number';
  284. const fixedRightFlag = fixedRight || typeof fixedRight === 'number';
  285. const { tdProps, customCellProps } = this.getTdProps();
  286. const renderTextResult = this.renderText(tdProps);
  287. let { text } = renderTextResult;
  288. const { indentText, rowSpan, colSpan, realExpandIcon, tdProps: newTdProps } = renderTextResult;
  289. if (rowSpan === 0 || colSpan === 0) {
  290. return null;
  291. }
  292. if (isInvalidRenderCellText(text)) {
  293. text = null;
  294. }
  295. const inner = this.renderInner(text, indentText, realExpandIcon);
  296. const columnCls = classnames(
  297. className,
  298. `${prefixCls}-row-cell`,
  299. get(customCellProps, 'className'),
  300. {
  301. [`${prefixCls}-cell-fixed-left`]: fixedLeftFlag,
  302. [`${prefixCls}-cell-fixed-left-last`]: lastFixedLeft,
  303. [`${prefixCls}-cell-fixed-right`]: fixedRightFlag,
  304. [`${prefixCls}-cell-fixed-right-first`]: firstFixedRight,
  305. }
  306. );
  307. return (
  308. <BodyCell className={columnCls} onClick={this.handleClick} {...newTdProps} ref={this.setRef}>
  309. {inner}
  310. </BodyCell>
  311. );
  312. }
  313. }