TableCell.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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, getRTLAlign, shouldShowEllipsisTitle } 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 { 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 { direction } = this.context;
  162. const isRTL = direction === 'rtl';
  163. const fixedLeftFlag = fixedLeft || typeof fixedLeft === 'number';
  164. const fixedRightFlag = fixedRight || typeof fixedRight === 'number';
  165. if (fixedLeftFlag) {
  166. set(tdProps, isRTL ? 'style.right' : 'style.left', typeof fixedLeft === 'number' ? fixedLeft : 0);
  167. } else if (fixedRightFlag) {
  168. set(tdProps, isRTL ? 'style.left' : 'style.right', typeof fixedRight === 'number' ? fixedRight : 0);
  169. }
  170. if (width != null) {
  171. set(tdProps, 'style.width', width);
  172. }
  173. if (height != null) {
  174. set(tdProps, 'style.height', height);
  175. }
  176. if (column.onCell) {
  177. customCellProps = (column as any).onCell(record, index);
  178. this.adapter.setCache('customCellProps', { ...customCellProps });
  179. tdProps = { ...tdProps, ...omit(customCellProps, ['style', 'className', 'onClick']) };
  180. const customCellStyle = get(customCellProps, 'style') || {};
  181. tdProps.style = { ...tdProps.style, ...customCellStyle };
  182. }
  183. if (column.align) {
  184. const textAlign = getRTLAlign(column.align, direction);
  185. tdProps.style = { ...tdProps.style, textAlign };
  186. }
  187. return { tdProps, customCellProps };
  188. }
  189. /**
  190. * We should return undefined if no dataIndex is specified, but in order to
  191. * be compatible with object-path's behavior, we return the record object instead.
  192. */
  193. renderText(tdProps: { style?: React.CSSProperties; colSpan?: number; rowSpan?: number }) {
  194. const {
  195. record,
  196. indentSize,
  197. prefixCls,
  198. indent,
  199. index,
  200. expandIcon,
  201. renderExpandIcon,
  202. column = {},
  203. } = this.props;
  204. const { dataIndex, render, useFullRender } = column;
  205. let text: any,
  206. colSpan: number,
  207. rowSpan: number;
  208. if (typeof dataIndex === 'number') {
  209. text = get(record, dataIndex);
  210. } else if (!dataIndex || dataIndex.length === 0) {
  211. text = record;
  212. } else {
  213. text = get(record, dataIndex);
  214. }
  215. const indentText = (indent && indentSize) ? (
  216. <span
  217. style={{ paddingLeft: `${indentSize * indent}px` }}
  218. className={`${prefixCls}-row-indent indent-level-${indent}`}
  219. />
  220. ) : null;
  221. // column.render
  222. const realExpandIcon = (typeof renderExpandIcon === 'function' ? renderExpandIcon(record) : expandIcon) as React.ReactNode;
  223. if (render) {
  224. const renderOptions = {
  225. expandIcon: realExpandIcon,
  226. };
  227. // column.useFullRender
  228. if (useFullRender) {
  229. const { renderSelection } = this.context;
  230. const realSelection = typeof renderSelection === 'function' ? renderSelection(record) : null;
  231. Object.assign(renderOptions, {
  232. selection: realSelection,
  233. indentText,
  234. });
  235. }
  236. text = render(text, record, index, renderOptions);
  237. if (isInvalidRenderCellText(text)) {
  238. // eslint-disable-next-line no-param-reassign
  239. tdProps = text.props ? merge(tdProps, text.props) : tdProps;
  240. colSpan = tdProps.colSpan;
  241. rowSpan = tdProps.rowSpan;
  242. text = text.children;
  243. }
  244. }
  245. return { text, indentText, rowSpan, colSpan, realExpandIcon, tdProps };
  246. }
  247. renderInner(text: ReactNode, indentText: ReactNode, realExpandIcon: ReactNode) {
  248. const {
  249. prefixCls,
  250. isSection,
  251. expandIcon,
  252. column = {},
  253. } = this.props;
  254. const { tableWidth, anyColumnFixed } = this.context;
  255. const { useFullRender } = column;
  256. let inner = null;
  257. if (useFullRender) {
  258. inner = text;
  259. } else {
  260. inner = [
  261. <Fragment key={'indentText'}>{indentText}</Fragment>,
  262. <Fragment key={'expandIcon'}>{expandIcon ? realExpandIcon : null}</Fragment>,
  263. <Fragment key={'text'}>{text}</Fragment>,
  264. ];
  265. }
  266. if (isSection) {
  267. inner = (
  268. <div
  269. className={classnames(`${prefixCls}-section-inner`)}
  270. style={{ width: anyColumnFixed ? amendTableWidth(tableWidth) : undefined }}
  271. >
  272. {inner}
  273. </div>
  274. );
  275. }
  276. return inner;
  277. }
  278. render() {
  279. const {
  280. prefixCls,
  281. column = {},
  282. component: BodyCell,
  283. fixedLeft,
  284. fixedRight,
  285. lastFixedLeft,
  286. firstFixedRight,
  287. colIndex
  288. } = this.props;
  289. const { direction } = this.context;
  290. const isRTL = direction === 'rtl';
  291. const { className, ellipsis } = column;
  292. const fixedLeftFlag = fixedLeft || typeof fixedLeft === 'number';
  293. const fixedRightFlag = fixedRight || typeof fixedRight === 'number';
  294. const { tdProps, customCellProps } = this.getTdProps();
  295. const renderTextResult = this.renderText(tdProps);
  296. let { text } = renderTextResult;
  297. const { indentText, rowSpan, colSpan, realExpandIcon, tdProps: newTdProps } = renderTextResult;
  298. let title: string;
  299. const shouldShowTitle = shouldShowEllipsisTitle(ellipsis);
  300. if (shouldShowTitle) {
  301. if (typeof text === 'string') {
  302. title = text;
  303. }
  304. }
  305. if (rowSpan === 0 || colSpan === 0) {
  306. return null;
  307. }
  308. if (isInvalidRenderCellText(text)) {
  309. text = null;
  310. }
  311. const inner = this.renderInner(text, indentText, realExpandIcon);
  312. let isFixedLeft, isFixedLeftLast, isFixedRight, isFixedRightFirst;
  313. if (isRTL) {
  314. isFixedLeft = fixedRightFlag;
  315. isFixedLeftLast = firstFixedRight;
  316. isFixedRight = fixedLeftFlag;
  317. isFixedRightFirst = lastFixedLeft;
  318. } else {
  319. isFixedLeft = fixedLeftFlag;
  320. isFixedLeftLast = lastFixedLeft;
  321. isFixedRight = fixedRightFlag;
  322. isFixedRightFirst = firstFixedRight;
  323. }
  324. const columnCls = classnames(
  325. className,
  326. `${prefixCls}-row-cell`,
  327. get(customCellProps, 'className'),
  328. {
  329. [`${prefixCls}-cell-fixed-left`]: isFixedLeft,
  330. [`${prefixCls}-cell-fixed-left-last`]: isFixedLeftLast,
  331. [`${prefixCls}-cell-fixed-right`]: isFixedRight,
  332. [`${prefixCls}-cell-fixed-right-first`]: isFixedRightFirst,
  333. [`${prefixCls}-row-cell-ellipsis`]: ellipsis,
  334. }
  335. );
  336. return (
  337. <BodyCell
  338. role="gridcell"
  339. aria-colindex={colIndex + 1}
  340. className={columnCls}
  341. onClick={this.handleClick}
  342. title={title}
  343. {...newTdProps}
  344. ref={this.setRef}
  345. >
  346. {inner}
  347. </BodyCell>
  348. );
  349. }
  350. }