TableCell.tsx 14 KB

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