TableCell.tsx 14 KB

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