TableCell.tsx 13 KB

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