ten-design-vue
Version:
ten-vue
724 lines (634 loc) • 23.1 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _babelHelperVueJsxMergeProps = _interopRequireDefault(require("babel-helper-vue-jsx-merge-props"));
var _tableBodyCell = _interopRequireDefault(require("./table-body-cell.js"));
var _tableHeadCell = _interopRequireDefault(require("./table-head-cell.js"));
var _domHelper = _interopRequireDefault(require("../scripts/utils/dom-helper"));
var _helper = require("../scripts/utils/helper");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getHeight(_height) {
var height = _height;
if (typeof height === 'number') return height;
if (typeof height === 'string') height = Number(height.replace(/px$/, ''));
if (!isNaN(height)) return height;
}
var _default2 = {
name: 'ten-table-table',
inject: ['table'],
props: {
/**
* 表头树
*/
columnsTree: {
type: Array,
default: function _default() {
return [];
}
},
/**
* 表头的叶子节点列表
*/
columns: {
type: Array,
default: function _default() {
return [];
}
},
rowProps: Function,
/**
* 表头树的深度
*/
depth: {
type: Number,
default: 0
},
/**
* 表格数据
*/
data: {
type: Array,
default: function _default() {
return [];
}
},
sizeData: {
type: Object,
default: function _default() {
return {
width: undefined,
trHeights: [],
thWidths: []
};
}
},
/**
* 无数据提示
*/
emptyText: [String, Function],
/**
* 固定的方向
*/
fixed: String,
/**
* 固定的列
*/
fixedColumns: Array,
/**
* 同步的scrollTop
*/
scrollTop: Number,
/**
* 实际渲染的table的宽度,
* 当用户没有为所有col设定宽度时,
* fixed-table的inner-table的宽度
* 需要使用middle-table的inner-table的宽度
*/
innderTableWidth: Number,
hoverRowIndex: Number
},
data: function data() {
return {
theadHeight: 0,
fixedTableWidth: undefined,
// fixed-table-wrapper的宽度
tbodyScrollTop: 0,
tbodyHeight: 0,
scrollbarWidth: 15,
scrollStatus: 'left'
};
},
computed: {
tbodyWrapperMaxHeight: function tbodyWrapperMaxHeight() {
var height = getHeight(this.table.maxHeight);
return height && height - this.theadHeight;
},
tbodyWrapperHeight: function tbodyWrapperHeight() {
var height = getHeight(this.table.height);
return height && height - this.theadHeight;
},
tableClassName: function tableClassName() {
var _ref;
return ['ten-table__table', (_ref = {
'ten-table__table--fixed': this.fixed
}, _defineProperty(_ref, "ten-table__table--fixed-".concat(this.fixed), this.fixed), _defineProperty(_ref, "is-scrolling--".concat(this.scrollStatus), this.scrollStatus), _ref)];
},
expandCol: function expandCol() {
return this.columns.find(function (col) {
return col.type === 'expand';
});
},
hasExpand: function hasExpand() {
return !!this.expandCol;
},
scrollableY: function scrollableY() {
var tbodyWrapperHeight = this.tbodyWrapperMaxHeight || this.tbodyWrapperHeight || this.tbodyHeight;
return tbodyWrapperHeight - this.tbodyHeight < 0;
},
fixedPrefix: function fixedPrefix() {
var fixedPrefix = this.fixed ? this.fixed : 'base';
return fixedPrefix;
}
},
watch: {
scrollTop: function scrollTop(v) {
var _this = this;
if (this.$refs.tbodyWrapper) {
this.$nextTick(function () {
_this.$refs.tbodyWrapper.scrollTop = v;
});
}
},
$route: {
handler: function handler() {
this.doLayout();
}
}
},
mounted: function mounted() {
this.doLayout();
this.initEventHandler();
this.$on('do-layout', this.doLayout);
this.passiveScroll = false;
this.scrollbarWidth = _domHelper.default.getBrowserScrollSize();
},
updated: function updated() {
this.setWrapperStyle();
},
beforeDestroy: function beforeDestroy() {
this.removeEventHandler();
},
render: function render(h) {
var _this2 = this;
var allRow = [];
this.getHeadRow(h, this.columnsTree, allRow);
var tableWidth;
if (this.fixed || this.table.scrollableX) {
if (this.scrollableY) {
tableWidth = this.innderTableWidth - this.scrollbarWidth;
} else {
tableWidth = this.innderTableWidth;
}
tableWidth += 'px';
}
var theadStyle = {
width: tableWidth
};
var theadWrapperStyle = {};
var tbodyStyle = {
width: tableWidth
};
var tbodyWrapperStyle = {
top: this.fixed ? "".concat(this.theadHeight, "px") : undefined,
maxHeight: "".concat(this.tbodyWrapperMaxHeight, "px"),
height: "".concat(this.tbodyWrapperHeight, "px")
};
if (this.scrollableY && this.fixed !== 'left') {
theadWrapperStyle['margin-right'] = "".concat(this.scrollbarWidth, "px");
}
theadStyle = _domHelper.default.filterCssStyles(theadStyle);
theadWrapperStyle = _domHelper.default.filterCssStyles(theadWrapperStyle);
tbodyWrapperStyle = _domHelper.default.filterCssStyles(tbodyWrapperStyle);
tbodyStyle = _domHelper.default.filterCssStyles(tbodyStyle);
var colgroup = this.renderColgroup();
return h("div", {
ref: 'tableWrapper',
"class": this.tableClassName
}, [this.table.hideHeader ? null : h("div", {
ref: 'theadWrapper',
"class": 'ten-table__table-head',
style: theadWrapperStyle
}, [h("table", {
attrs: {
cellspacing: '0',
cellpadding: '0',
border: '0'
},
style: theadStyle
}, [colgroup, h("thead", [allRow])])]), h("div", {
ref: 'tbodyWrapper',
"class": 'ten-table__table-body',
style: tbodyWrapperStyle,
on: {
"mouseleave": this.onTbodyMouseLeave
}
}, [h("table", {
ref: 'tbody',
attrs: {
cellspacing: '0',
cellpadding: '0',
border: '0'
},
style: tbodyStyle
}, [colgroup, h("tbody", {
ref: 'tbody'
}, [this.data.length > 0 ? this.data.map(function (row, i) {
return _this2.renderRows(h, row, i);
}) : h("tr", [h("td", {
"class": 'ten-table__table-cell ten-table__table-cell--empty-text',
attrs: {
colspan: this.columns.length
}
}, [typeof this.emptyText === 'function' ? this.emptyText() : this.emptyText])])])])])]);
},
methods: {
onResize: function onResize() {
var _this3 = this;
setTimeout(function () {
if (_this3.$refs.theadWrapper) {
_this3.theadHeight = _this3.$refs.theadWrapper.offsetHeight;
}
});
if (!this.fixed && this.$el) {
this.$emit('resize', this.$el);
}
setTimeout(function () {
if (_this3.$refs.tbody) {
_this3.tbodyHeight = _this3.$refs.tbody.offsetHeight;
}
});
setTimeout(function () {
_this3.setWrapperStyle();
});
},
onScroll: function onScroll() {
if (this.passiveScroll) {
this.passiveScroll = false;
return;
}
if (this.$refs.tbodyWrapper && this.$refs.theadWrapper) {
this.$refs.theadWrapper.scrollLeft = this.$refs.tbodyWrapper.scrollLeft;
var scrollStatus;
if (!this.fixed) {
if (this.$refs.tbodyWrapper.scrollLeft === 0) {
scrollStatus = 'left';
} else if (this.$refs.tbodyWrapper.scrollWidth - this.$refs.tbodyWrapper.clientWidth <= this.$refs.tbodyWrapper.scrollLeft) {
scrollStatus = 'right';
} else {
scrollStatus = 'middle';
}
}
this.$emit('scroll', {
tbodyScrollTop: this.$refs.tbodyWrapper.scrollTop,
scrollStatus: scrollStatus,
target: this
});
}
},
setScrollTop: function setScrollTop(scrollTop) {
if (this.$refs.tbodyWrapper) {
this.passiveScroll = true;
this.$refs.tbodyWrapper.scrollTop = scrollTop;
}
},
setBodyHover: function setBodyHover(index) {
if (this.$refs.tbody) {
var trs = this.$refs.tbody.querySelectorAll('tr');
_toConsumableArray(trs).forEach(function (tr) {
var trIndex = tr.getAttribute('data-row-index');
if (trIndex && Number(trIndex) === index) {
tr.classList.add('ten-table__table-row--hover');
} else {
tr.classList.remove('ten-table__table-row--hover');
}
});
}
},
setWrapperStyle: function setWrapperStyle() {
var fixedTableWidth = this.getTableWrapperWidth();
if (!fixedTableWidth) {
return;
}
var tableWrapperStyle = {
width: "".concat(fixedTableWidth, "px")
};
var theadWrapperStyle = {};
var tbodyWrapperStyle = {
top: "".concat(this.theadHeight, "px"),
'max-height': "".concat(this.tbodyWrapperMaxHeight, "px"),
height: "".concat(this.tbodyWrapperHeight, "px")
};
if (this.scrollableY) {
if (this.fixed === 'left') {
tbodyWrapperStyle['margin-right'] = "".concat(-this.scrollbarWidth, "px");
tbodyWrapperStyle['padding-right'] = "".concat(this.scrollbarWidth, "px");
} else {
// theadWrapperStyle['padding-right'] = `${this.scrollbarWidth}px`;
tableWrapperStyle.width = "".concat(fixedTableWidth + this.scrollbarWidth, "px");
tbodyWrapperStyle.width = "".concat(this.innderTableWidth, "px");
}
} else {
tbodyWrapperStyle['margin-right'] = '';
tbodyWrapperStyle['padding-right'] = '';
theadWrapperStyle['padding-right'] = '';
}
if (this.table.scrollableX) {
tbodyWrapperStyle['margin-bottom'] = "".concat(-this.scrollbarWidth, "px");
tbodyWrapperStyle['padding-bottom'] = "".concat(this.scrollbarWidth, "px");
tableWrapperStyle['margin-bottom'] = this.scrollbarWidth ? "".concat(this.scrollbarWidth + 1, "px") : 0;
} else {
tbodyWrapperStyle['margin-bottom'] = '';
tbodyWrapperStyle['padding-bottom'] = '';
tableWrapperStyle['margin-bottom'] = '';
}
_domHelper.default.setStyles(this.$refs.tableWrapper, tableWrapperStyle);
_domHelper.default.setStyles(this.$refs.theadWrapper, theadWrapperStyle);
_domHelper.default.setStyles(this.$refs.tbodyWrapper, tbodyWrapperStyle);
},
initEventHandler: function initEventHandler() {
this.$refs.tbodyWrapper && this.$refs.tbodyWrapper.addEventListener('scroll', this.onScroll);
window.addEventListener('resize', this.onResize);
},
removeEventHandler: function removeEventHandler() {
this.$refs.tbodyWrapper && this.$refs.tbodyWrapper.removeEventListener('scroll', this.onScroll);
window.removeEventListener('resize', this.onResize);
},
getTableWrapperWidth: function getTableWrapperWidth() {
if (this.$refs.theadWrapper) {
var cols = Array.from(this.$refs.theadWrapper.querySelectorAll("th[is-leaf][fixed=\"".concat(this.fixed, "\"]")));
return cols.reduce(function (acc, cur) {
return acc + cur.offsetWidth;
}, 0);
}
return 0;
},
renderColgroup: function renderColgroup() {
var h = this.$createElement;
var columns = this.columns,
innderTableWidth = this.innderTableWidth;
var definedWidthColumns = columns.filter(function (column) {
return column.validWidth;
});
var totalDefinedWidth = definedWidthColumns.reduce(function (p, c) {
if (c.validWidth < 1) {
// percent
return p + c.validWidth * innderTableWidth;
}
return p + c.validWidth;
}, 0);
var remainWidth = innderTableWidth - totalDefinedWidth;
var averageWidth = remainWidth / (columns.length - definedWidthColumns.length);
return h("colgroup", [columns.map(function (column, i) {
var width;
if (innderTableWidth && !column.validWidth && column.validMinWidth) {
// 如果当前列 minWidth 大于可剩余可分配宽度,则 minWidth 生效
var validMinWidth = column.validMinWidth;
if (validMinWidth < 1) {
validMinWidth = validMinWidth * innderTableWidth;
}
if (validMinWidth > averageWidth && validMinWidth < remainWidth) {
remainWidth -= validMinWidth;
width = column.minWidth;
}
} else if (column.validWidth) {
width = column.width; // eslint-disable-line
}
var colProps = {
attrs: (0, _helper.removeUndefinedAttr)({
width: width
})
};
return h("col", (0, _babelHelperVueJsxMergeProps.default)([{
key: i
}, colProps]));
})]);
},
getHeadRow: function getHeadRow(h, row, allRow) {
var _this4 = this;
if (row && row.length > 0) {
var newRow = [];
allRow.push(h("tr", [row.map(function (cell, i) {
var pureId = "th-".concat(allRow.length, "-").concat(i);
var id = "".concat(_this4.fixedPrefix, "-").concat(pureId);
var invisible = false;
if (!_this4.fixed && _this4.table.scrollableX && cell.fixed || _this4.fixed && _this4.table.scrollableX && cell.fixed !== _this4.fixed) {
invisible = true;
}
if (cell.children) {
newRow = newRow.concat(cell.children);
}
return h(_tableHeadCell.default, {
attrs: {
id: id,
pureId: pureId,
"data-cell-id": id,
rowspan: _this4.depth - cell.depth + 1,
colspan: cell.leafCount,
column: cell,
"data-th-invisible": invisible ? 1 : 0,
"is-leaf": cell.isLeaf,
fixed: cell.fixed,
invisible: invisible
}
});
})]));
this.getHeadRow(h, newRow, allRow);
}
},
renderRows: function renderRows(h, row, i) {
return this.renderRow(h, row, i);
},
renderRow: function renderRow(h, row, i) {
var _this5 = this;
var expanded = this.showExpandRow(row);
var rowProps = this.rowProps(row, i);
rowProps = rowProps || {}; // 是否绑定拖拽功能
var dragProps = this.table.dragSort ? {
attrs: {
draggable: this.table.dragSort
},
on: {
dragstart: this.handleDragstart
}
} : {};
var content = [h("tr", (0, _babelHelperVueJsxMergeProps.default)([{
"class": {
'ten-table__table-row--expanded': expanded,
'ten-table__table-row--hover': this.hoverRowIndex === i,
'ten-table__table-row--selected': Array.isArray(this.table.selectedRowKeys) && this.table.selectedRowKeys.indexOf(this.table.getRowKey(row)) > -1
},
attrs: {
"data-row-index": i
},
key: row[this.table.getRowKey(row)] || i,
on: {
"mouseenter": function mouseenter() {
_this5.onRowMouseEnter(i);
}
}
}, rowProps, dragProps]), [this.columns.map(function (column, j) {
var pureId = "td-".concat(i, "-").concat(j);
var id = "".concat(_this5.fixedPrefix, "-").concat(pureId);
var invisible = false;
if (!_this5.fixed && _this5.table.scrollableX && column.fixed || _this5.fixed && _this5.table.scrollableX && column.fixed !== _this5.fixed) {
invisible = true;
}
return h(_tableBodyCell.default, {
key: j,
attrs: {
id: id,
pureId: pureId,
"data-cell-id": id,
column: column,
row: row,
rowIndex: i,
colIndex: j,
expanded: expanded,
invisible: invisible,
"data-invisible": invisible
}
});
})])];
if (this.hasExpand) {
var _this$expandCol = this.expandCol,
renderCell = _this$expandCol.renderCell,
render = _this$expandCol.render;
var expandContent;
if (renderCell && typeof renderCell === 'function') {
expandContent = renderCell({
row: row,
column: this.expandCol,
$index: i
});
} else {
expandContent = typeof render === 'function' ? render(h, {
row: row,
column: this.expandCol,
$index: i
}) : row[render];
}
content.push(h("tr", {
"class": 'ten-table__table-row--expand',
key: "".concat(row[this.table.getRowKey(row)] || i, "_expand"),
directives: [{
name: "show",
value: expanded
}]
}, [h("td", {
attrs: {
colspan: this.columns.length
}
}, [h("div", {
"class": 'ten-table__table-cell'
}, [expandContent])])]));
}
return content;
},
handleDragstart: function handleDragstart(e) {
var _this6 = this;
function findNode(node, bool) {
if (!node) return node;
if (bool && bool(node)) return node;
return findNode(node.parentNode, bool);
}
function findNodeToTR(node) {
return findNode(node, function (node) {
return node.nodeName === 'TR';
});
}
function findNodeIndex(node) {
return [].indexOf.call(parent.children, node);
}
var parent = findNode(e.target, function (node) {
return node.nodeName === 'TBODY';
});
var dragNode = findNodeToTR(e.target);
var dragNodeIndex = findNodeIndex(dragNode);
dragNode.style.opacity = 0.6; // 拖拽移动的过程中,对移入的目标
function dragenter(event) {
var enterDrag = findNode(event.target, function (node) {
return node.nodeName === 'TR';
});
var enterDragIndex = findNodeIndex(enterDrag);
if (dragNode === enterDrag) return true; // 用于判断是否为上插入还是下插入的提示
// enterDrag.style.boxSizing = 'border-box';
if (dragNodeIndex > enterDragIndex) {
enterDrag.style.borderTop = '2px #0052d9 dashed';
} else {
enterDrag.style.borderBottom = '2px #0052d9 dashed';
}
}
parent.addEventListener('dragenter', dragenter); // 拖拽离开目标时,恢复样式
function dragleave(event) {
var leaveDrag = findNodeToTR(event.target);
if (dragNode === leaveDrag) return true;
leaveDrag.style.borderBottom = '';
leaveDrag.style.borderTop = '';
}
parent.addEventListener('dragleave', dragleave); // 拖拽动作结束的时候,拖拽节点样式恢复
// 清除所有事件
function dragend() {
dragNode.style.opacity = '';
clearEvent();
}
parent.addEventListener('dragend', dragend);
function dragover() {
// 阻止默认动作
event.preventDefault();
}
parent.addEventListener('dragover', dragover);
var drop = function drop(event) {
// 阻止默认动作(如打开一些元素的链接)
event.preventDefault();
var targetNode = findNodeToTR(event.target);
var targetNodeIndex = findNodeIndex(targetNode);
if (dragNodeIndex > targetNodeIndex) {
// 上插入
parent.insertBefore(dragNode, targetNode);
} else {
// 下插入
var targetNextNode = targetNode.nextSibling;
parent.insertBefore(dragNode, targetNextNode);
} // 初始化 style 样式
targetNode.style.borderBottom = '';
targetNode.style.borderTop = '';
dragNode.style.opacity = ''; // 返回拖拽排序完成后的数组
var trDoms = parent.querySelectorAll('tr');
var newData = [].map.call(trDoms, function (item) {
var rowIndex = item.getAttribute('data-row-index');
return _this6.data[+rowIndex];
}); // 触发父级 sort 事件
_this6.table.$emit('sort', newData, 'drag');
clearEvent();
}; // 用于清除拖拽的事件
function clearEvent() {
parent.removeEventListener('drop', drop);
parent.removeEventListener('dragenter', dragenter);
parent.removeEventListener('dragleave', dragleave);
parent.removeEventListener('dragend', dragend);
parent.removeEventListener('dragover', dragover);
}
parent.addEventListener('drop', drop);
},
doLayout: function doLayout() {
var _this7 = this;
this.$nextTick(function () {
_this7.onResize();
_this7.onScroll();
});
},
onRowMouseEnter: function onRowMouseEnter(i) {
this.$emit('hoverChange', i);
},
onTbodyMouseLeave: function onTbodyMouseLeave() {
this.$emit('hoverChange', -1);
},
showExpandRow: function showExpandRow(row) {
if (!this.hasExpand) return;
var rowKey = this.table.getRowKey(row);
return !!this.table.expandedRowKeys.find(function (key) {
return key === rowKey;
});
}
}
};
exports.default = _default2;