@txdfe/at
Version:
一个设计体系组件库
477 lines (470 loc) • 18.3 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _reactDom = require("react-dom");
var _util = require("../util");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var NOOP = function NOOP() {};
var MAX_SYNC_UPDATES = 100;
var isEqualSubset = function isEqualSubset(a, b) {
for (var key in b) {
if (a[key] !== b[key]) {
return false;
}
}
return true;
};
/** VirtualList */
var VirtualList = exports["default"] = /*#__PURE__*/function (_Component) {
function VirtualList(props) {
var _this;
_classCallCheck(this, VirtualList);
_this = _callSuper(this, VirtualList, [props]);
_defineProperty(_this, "scrollTo", function (index) {
_this.setScroll(_this.getSpaceBefore(index));
});
var jumpIndex = props.jumpIndex;
var _this$constrain = _this.constrain(jumpIndex, 0, props),
from = _this$constrain.from,
size = _this$constrain.size;
_this.state = {
from: from,
size: size
};
_this.cache = {};
_this.cachedScroll = null;
_this.unstable = false;
_this.updateCounter = 0;
return _this;
}
_inherits(VirtualList, _Component);
return _createClass(VirtualList, [{
key: "componentDidMount",
value: function componentDidMount() {
var jumpIndex = this.props.jumpIndex;
this.updateFrameAndClearCache = this.updateFrameAndClearCache.bind(this);
_util.events.on(window, 'resize', this.updateFrameAndClearCache);
this.updateFrame(this.scrollTo.bind(this, jumpIndex));
}
}, {
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(next) {
var _this$state = this.state,
from = _this$state.from,
size = _this$state.size;
var oldIndex = this.props.jumpIndex;
var newIndex = next.jumpIndex;
if (oldIndex !== newIndex) {
this.updateFrame(this.scrollTo.bind(this, newIndex));
}
this.maybeSetState(this.constrain(from, size, next), NOOP);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
var _this2 = this;
// If the list has reached an unstable state, prevent an infinite loop.
if (this.unstable) {
return;
}
if (++this.updateCounter > MAX_SYNC_UPDATES) {
this.unstable = true;
}
if (!this.updateCounterTimeoutId) {
this.updateCounterTimeoutId = setTimeout(function () {
_this2.updateCounter = 0;
delete _this2.updateCounterTimeoutId;
}, 0);
}
this.updateFrame();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
_util.events.off(window, 'resize', this.updateFrameAndClearCache);
_util.events.off(this.scrollParent, 'scroll', this.updateFrameAndClearCache);
_util.events.off(this.scrollParent, 'mousewheel', NOOP);
}
}, {
key: "maybeSetState",
value: function maybeSetState(b, cb) {
if (isEqualSubset(this.state, b)) {
return cb();
}
this.setState(b, cb);
}
}, {
key: "getOffset",
value: function getOffset(el) {
var offset = el.clientLeft || 0;
do {
offset += el.offsetTop || 0;
el = el.offsetParent;
} while (el);
return offset;
}
}, {
key: "getEl",
value: function getEl() {
return this.el || this.items || {};
}
}, {
key: "getScrollParent",
value: function getScrollParent() {
var el = this.getEl();
el = el.parentElement;
switch (window.getComputedStyle(el).overflowY) {
case 'auto':
case 'scroll':
case 'overlay':
case 'visible':
return el;
}
return window;
}
}, {
key: "getScroll",
value: function getScroll() {
// Cache scroll position as this causes a forced synchronous layout.
// if (typeof this.cachedScroll === 'number') {
// return this.cachedScroll;
// }
var scrollParent = this.scrollParent;
var scrollKey = 'scrollTop';
var actual = scrollParent === window ?
// Firefox always returns document.body[scrollKey] as 0 and Chrome/Safari
// always return document.documentElement[scrollKey] as 0, so take
// whichever has a value.
document.body[scrollKey] || document.documentElement[scrollKey] : scrollParent[scrollKey];
var max = this.getScrollSize() - this.getViewportSize();
var scroll = Math.max(0, Math.min(actual, max));
var el = this.getEl();
this.cachedScroll = this.getOffset(scrollParent) + scroll - this.getOffset(el);
return this.cachedScroll;
}
}, {
key: "setScroll",
value: function setScroll(offset) {
var scrollParent = this.scrollParent;
offset += this.getOffset(this.getEl());
if (scrollParent === window) {
return window.scrollTo(0, offset);
}
offset -= this.getOffset(this.scrollParent);
scrollParent.scrollTop = offset;
}
}, {
key: "getViewportSize",
value: function getViewportSize() {
var scrollParent = this.scrollParent;
return scrollParent === window ? window.innerHeight : scrollParent.clientHeight;
}
}, {
key: "getScrollSize",
value: function getScrollSize() {
var scrollParent = this.scrollParent;
var _document = document,
body = _document.body,
documentElement = _document.documentElement;
var key = 'scrollHeight';
return scrollParent === window ? Math.max(body[key], documentElement[key]) : scrollParent[key];
}
}, {
key: "getStartAndEnd",
value: function getStartAndEnd() {
var threshold = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props.threshold;
var scroll = this.getScroll();
var trueScroll = scroll;
var start = Math.max(0, trueScroll - threshold);
var end = trueScroll + this.getViewportSize() + threshold;
return {
start: start,
end: end
};
}
// Called by 'scroll' and 'resize' events, clears scroll position cache.
}, {
key: "updateFrameAndClearCache",
value: function updateFrameAndClearCache(cb) {
this.cachedScroll = null;
return this.updateFrame(cb);
}
}, {
key: "updateFrame",
value: function updateFrame(cb) {
this.updateScrollParent();
if (typeof cb !== 'function') {
cb = NOOP;
}
return this.updateVariableFrame(cb);
}
}, {
key: "updateScrollParent",
value: function updateScrollParent() {
var prev = this.scrollParent;
this.scrollParent = this.getScrollParent();
if (prev === this.scrollParent) {
return;
}
if (prev) {
_util.events.off(prev, 'scroll', this.updateFrameAndClearCache);
_util.events.off(prev, 'mousewheel', NOOP);
}
_util.events.on(this.scrollParent, 'scroll', this.updateFrameAndClearCache);
_util.events.on(this.scrollParent, 'mousewheel', NOOP);
// You have to attach mousewheel listener to the scrollable element.
// Just an empty listener. After that onscroll events will be fired synchronously.
}
}, {
key: "updateVariableFrame",
value: function updateVariableFrame(cb) {
if (!this.props.itemSizeGetter) {
this.cacheSizes();
}
var _this$getStartAndEnd = this.getStartAndEnd(),
start = _this$getStartAndEnd.start,
end = _this$getStartAndEnd.end;
var _this$props = this.props,
pageSize = _this$props.pageSize,
children = _this$props.children;
var length = children.length;
var space = 0;
var from = 0;
var size = 0;
var maxFrom = length - 1;
while (from < maxFrom) {
var itemSize = this.getSizeOf(from);
if (itemSize === null || itemSize === undefined || space + itemSize > start) {
break;
}
space += itemSize;
++from;
}
var maxSize = length - from;
while (size < maxSize && space < end) {
var _itemSize = this.getSizeOf(from + size);
if (_itemSize === null || _itemSize === undefined) {
size = Math.min(size + pageSize, maxSize);
break;
}
space += _itemSize;
++size;
}
this.maybeSetState({
from: from,
size: size
}, cb);
}
}, {
key: "getSpaceBefore",
value: function getSpaceBefore(index) {
var cache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!index) {
return 0;
}
if (cache[index] !== null && cache[index] !== undefined) {
return cache[index] || 0;
}
// Find the closest space to index there is a cached value for.
var from = index;
while (from > 0 && (cache[from] === null || cache[from] === undefined)) {
from--;
}
// Finally, accumulate sizes of items from - index.
var space = cache[from] || 0;
for (var i = from; i < index; ++i) {
cache[i] = space;
var itemSize = this.getSizeOf(i);
if (itemSize === null || itemSize === undefined) {
break;
}
space += itemSize;
}
cache[index] = space;
return cache[index] || 0;
}
}, {
key: "cacheSizes",
value: function cacheSizes() {
var cache = this.cache;
var from = this.state.from;
var _this$items = this.items,
children = _this$items.children,
_this$items$props = _this$items.props,
props = _this$items$props === void 0 ? {} : _this$items$props;
var itemEls = children || props.children || [];
for (var i = 0, l = itemEls.length; i < l; ++i) {
var ulRef = (0, _reactDom.findDOMNode)(this.items);
var height = ulRef.children[i].offsetHeight;
if (height > 0) {
cache[from + i] = height;
}
}
}
}, {
key: "getSizeOf",
value: function getSizeOf(index) {
var _this3 = this;
var cache = this.cache;
var _this$props2 = this.props,
itemSizeGetter = _this$props2.itemSizeGetter,
jumpIndex = _this$props2.jumpIndex;
// Try the cache.
if (index in cache) {
return cache[index];
}
if (itemSizeGetter) {
return itemSizeGetter(index);
}
var height = Object.keys(this.cache).map(function (key) {
return _this3.cache[key];
}).pop();
if (!this.defaultItemHeight && jumpIndex > -1 && height) {
this.defaultItemHeight = height;
}
if (this.defaultItemHeight) {
return this.defaultItemHeight;
}
}
}, {
key: "constrain",
value: function constrain(from, size, _ref) {
var children = _ref.children,
minSize = _ref.minSize;
var length = children && children.length;
size = Math.max(size, minSize);
if (size > length) {
size = length;
}
from = from ? Math.max(Math.min(from, length - size), 0) : 0;
return {
from: from,
size: size
};
}
}, {
key: "renderMenuItems",
value: function renderMenuItems() {
var _this4 = this;
var _this$props3 = this.props,
children = _this$props3.children,
itemsRenderer = _this$props3.itemsRenderer;
var _this$state2 = this.state,
from = _this$state2.from,
size = _this$state2.size;
var items = [];
for (var i = 0; i < size; ++i) {
items.push(children[from + i]);
}
return itemsRenderer(items, function (c) {
_this4.items = c;
return _this4.items;
});
}
}, {
key: "render",
value: function render() {
var _this5 = this;
var _this$props4 = this.props,
_this$props4$children = _this$props4.children,
children = _this$props4$children === void 0 ? [] : _this$props4$children,
prefix = _this$props4.prefix,
className = _this$props4.className;
var length = children.length;
var from = this.state.from;
var items = this.renderMenuItems();
var style = {
position: 'relative'
};
var cache = {};
var size = this.getSpaceBefore(length, cache);
if (size) {
style.height = size;
}
var offset = this.getSpaceBefore(from, cache);
var transform = "translate(0px, ".concat(offset, "px)");
var listStyle = {
msTransform: transform,
WebkitTransform: transform,
transform: transform
};
var cls = (0, _classnames["default"])(_defineProperty(_defineProperty({}, "".concat(prefix, "virtual-list-wrapper"), true), className, !!className));
return /*#__PURE__*/_react["default"].createElement("div", {
className: cls,
style: style,
ref: function ref(c) {
_this5.el = c;
return _this5.el;
}
}, /*#__PURE__*/_react["default"].createElement("div", {
style: listStyle
}, items));
}
}]);
}(_react.Component);
_defineProperty(VirtualList, "displayName", 'VirtualList');
_defineProperty(VirtualList, "propTypes", {
prefix: _propTypes["default"].string,
/**
* 渲染的子节点
*/
children: _propTypes["default"].any,
/**
* 最小加载数量
*/
minSize: _propTypes["default"].number,
/**
* 一屏数量
*/
pageSize: _propTypes["default"].number,
/**
* 父渲染函数,默认为 (items, ref) => <ul ref={ref}>{items}</ul>
*/
itemsRenderer: _propTypes["default"].func,
/**
* 缓冲区高度
*/
threshold: _propTypes["default"].number,
/**
* 获取item高度的函数
*/
itemSizeGetter: _propTypes["default"].func,
/**
* 设置跳转位置,需要设置 itemSizeGetter 才能生效, 不设置认为元素等高并取第一个元素高度作为默认高
*/
jumpIndex: _propTypes["default"].number,
className: _propTypes["default"].string
});
_defineProperty(VirtualList, "defaultProps", {
prefix: 'next-',
itemsRenderer: function itemsRenderer(items, ref) {
return /*#__PURE__*/_react["default"].createElement("ul", {
ref: ref
}, items);
},
minSize: 1,
pageSize: 10,
jumpIndex: 0,
threshold: 100
});