@txdfe/at
Version:
一个设计体系组件库
553 lines (458 loc) • 17.6 kB
JavaScript
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); }
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; }
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import cx from 'classnames';
import { findDOMNode } from 'react-dom';
import { events } from '../util';
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 = /*#__PURE__*/function (_Component) {
_inherits(VirtualList, _Component);
var _super = _createSuper(VirtualList);
function VirtualList(props) {
var _this;
_classCallCheck(this, VirtualList);
_this = _super.call(this, props);
_defineProperty(_assertThisInitialized(_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;
}
_createClass(VirtualList, [{
key: "componentDidMount",
value: function componentDidMount() {
var jumpIndex = this.props.jumpIndex;
this.updateFrameAndClearCache = this.updateFrameAndClearCache.bind(this);
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() {
events.off(window, 'resize', this.updateFrameAndClearCache);
events.off(this.scrollParent, 'scroll', this.updateFrameAndClearCache);
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) {
events.off(prev, 'scroll', this.updateFrameAndClearCache);
events.off(prev, 'mousewheel', NOOP);
}
events.on(this.scrollParent, 'scroll', this.updateFrameAndClearCache);
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 = 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 _cx,
_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 = cx((_cx = {}, _defineProperty(_cx, "".concat(prefix, "virtual-list-wrapper"), true), _defineProperty(_cx, className, !!className), _cx));
return /*#__PURE__*/React.createElement("div", {
className: cls,
style: style,
ref: function ref(c) {
_this5.el = c;
return _this5.el;
}
}, /*#__PURE__*/React.createElement("div", {
style: listStyle
}, items));
}
}]);
return VirtualList;
}(Component);
_defineProperty(VirtualList, "displayName", 'VirtualList');
_defineProperty(VirtualList, "propTypes", {
prefix: PropTypes.string,
/**
* 渲染的子节点
*/
children: PropTypes.any,
/**
* 最小加载数量
*/
minSize: PropTypes.number,
/**
* 一屏数量
*/
pageSize: PropTypes.number,
/**
* 父渲染函数,默认为 (items, ref) => <ul ref={ref}>{items}</ul>
*/
itemsRenderer: PropTypes.func,
/**
* 缓冲区高度
*/
threshold: PropTypes.number,
/**
* 获取item高度的函数
*/
itemSizeGetter: PropTypes.func,
/**
* 设置跳转位置,需要设置 itemSizeGetter 才能生效, 不设置认为元素等高并取第一个元素高度作为默认高
*/
jumpIndex: PropTypes.number,
className: PropTypes.string
});
_defineProperty(VirtualList, "defaultProps", {
prefix: 'next-',
itemsRenderer: function itemsRenderer(items, ref) {
return /*#__PURE__*/React.createElement("ul", {
ref: ref
}, items);
},
minSize: 1,
pageSize: 10,
jumpIndex: 0,
threshold: 100
});
export { VirtualList as default };