@txdfe/at
Version:
一个设计体系组件库
400 lines (323 loc) • 16.9 kB
JavaScript
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = virtual;
var _react = _interopRequireDefault(require("react"));
var _reactDom = require("react-dom");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _util = require("../util");
var _body = _interopRequireDefault(require("./virtual/body"));
var _util2 = require("./util");
var _excluded = ["useVirtual", "components", "dataSource", "fixedHeader", "rowHeight", "scrollToRow", "onBodyScroll"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
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; }
var noop = function noop() {};
function virtual(BaseComponent) {
var VirtualTable = /*#__PURE__*/function (_React$Component) {
_inherits(VirtualTable, _React$Component);
var _super = _createSuper(VirtualTable);
function VirtualTable() {
var _this;
_classCallCheck(this, VirtualTable);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_defineProperty(_assertThisInitialized(_this), "state", {
rowHeight: _this.props.rowHeight,
scrollToRow: _this.props.scrollToRow,
height: _this.props.maxBodyHeight
});
_defineProperty(_assertThisInitialized(_this), "onScroll", function () {
// 避免横向滚动带来的性能问题
var scrollTop = _this.bodyNode.scrollTop;
if (scrollTop === _this.lastScrollTop) {
return;
}
var start = _this.computeScrollToRow(scrollTop);
if (!('scrollToRow' in _this.props)) {
_this.setState({
scrollToRow: start
});
}
_this.props.onBodyScroll(start);
_this.lastScrollTop = scrollTop;
});
_defineProperty(_assertThisInitialized(_this), "getBodyNode", function (node, lockType) {
lockType = lockType ? lockType.charAt(0).toUpperCase() + lockType.substr(1) : '';
_this["body".concat(lockType, "Node")] = node;
});
_defineProperty(_assertThisInitialized(_this), "getTableInstance", function (type, instance) {
type = type ? type.charAt(0).toUpperCase() + type.substr(1) : '';
_this["table".concat(type, "Inc")] = instance;
});
return _this;
}
_createClass(VirtualTable, [{
key: "getChildContext",
value: function getChildContext() {
return {
onVirtualScroll: this.onScroll,
bodyHeight: this.computeBodyHeight(),
innerTop: this.computeInnerTop(),
getBodyNode: this.getBodyNode,
getTableInstanceForVirtual: this.getTableInstance,
rowSelection: this.rowSelection
};
}
}, {
key: "UNSAFE_componentWillMount",
value: function UNSAFE_componentWillMount() {
var _this$props = this.props,
useVirtual = _this$props.useVirtual,
dataSource = _this$props.dataSource;
this.hasVirtualData = useVirtual && dataSource && dataSource.length > 0;
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.hasVirtualData) {
this.lastScrollTop = this.bodyNode.scrollTop;
}
this.adjustScrollTop();
this.adjustSize();
this.reComputeSize();
}
}, {
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(nextProps) {
var useVirtual = nextProps.useVirtual,
dataSource = nextProps.dataSource;
this.hasVirtualData = useVirtual && dataSource && dataSource.length > 0;
if ('maxBodyHeight' in nextProps) {
if (this.state.height !== nextProps.maxBodyHeight) {
this.setState({
height: nextProps.maxBodyHeight
});
}
}
if ('scrollToRow' in nextProps) {
this.setState({
scrollToRow: nextProps.scrollToRow
});
}
if (this.state.rowHeight && 'rowHeight' in nextProps) {
var row = this.getRowNode();
var rowClientHeight = row && row.clientHeight;
if (rowClientHeight && rowClientHeight !== this.state.rowHeight) {
this.setState({
rowHeight: rowClientHeight
});
}
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
this.adjustScrollTop();
this.adjustSize();
this.reComputeSize();
}
}, {
key: "reComputeSize",
value: function reComputeSize() {
var rowHeight = this.state.rowHeight;
if (typeof rowHeight === 'function' && this.hasVirtualData) {
var row = this.getRowNode();
var rowClientHeight = row && row.clientHeight;
if (rowClientHeight !== this.state.rowHeight) {
this.setState({
rowHeight: rowClientHeight
});
}
}
}
}, {
key: "computeBodyHeight",
value: function computeBodyHeight() {
var rowHeight = this.state.rowHeight;
var dataSource = this.props.dataSource;
if (typeof rowHeight === 'function') {
return 0;
}
return dataSource.length * rowHeight;
}
}, {
key: "computeInnerTop",
value: function computeInnerTop() {
var rowHeight = this.state.rowHeight;
if (typeof rowHeight === 'function') {
return 0;
}
return this.start * rowHeight;
}
}, {
key: "getVisibleRange",
value: function getVisibleRange(ExpectStart) {
var _this$state = this.state,
height = _this$state.height,
rowHeight = _this$state.rowHeight;
var len = this.props.dataSource.length;
var end;
var visibleCount = 0;
var start = 0;
if (typeof rowHeight === 'function') {
// try get cell height;
end = 1;
} else {
visibleCount = parseInt(height / rowHeight, 10);
if (typeof ExpectStart === 'number') {
start = ExpectStart < len ? ExpectStart : 0;
}
end = Math.min(+start + 1 + visibleCount + 10, len);
}
this.end = end;
this.visibleCount = visibleCount;
return {
start: start,
end: end
};
}
}, {
key: "adjustScrollTop",
value: function adjustScrollTop() {
if (this.hasVirtualData) {
this.bodyNode.scrollTop = this.lastScrollTop % this.state.rowHeight + this.state.rowHeight * this.state.scrollToRow;
}
}
}, {
key: "adjustSize",
value: function adjustSize() {
if (this.hasVirtualData) {
var body = this.bodyNode;
var virtualScrollNode = body.querySelector('div');
var clientHeight = body.clientHeight,
clientWidth = body.clientWidth;
var tableInc = this.tableInc;
var tableNode = (0, _reactDom.findDOMNode)(tableInc);
var prefix = this.props.prefix;
var headerNode = tableNode.querySelector(".".concat(prefix, "table-header table"));
var headerClientWidth = headerNode && headerNode.clientWidth;
if (clientWidth < headerClientWidth) {
_util.dom.setStyle(virtualScrollNode, 'min-width', headerClientWidth);
var leftNode = this.bodyLeftNode;
var rightNode = this.bodyRightNode;
leftNode && _util.dom.setStyle(leftNode, 'max-height', clientHeight);
rightNode && _util.dom.setStyle(rightNode, 'max-height', clientHeight);
this.hasScrollbar = true;
} else {
_util.dom.setStyle(virtualScrollNode, 'min-width', 'auto');
this.hasScrollbar = false;
}
}
}
}, {
key: "computeScrollToRow",
value: function computeScrollToRow(offset) {
var rowHeight = this.state.rowHeight;
var start = parseInt(offset / rowHeight);
this.start = start;
return start;
}
}, {
key: "getRowNode",
value: function getRowNode() {
try {
// in case of finding an unmounted component due to cached data
// need to clear refs of this.tableInc when dataSource Changed
// use try catch for temporary
return (0, _reactDom.findDOMNode)(this.tableInc.getRowRef(0));
} catch (error) {
return null;
}
}
}, {
key: "render",
value: function render() {
/* eslint-disable no-unused-vars, prefer-const */
var _this$props2 = this.props,
useVirtual = _this$props2.useVirtual,
components = _this$props2.components,
dataSource = _this$props2.dataSource,
fixedHeader = _this$props2.fixedHeader,
rowHeight = _this$props2.rowHeight,
scrollToRow = _this$props2.scrollToRow,
onBodyScroll = _this$props2.onBodyScroll,
others = _objectWithoutProperties(_this$props2, _excluded);
var entireDataSource = dataSource;
this.rowSelection = this.props.rowSelection;
if (this.hasVirtualData) {
components = _objectSpread({}, components);
var _this$getVisibleRange = this.getVisibleRange(this.state.scrollToRow),
start = _this$getVisibleRange.start,
end = _this$getVisibleRange.end;
dataSource = dataSource.slice(start, end);
if (!components.Body) {
components.Body = _body["default"];
}
fixedHeader = true;
}
return /*#__PURE__*/_react["default"].createElement(BaseComponent, _extends({}, others, {
dataSource: dataSource,
entireDataSource: entireDataSource,
components: components,
fixedHeader: fixedHeader
}));
}
}]);
return VirtualTable;
}(_react["default"].Component);
_defineProperty(VirtualTable, "VirtualBody", _body["default"]);
_defineProperty(VirtualTable, "propTypes", _objectSpread({
/**
* 是否开启虚拟滚动
*/
useVirtual: _propTypes["default"].bool,
/**
* 设置行高
*/
rowHeight: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].func]),
maxBodyHeight: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]),
primaryKey: _propTypes["default"].string,
dataSource: _propTypes["default"].array,
/**
* 在内容区域滚动的时候触发的函数
*/
onBodyScroll: _propTypes["default"].func
}, BaseComponent.propTypes));
_defineProperty(VirtualTable, "defaultProps", _objectSpread(_objectSpread({}, BaseComponent.defaultProps), {}, {
primaryKey: 'id',
rowHeight: noop,
maxBodyHeight: 200,
components: {},
prefix: 'next-',
onBodyScroll: noop
}));
_defineProperty(VirtualTable, "childContextTypes", {
onVirtualScroll: _propTypes["default"].func,
bodyHeight: _propTypes["default"].number,
innerTop: _propTypes["default"].number,
getBodyNode: _propTypes["default"].func,
getTableInstanceForVirtual: _propTypes["default"].func,
rowSelection: _propTypes["default"].object
});
(0, _util2.statics)(VirtualTable, BaseComponent);
return VirtualTable;
}