table-body.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import { arrayFindIndex } from 'element-ui/src/utils/util';
  2. import { getCell, getColumnByCell, getRowIdentity } from './util';
  3. import { getStyle, hasClass, removeClass, addClass } from 'element-ui/src/utils/dom';
  4. import ElCheckbox from 'element-ui/packages/checkbox';
  5. import ElTooltip from 'element-ui/packages/tooltip';
  6. import debounce from 'throttle-debounce/debounce';
  7. import LayoutObserver from './layout-observer';
  8. import { mapStates } from './store/helper';
  9. import TableRow from './table-row.js';
  10. export default {
  11. name: 'ElTableBody',
  12. mixins: [LayoutObserver],
  13. components: {
  14. ElCheckbox,
  15. ElTooltip,
  16. TableRow
  17. },
  18. props: {
  19. store: {
  20. required: true
  21. },
  22. stripe: Boolean,
  23. context: {},
  24. rowClassName: [String, Function],
  25. rowStyle: [Object, Function],
  26. fixed: String,
  27. highlight: Boolean
  28. },
  29. render(h) {
  30. const data = this.data || [];
  31. return (
  32. <table
  33. class="el-table__body"
  34. cellspacing="0"
  35. cellpadding="0"
  36. border="0">
  37. <colgroup>
  38. {
  39. this.columns.map(column => <col name={column.id} key={column.id} />)
  40. }
  41. </colgroup>
  42. <tbody>
  43. {
  44. data.reduce((acc, row) => {
  45. return acc.concat(this.wrappedRowRender(row, acc.length));
  46. }, [])
  47. }
  48. <el-tooltip effect={this.table.tooltipEffect} placement="top" ref="tooltip" content={this.tooltipContent}></el-tooltip>
  49. </tbody>
  50. </table>
  51. );
  52. },
  53. computed: {
  54. table() {
  55. return this.$parent;
  56. },
  57. ...mapStates({
  58. data: 'data',
  59. columns: 'columns',
  60. treeIndent: 'indent',
  61. leftFixedLeafCount: 'fixedLeafColumnsLength',
  62. rightFixedLeafCount: 'rightFixedLeafColumnsLength',
  63. columnsCount: states => states.columns.length,
  64. leftFixedCount: states => states.fixedColumns.length,
  65. rightFixedCount: states => states.rightFixedColumns.length,
  66. hasExpandColumn: states => states.columns.some(({ type }) => type === 'expand')
  67. }),
  68. columnsHidden() {
  69. return this.columns.map((column, index) => this.isColumnHidden(index));
  70. },
  71. firstDefaultColumnIndex() {
  72. return arrayFindIndex(this.columns, ({ type }) => type === 'default');
  73. }
  74. },
  75. watch: {
  76. // don't trigger getter of currentRow in getCellClass. see https://jsfiddle.net/oe2b4hqt/
  77. // update DOM manually. see https://github.com/ElemeFE/element/pull/13954/files#diff-9b450c00d0a9dec0ffad5a3176972e40
  78. 'store.states.hoverRow'(newVal, oldVal) {
  79. if (!this.store.states.isComplex || this.$isServer) return;
  80. let raf = window.requestAnimationFrame;
  81. if (!raf) {
  82. raf = (fn) => setTimeout(fn, 16);
  83. }
  84. raf(() => {
  85. const rows = this.$el.querySelectorAll('.el-table__row');
  86. const oldRow = rows[oldVal];
  87. const newRow = rows[newVal];
  88. if (oldRow) {
  89. removeClass(oldRow, 'hover-row');
  90. }
  91. if (newRow) {
  92. addClass(newRow, 'hover-row');
  93. }
  94. });
  95. }
  96. },
  97. data() {
  98. return {
  99. tooltipContent: ''
  100. };
  101. },
  102. created() {
  103. this.activateTooltip = debounce(50, tooltip => tooltip.handleShowPopper());
  104. },
  105. methods: {
  106. getKeyOfRow(row, index) {
  107. const rowKey = this.table.rowKey;
  108. if (rowKey) {
  109. return getRowIdentity(row, rowKey);
  110. }
  111. return index;
  112. },
  113. isColumnHidden(index) {
  114. if (this.fixed === true || this.fixed === 'left') {
  115. return index >= this.leftFixedLeafCount;
  116. } else if (this.fixed === 'right') {
  117. return index < this.columnsCount - this.rightFixedLeafCount;
  118. } else {
  119. return (index < this.leftFixedLeafCount) || (index >= this.columnsCount - this.rightFixedLeafCount);
  120. }
  121. },
  122. getSpan(row, column, rowIndex, columnIndex) {
  123. let rowspan = 1;
  124. let colspan = 1;
  125. const fn = this.table.spanMethod;
  126. if (typeof fn === 'function') {
  127. const result = fn({
  128. row,
  129. column,
  130. rowIndex,
  131. columnIndex
  132. });
  133. if (Array.isArray(result)) {
  134. rowspan = result[0];
  135. colspan = result[1];
  136. } else if (typeof result === 'object') {
  137. rowspan = result.rowspan;
  138. colspan = result.colspan;
  139. }
  140. }
  141. return { rowspan, colspan };
  142. },
  143. getRowStyle(row, rowIndex) {
  144. const rowStyle = this.table.rowStyle;
  145. if (typeof rowStyle === 'function') {
  146. return rowStyle.call(null, {
  147. row,
  148. rowIndex
  149. });
  150. }
  151. return rowStyle || null;
  152. },
  153. getRowClass(row, rowIndex) {
  154. const classes = ['el-table__row'];
  155. if (this.table.highlightCurrentRow && row === this.store.states.currentRow) {
  156. classes.push('current-row');
  157. }
  158. if (this.stripe && rowIndex % 2 === 1) {
  159. classes.push('el-table__row--striped');
  160. }
  161. const rowClassName = this.table.rowClassName;
  162. if (typeof rowClassName === 'string') {
  163. classes.push(rowClassName);
  164. } else if (typeof rowClassName === 'function') {
  165. classes.push(rowClassName.call(null, {
  166. row,
  167. rowIndex
  168. }));
  169. }
  170. if (this.store.states.expandRows.indexOf(row) > -1) {
  171. classes.push('expanded');
  172. }
  173. return classes;
  174. },
  175. getCellStyle(rowIndex, columnIndex, row, column) {
  176. const cellStyle = this.table.cellStyle;
  177. if (typeof cellStyle === 'function') {
  178. return cellStyle.call(null, {
  179. rowIndex,
  180. columnIndex,
  181. row,
  182. column
  183. });
  184. }
  185. return cellStyle;
  186. },
  187. getCellClass(rowIndex, columnIndex, row, column) {
  188. const classes = [column.id, column.align, column.className];
  189. if (this.isColumnHidden(columnIndex)) {
  190. classes.push('is-hidden');
  191. }
  192. const cellClassName = this.table.cellClassName;
  193. if (typeof cellClassName === 'string') {
  194. classes.push(cellClassName);
  195. } else if (typeof cellClassName === 'function') {
  196. classes.push(cellClassName.call(null, {
  197. rowIndex,
  198. columnIndex,
  199. row,
  200. column
  201. }));
  202. }
  203. classes.push('el-table__cell');
  204. return classes.join(' ');
  205. },
  206. getColspanRealWidth(columns, colspan, index) {
  207. if (colspan < 1) {
  208. return columns[index].realWidth;
  209. }
  210. const widthArr = columns.map(({ realWidth }) => realWidth).slice(index, index + colspan);
  211. return widthArr.reduce((acc, width) => acc + width, -1);
  212. },
  213. handleCellMouseEnter(event, row) {
  214. const table = this.table;
  215. const cell = getCell(event);
  216. if (cell) {
  217. const column = getColumnByCell(table, cell);
  218. const hoverState = table.hoverState = { cell, column, row };
  219. table.$emit('cell-mouse-enter', hoverState.row, hoverState.column, hoverState.cell, event);
  220. }
  221. // 判断是否text-overflow, 如果是就显示tooltip
  222. const cellChild = event.target.querySelector('.cell');
  223. if (!(hasClass(cellChild, 'el-tooltip') && cellChild.childNodes.length)) {
  224. return;
  225. }
  226. // use range width instead of scrollWidth to determine whether the text is overflowing
  227. // to address a potential FireFox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1074543#c3
  228. const range = document.createRange();
  229. range.setStart(cellChild, 0);
  230. range.setEnd(cellChild, cellChild.childNodes.length);
  231. const rangeWidth = range.getBoundingClientRect().width;
  232. const padding = (parseInt(getStyle(cellChild, 'paddingLeft'), 10) || 0) +
  233. (parseInt(getStyle(cellChild, 'paddingRight'), 10) || 0);
  234. if ((rangeWidth + padding > cellChild.offsetWidth || cellChild.scrollWidth > cellChild.offsetWidth) && this.$refs.tooltip) {
  235. const tooltip = this.$refs.tooltip;
  236. // TODO 会引起整个 Table 的重新渲染,需要优化
  237. this.tooltipContent = cell.innerText || cell.textContent;
  238. tooltip.referenceElm = cell;
  239. tooltip.$refs.popper && (tooltip.$refs.popper.style.display = 'none');
  240. tooltip.doDestroy();
  241. tooltip.setExpectedState(true);
  242. this.activateTooltip(tooltip);
  243. }
  244. },
  245. handleCellMouseLeave(event) {
  246. const tooltip = this.$refs.tooltip;
  247. if (tooltip) {
  248. tooltip.setExpectedState(false);
  249. tooltip.handleClosePopper();
  250. }
  251. const cell = getCell(event);
  252. if (!cell) return;
  253. const oldHoverState = this.table.hoverState || {};
  254. this.table.$emit('cell-mouse-leave', oldHoverState.row, oldHoverState.column, oldHoverState.cell, event);
  255. },
  256. handleMouseEnter: debounce(30, function(index) {
  257. this.store.commit('setHoverRow', index);
  258. }),
  259. handleMouseLeave: debounce(30, function() {
  260. this.store.commit('setHoverRow', null);
  261. }),
  262. handleContextMenu(event, row) {
  263. this.handleEvent(event, row, 'contextmenu');
  264. },
  265. handleDoubleClick(event, row) {
  266. this.handleEvent(event, row, 'dblclick');
  267. },
  268. handleClick(event, row) {
  269. this.store.commit('setCurrentRow', row);
  270. this.handleEvent(event, row, 'click');
  271. },
  272. handleEvent(event, row, name) {
  273. const table = this.table;
  274. const cell = getCell(event);
  275. let column;
  276. if (cell) {
  277. column = getColumnByCell(table, cell);
  278. if (column) {
  279. table.$emit(`cell-${name}`, row, column, cell, event);
  280. }
  281. }
  282. table.$emit(`row-${name}`, row, column, event);
  283. },
  284. rowRender(row, $index, treeRowData) {
  285. const { treeIndent, columns, firstDefaultColumnIndex } = this;
  286. const rowClasses = this.getRowClass(row, $index);
  287. let display = true;
  288. if (treeRowData) {
  289. rowClasses.push('el-table__row--level-' + treeRowData.level);
  290. display = treeRowData.display;
  291. }
  292. // 指令 v-show 会覆盖 row-style 中 display
  293. // 使用 :style 代替 v-show https://github.com/ElemeFE/element/issues/16995
  294. let displayStyle = display ? null : {
  295. display: 'none'
  296. };
  297. return (
  298. <TableRow
  299. style={[displayStyle, this.getRowStyle(row, $index)]}
  300. class={rowClasses}
  301. key={this.getKeyOfRow(row, $index)}
  302. nativeOn-dblclick={($event) => this.handleDoubleClick($event, row)}
  303. nativeOn-click={($event) => this.handleClick($event, row)}
  304. nativeOn-contextmenu={($event) => this.handleContextMenu($event, row)}
  305. nativeOn-mouseenter={_ => this.handleMouseEnter($index)}
  306. nativeOn-mouseleave={this.handleMouseLeave}
  307. columns={columns}
  308. row={row}
  309. index={$index}
  310. store={this.store}
  311. context={this.context || this.table.$vnode.context}
  312. firstDefaultColumnIndex={firstDefaultColumnIndex}
  313. treeRowData={treeRowData}
  314. treeIndent={treeIndent}
  315. columnsHidden={this.columnsHidden}
  316. getSpan={this.getSpan}
  317. getColspanRealWidth={this.getColspanRealWidth}
  318. getCellStyle={this.getCellStyle}
  319. getCellClass={this.getCellClass}
  320. handleCellMouseEnter={this.handleCellMouseEnter}
  321. handleCellMouseLeave={this.handleCellMouseLeave}
  322. isSelected={this.store.isSelected(row)}
  323. isExpanded={this.store.states.expandRows.indexOf(row) > -1}
  324. fixed={this.fixed}
  325. >
  326. </TableRow>
  327. );
  328. },
  329. wrappedRowRender(row, $index) {
  330. const store = this.store;
  331. const { isRowExpanded, assertRowKey } = store;
  332. const { treeData, lazyTreeNodeMap, childrenColumnName, rowKey } = store.states;
  333. if (this.hasExpandColumn && isRowExpanded(row)) {
  334. const renderExpanded = this.table.renderExpanded;
  335. const tr = this.rowRender(row, $index);
  336. if (!renderExpanded) {
  337. console.error('[Element Error]renderExpanded is required.');
  338. return tr;
  339. }
  340. // 使用二维数组,避免修改 $index
  341. return [[
  342. tr,
  343. <tr key={'expanded-row__' + tr.key}>
  344. <td colspan={ this.columnsCount } class="el-table__cell el-table__expanded-cell">
  345. { renderExpanded(this.$createElement, { row, $index, store: this.store }) }
  346. </td>
  347. </tr>]];
  348. } else if (Object.keys(treeData).length) {
  349. assertRowKey();
  350. // TreeTable 时,rowKey 必须由用户设定,不使用 getKeyOfRow 计算
  351. // 在调用 rowRender 函数时,仍然会计算 rowKey,不太好的操作
  352. const key = getRowIdentity(row, rowKey);
  353. let cur = treeData[key];
  354. let treeRowData = null;
  355. if (cur) {
  356. treeRowData = {
  357. expanded: cur.expanded,
  358. level: cur.level,
  359. display: true
  360. };
  361. if (typeof cur.lazy === 'boolean') {
  362. if (typeof cur.loaded === 'boolean' && cur.loaded) {
  363. treeRowData.noLazyChildren = !(cur.children && cur.children.length);
  364. }
  365. treeRowData.loading = cur.loading;
  366. }
  367. }
  368. const tmp = [this.rowRender(row, $index, treeRowData)];
  369. // 渲染嵌套数据
  370. if (cur) {
  371. // currentRow 记录的是 index,所以还需主动增加 TreeTable 的 index
  372. let i = 0;
  373. const traverse = (children, parent) => {
  374. if (!(children && children.length && parent)) return;
  375. children.forEach(node => {
  376. // 父节点的 display 状态影响子节点的显示状态
  377. const innerTreeRowData = {
  378. display: parent.display && parent.expanded,
  379. level: parent.level + 1
  380. };
  381. const childKey = getRowIdentity(node, rowKey);
  382. if (childKey === undefined || childKey === null) {
  383. throw new Error('for nested data item, row-key is required.');
  384. }
  385. cur = { ...treeData[childKey] };
  386. // 对于当前节点,分成有无子节点两种情况。
  387. // 如果包含子节点的,设置 expanded 属性。
  388. // 对于它子节点的 display 属性由它本身的 expanded 与 display 共同决定。
  389. if (cur) {
  390. innerTreeRowData.expanded = cur.expanded;
  391. // 懒加载的某些节点,level 未知
  392. cur.level = cur.level || innerTreeRowData.level;
  393. cur.display = !!(cur.expanded && innerTreeRowData.display);
  394. if (typeof cur.lazy === 'boolean') {
  395. if (typeof cur.loaded === 'boolean' && cur.loaded) {
  396. innerTreeRowData.noLazyChildren = !(cur.children && cur.children.length);
  397. }
  398. innerTreeRowData.loading = cur.loading;
  399. }
  400. }
  401. i++;
  402. tmp.push(this.rowRender(node, $index + i, innerTreeRowData));
  403. if (cur) {
  404. const nodes = lazyTreeNodeMap[childKey] || node[childrenColumnName];
  405. traverse(nodes, cur);
  406. }
  407. });
  408. };
  409. // 对于 root 节点,display 一定为 true
  410. cur.display = true;
  411. const nodes = lazyTreeNodeMap[key] || row[childrenColumnName];
  412. traverse(nodes, cur);
  413. }
  414. return tmp;
  415. } else {
  416. return this.rowRender(row, $index);
  417. }
  418. }
  419. }
  420. };