@enact/moonstone
Version:
Large-screen/TV support library for Enact, containing a variety of UI components.
1,045 lines (1,018 loc) • 61 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = exports.VirtualListBaseNative = exports.VirtualListBase = void 0;
var _classnames = _interopRequireDefault(require("classnames"));
var _handle = require("@enact/core/handle");
var _platform = require("@enact/core/platform");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _equals = _interopRequireDefault(require("ramda/src/equals"));
var _react = require("react");
var _UiVirtualListModule = _interopRequireDefault(require("./UiVirtualList.module.css"));
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["className", "containerProps", "itemsRenderer", "style"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
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 _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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return 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, _toPropertyKey(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 _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(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); }
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 ? Object.setPrototypeOf.bind() : 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() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /**
* Unstyled virtual list components and behaviors to be customized by a theme or application.
*
* @module moonstone/UiVirtualList
* @exports VirtualListBase
*/
var nop = function nop() {},
JS = 'JS',
Native = 'Native';
var gridListItemSizeShape = _propTypes["default"].shape({
minHeight: _propTypes["default"].number.isRequired,
minWidth: _propTypes["default"].number.isRequired
});
/**
* The base version of the virtual list component.
*
* @class VirtualListCore
* @memberof moonstone/UiVirtualList
* @ui
* @private
*/
var VirtualListBaseFactory = function VirtualListBaseFactory(type) {
var _class;
return _class = /*#__PURE__*/function (_Component) {
_inherits(VirtualListCore, _Component);
var _super = _createSuper(VirtualListCore);
function VirtualListCore(_props) {
var _this;
_classCallCheck(this, VirtualListCore);
var nextState = null;
_this = _super.call(this, _props);
_this.scrollBounds = {
clientWidth: 0,
clientHeight: 0,
scrollWidth: 0,
scrollHeight: 0,
maxLeft: 0,
maxTop: 0
};
_this.moreInfo = {
firstVisibleIndex: null,
lastVisibleIndex: null
};
_this.primary = null;
_this.secondary = null;
_this.isPrimaryDirectionVertical = true;
_this.isItemSized = false;
_this.shouldUpdateBounds = false;
_this.dimensionToExtent = 0;
_this.threshold = 0;
_this.maxFirstIndex = 0;
_this.curDataSize = 0;
_this.hasDataSizeChanged = false;
_this.cc = [];
_this.scrollPosition = 0;
_this.scrollPositionTarget = 0;
// For individually sized item
_this.itemPositions = [];
_this.indexToScrollIntoView = -1;
_this.updateScrollPosition = function (_ref) {
var x = _ref.x,
y = _ref.y;
var rtl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _this.props.rtl;
if (type === Native) {
_this.scrollToPosition(x, y, rtl);
} else {
_this.setScrollPosition(x, y, rtl, x, y);
}
};
_this.isVertical = function () {
return _this.isPrimaryDirectionVertical;
};
_this.isHorizontal = function () {
return !_this.isPrimaryDirectionVertical;
};
_this.getScrollBounds = function () {
return _this.scrollBounds;
};
_this.getMoreInfo = function () {
return _this.moreInfo;
};
// For individually sized item
_this.getItemBottomPosition = function (index) {
var itemPosition = _this.itemPositions[index],
itemSize = _this.props.itemSizes[index];
if (itemPosition && (itemSize || itemSize === 0)) {
return itemPosition.position + itemSize;
} else {
return index * _this.primary.gridSize - _this.props.spacing;
}
};
// For individually sized item
_this.getItemTopPositionFromPreviousItemBottomPosition = function (index, spacing) {
return index === 0 ? 0 : _this.getItemBottomPosition(index - 1) + spacing;
};
_this.getItemPosition = function (index) {
var stickTo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'start';
var _assertThisInitialize = _assertThisInitialized(_this),
primary = _assertThisInitialize.primary,
position = _this.getGridPosition(index);
var offset = 0;
if (stickTo === 'start') {
offset = 0;
} else if (_this.props.itemSizes) {
offset = primary.clientSize - _this.props.itemSizes[index];
} else {
offset = primary.clientSize - primary.itemSize;
}
position.primaryPosition -= offset;
return _this.gridPositionToItemPosition(position);
};
_this.gridPositionToItemPosition = function (_ref2) {
var primaryPosition = _ref2.primaryPosition,
secondaryPosition = _ref2.secondaryPosition;
return _this.isPrimaryDirectionVertical ? {
left: secondaryPosition,
top: primaryPosition
} : {
left: primaryPosition,
top: secondaryPosition
};
};
_this.getXY = function (primaryPosition, secondaryPosition) {
return _this.isPrimaryDirectionVertical ? {
x: secondaryPosition,
y: primaryPosition
} : {
x: primaryPosition,
y: secondaryPosition
};
};
_this.getClientSize = function (node) {
return {
clientWidth: node.clientWidth,
clientHeight: node.clientHeight
};
};
_this.getStatesAndUpdateBounds = function (props) {
var firstIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var dataSize = props.dataSize,
overhang = props.overhang,
updateStatesAndBounds = props.updateStatesAndBounds,
_assertThisInitialize2 = _assertThisInitialized(_this),
dimensionToExtent = _assertThisInitialize2.dimensionToExtent,
primary = _assertThisInitialize2.primary,
moreInfo = _assertThisInitialize2.moreInfo,
scrollPosition = _assertThisInitialize2.scrollPosition,
numOfItems = Math.min(dataSize, dimensionToExtent * (Math.ceil(primary.clientSize / primary.gridSize) + overhang)),
wasFirstIndexMax = _this.maxFirstIndex < moreInfo.firstVisibleIndex - dimensionToExtent && firstIndex === _this.maxFirstIndex,
dataSizeDiff = dataSize - _this.curDataSize;
var newFirstIndex = firstIndex;
// When calling setState() except in didScroll(), `shouldUpdateBounds` should be `true`
// so that setState() in didScroll() could be called to override state.
// Before calling setState() except in didScroll(), getStatesAndUpdateBounds() is always called.
// So `shouldUpdateBounds` is true here.
_this.shouldUpdateBounds = true;
_this.maxFirstIndex = Math.ceil((dataSize - numOfItems) / dimensionToExtent) * dimensionToExtent;
_this.curDataSize = dataSize;
// reset children
_this.cc = [];
_this.itemPositions = []; // For individually sized item
_this.calculateScrollBounds(props);
_this.updateMoreInfo(dataSize, scrollPosition);
if (!(updateStatesAndBounds && updateStatesAndBounds({
cbScrollTo: props.cbScrollTo,
numOfItems: numOfItems,
dataSize: dataSize,
moreInfo: moreInfo
}))) {
newFirstIndex = _this.calculateFirstIndex(props, wasFirstIndexMax, dataSizeDiff, firstIndex);
}
return {
firstIndex: Math.min(newFirstIndex, _this.maxFirstIndex),
numOfItems: numOfItems
};
};
_this.setContainerSize = function () {
if (_this.contentRef.current) {
_this.contentRef.current.style.width = _this.scrollBounds.scrollWidth + (_this.isPrimaryDirectionVertical ? -1 : 0) + 'px';
_this.contentRef.current.style.height = _this.scrollBounds.scrollHeight + (_this.isPrimaryDirectionVertical ? 0 : -1) + 'px';
}
};
_this.getItemNode = function (index) {
var ref = _this.itemContainerRef.current;
return ref ? ref.children[index % _this.state.numOfItems] : null;
};
_this.applyStyleToNewNode = function (index) {
var _this2;
var _this$props = _this.props,
itemRenderer = _this$props.itemRenderer,
getComponentProps = _this$props.getComponentProps,
key = index % _this.state.numOfItems,
itemElement = itemRenderer(_objectSpread(_objectSpread({}, _this.props.childProps), {}, {
key: key,
index: index
})),
componentProps = getComponentProps && getComponentProps(index) || {};
for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
_this.cc[key] = /*#__PURE__*/(0, _react.cloneElement)(itemElement, _objectSpread(_objectSpread({}, componentProps), {}, {
className: (0, _classnames["default"])(_UiVirtualListModule["default"].listItem, itemElement.props.className),
style: _objectSpread(_objectSpread({}, itemElement.props.style), (_this2 = _this).composeStyle.apply(_this2, rest))
}));
};
_this.applyStyleToHideNode = function (index) {
var key = index % _this.state.numOfItems;
_this.cc[key] = /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
style: {
display: 'none'
}
}, key);
};
_this.getScrollHeight = function () {
return _this.isPrimaryDirectionVertical ? _this.getVirtualScrollDimension() : _this.scrollBounds.clientHeight;
};
_this.getScrollWidth = function () {
return _this.isPrimaryDirectionVertical ? _this.scrollBounds.clientWidth : _this.getVirtualScrollDimension();
};
_this.getVirtualScrollDimension = function () {
if (_this.props.itemSizes) {
return _this.props.itemSizes.reduce(function (total, size, index) {
return total + size + (index > 0 ? _this.props.spacing : 0);
}, 0);
} else {
var _assertThisInitialize3 = _assertThisInitialized(_this),
dimensionToExtent = _assertThisInitialize3.dimensionToExtent,
primary = _assertThisInitialize3.primary,
curDataSize = _assertThisInitialize3.curDataSize,
spacing = _this.props.spacing;
return Math.ceil(curDataSize / dimensionToExtent) * primary.gridSize - spacing;
}
};
_this.syncClientSize = function () {
var _assertThisInitialize4 = _assertThisInitialized(_this),
props = _assertThisInitialize4.props,
node = _this.containerRef.current;
if (!props.clientSize && !node) {
return false;
}
var _ref3 = props.clientSize || _this.getClientSize(node),
clientWidth = _ref3.clientWidth,
clientHeight = _ref3.clientHeight,
_assertThisInitialize5 = _assertThisInitialized(_this),
scrollBounds = _assertThisInitialize5.scrollBounds;
if (clientWidth !== scrollBounds.clientWidth || clientHeight !== scrollBounds.clientHeight) {
_this.calculateMetrics(props);
_this.setState(_this.getStatesAndUpdateBounds(props));
_this.setContainerSize();
return true;
}
return false;
};
_this.containerRef = /*#__PURE__*/(0, _react.createRef)();
_this.contentRef = /*#__PURE__*/(0, _react.createRef)();
_this.itemContainerRef = /*#__PURE__*/(0, _react.createRef)();
if (_props.clientSize) {
_this.calculateMetrics(_props);
nextState = _this.getStatesAndUpdateBounds(_props);
}
_this.state = _objectSpread({
firstIndex: 0,
numOfItems: 0,
prevChildProps: null,
prevFirstIndex: 0,
updateFrom: 0,
updateTo: 0
}, nextState);
return _this;
}
_createClass(VirtualListCore, [{
key: "componentDidMount",
value:
// Calculate metrics for VirtualList after the 1st render to know client W/H.
function componentDidMount() {
if (!this.props.clientSize) {
this.calculateMetrics(this.props);
this.setState(this.getStatesAndUpdateBounds(this.props));
} else {
this.emitUpdateItems();
}
if (this.props.itemSizes) {
this.adjustItemPositionWithItemSize();
} else {
this.setContainerSize();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
var deferScrollTo = false;
var _this$state = this.state,
firstIndex = _this$state.firstIndex,
numOfItems = _this$state.numOfItems;
this.shouldUpdateBounds = false;
// TODO: remove `this.hasDataSizeChanged` and fix moonstone/UiScrollable*
this.hasDataSizeChanged = prevProps.dataSize !== this.props.dataSize;
if (prevState.firstIndex !== firstIndex || prevState.numOfItems !== numOfItems) {
this.emitUpdateItems();
}
// When an item expands or shrinks,
// we need to calculate the item position again and
// the item needs to scroll into view if the item does not show fully.
if (this.props.itemSizes) {
if (this.itemPositions.length > this.props.itemSizes.length) {
// The item with `this.props.itemSizes.length` index is not rendered yet.
// So the item could scroll into view after it rendered.
// To do it, `this.props.itemSizes.length` value is cached in `this.indexToScrollIntoView`.
this.indexToScrollIntoView = this.props.itemSizes.length;
this.itemPositions = _toConsumableArray(this.itemPositions.slice(0, this.props.itemSizes.length));
this.adjustItemPositionWithItemSize();
} else {
var indexToScrollIntoView = this.indexToScrollIntoView;
this.adjustItemPositionWithItemSize();
if (indexToScrollIntoView !== -1) {
// Currently we support expandable items in only vertical VirtualList.
// So the top and bottom of the boundaries are checked.
var scrollBounds = {
top: this.scrollPosition,
bottom: this.scrollPosition + this.scrollBounds.clientHeight
},
itemBounds = {
top: this.getGridPosition(indexToScrollIntoView).primaryPosition,
bottom: this.getItemBottomPosition(indexToScrollIntoView)
};
if (itemBounds.top < scrollBounds.top) {
this.props.cbScrollTo({
index: indexToScrollIntoView,
stickTo: 'start',
animate: true
});
} else if (itemBounds.bottom > scrollBounds.bottom) {
this.props.cbScrollTo({
index: indexToScrollIntoView,
stickTo: 'end',
animate: true
});
}
}
this.indexToScrollIntoView = -1;
}
}
if (prevProps.direction !== this.props.direction || prevProps.overhang !== this.props.overhang || prevProps.spacing !== this.props.spacing || !(0, _equals["default"])(prevProps.itemSize, this.props.itemSize)) {
var _this$getXY = this.getXY(this.scrollPosition, 0),
x = _this$getXY.x,
y = _this$getXY.y;
this.calculateMetrics(this.props);
this.setState(this.getStatesAndUpdateBounds(this.props));
this.setContainerSize();
var _this$scrollBounds = this.scrollBounds,
clientHeight = _this$scrollBounds.clientHeight,
clientWidth = _this$scrollBounds.clientWidth,
scrollHeight = _this$scrollBounds.scrollHeight,
scrollWidth = _this$scrollBounds.scrollWidth;
var xMax = scrollWidth - clientWidth;
var yMax = scrollHeight - clientHeight;
this.updateScrollPosition({
x: xMax > x ? x : xMax,
y: yMax > y ? y : yMax
});
deferScrollTo = true;
} else if (this.hasDataSizeChanged) {
var newState = this.getStatesAndUpdateBounds(this.props, this.state.firstIndex);
this.setState(newState);
this.setContainerSize();
deferScrollTo = true;
} else if (prevProps.rtl !== this.props.rtl) {
this.updateScrollPosition(this.getXY(this.scrollPosition, 0));
}
var maxPos = this.isPrimaryDirectionVertical ? this.scrollBounds.maxTop : this.scrollBounds.maxLeft;
if (!deferScrollTo && this.scrollPosition > maxPos) {
this.props.cbScrollTo({
position: this.isPrimaryDirectionVertical ? {
y: maxPos
} : {
x: maxPos
},
animate: false
});
}
}
}, {
key: "getGridPosition",
value: function getGridPosition(index) {
var _this$props2 = this.props,
dataSize = _this$props2.dataSize,
itemSizes = _this$props2.itemSizes,
dimensionToExtent = this.dimensionToExtent,
itemPositions = this.itemPositions,
primary = this.primary,
secondary = this.secondary,
secondaryPosition = index % dimensionToExtent * secondary.gridSize,
extent = Math.floor(index / dimensionToExtent);
var primaryPosition;
if (itemSizes && typeof itemSizes[index] !== 'undefined' && dataSize > index) {
var firstIndexInExtent = extent * dimensionToExtent;
if (!itemPositions[firstIndexInExtent]) {
// Cache individually sized item positions
for (var i = itemPositions.length; i <= index; i++) {
this.calculateAndCacheItemPosition(i);
}
}
if (itemPositions[firstIndexInExtent]) {
primaryPosition = itemPositions[firstIndexInExtent].position;
} else {
primaryPosition = extent * primary.gridSize;
}
} else {
primaryPosition = extent * primary.gridSize;
}
return {
primaryPosition: primaryPosition,
secondaryPosition: secondaryPosition
};
}
}, {
key: "emitUpdateItems",
value: function emitUpdateItems() {
var dataSize = this.props.dataSize;
var _this$state2 = this.state,
firstIndex = _this$state2.firstIndex,
numOfItems = _this$state2.numOfItems;
(0, _handle.forward)('onUpdateItems', {
firstIndex: firstIndex,
lastIndex: Math.min(firstIndex + numOfItems, dataSize)
}, this.props);
}
}, {
key: "calculateMetrics",
value: function calculateMetrics(props) {
var clientSize = props.clientSize,
direction = props.direction,
itemSize = props.itemSize,
overhang = props.overhang,
spacing = props.spacing,
node = this.containerRef.current;
if (!clientSize && !node) {
return;
}
var _ref4 = clientSize || this.getClientSize(node),
clientWidth = _ref4.clientWidth,
clientHeight = _ref4.clientHeight,
heightInfo = {
clientSize: clientHeight,
minItemSize: itemSize.minHeight || null,
itemSize: itemSize
},
widthInfo = {
clientSize: clientWidth,
minItemSize: itemSize.minWidth || null,
itemSize: itemSize
};
var primary, secondary, dimensionToExtent, thresholdBase;
this.isPrimaryDirectionVertical = direction === 'vertical';
if (this.isPrimaryDirectionVertical) {
primary = heightInfo;
secondary = widthInfo;
} else {
primary = widthInfo;
secondary = heightInfo;
}
dimensionToExtent = 1;
this.isItemSized = primary.minItemSize && secondary.minItemSize;
if (this.isItemSized) {
// the number of columns is the ratio of the available width plus the spacing
// by the minimum item width plus the spacing
dimensionToExtent = Math.max(Math.floor((secondary.clientSize + spacing) / (secondary.minItemSize + spacing)), 1);
// the actual item width is a ratio of the remaining width after all columns
// and spacing are accounted for and the number of columns that we know we should have
secondary.itemSize = Math.floor((secondary.clientSize - spacing * (dimensionToExtent - 1)) / dimensionToExtent);
// the actual item height is related to the item width
primary.itemSize = Math.floor(primary.minItemSize * (secondary.itemSize / secondary.minItemSize));
}
primary.gridSize = primary.itemSize + spacing;
secondary.gridSize = secondary.itemSize + spacing;
thresholdBase = primary.gridSize * Math.ceil(overhang / 2);
this.threshold = {
min: -Infinity,
max: thresholdBase,
base: thresholdBase
};
this.dimensionToExtent = dimensionToExtent;
this.primary = primary;
this.secondary = secondary;
// reset
this.scrollPosition = 0;
if (type === JS && this.contentRef.current) {
this.contentRef.current.style.transform = null;
}
}
}, {
key: "calculateFirstIndex",
value: function calculateFirstIndex(props, wasFirstIndexMax, dataSizeDiff, firstIndex) {
var overhang = props.overhang,
dimensionToExtent = this.dimensionToExtent,
isPrimaryDirectionVertical = this.isPrimaryDirectionVertical,
maxFirstIndex = this.maxFirstIndex,
primary = this.primary,
scrollBounds = this.scrollBounds,
scrollPosition = this.scrollPosition,
threshold = this.threshold,
gridSize = primary.gridSize;
var newFirstIndex = firstIndex;
if (wasFirstIndexMax && dataSizeDiff > 0) {
// If dataSize increased from bottom, we need adjust firstIndex
// If this is a gridlist and dataSizeDiff is smaller than 1 line, we are adjusting firstIndex without threshold change.
if (dimensionToExtent > 1 && dataSizeDiff < dimensionToExtent) {
newFirstIndex = maxFirstIndex;
} else {
// For other bottom adding case, we need to update firstIndex and threshold.
var maxPos = isPrimaryDirectionVertical ? scrollBounds.maxTop : scrollBounds.maxLeft,
maxOfMin = maxPos - threshold.base,
numOfUpperLine = Math.floor(overhang / 2),
firstIndexFromPosition = Math.floor(scrollPosition / gridSize),
expectedFirstIndex = Math.max(0, firstIndexFromPosition - numOfUpperLine);
// To navigate with 5way, we need to adjust firstIndex to the next line
// since at the bottom we have num of overhang lines for upper side but none for bottom side
// So we add numOfUpperLine at the top and rest lines at the bottom
newFirstIndex = Math.min(maxFirstIndex, expectedFirstIndex * dimensionToExtent);
// We need to update threshold also since we moved the firstIndex
threshold.max = Math.min(maxPos, threshold.max + gridSize);
threshold.min = Math.min(maxOfMin, threshold.max - gridSize);
}
} else {
// Other cases, we can keep the min value between firstIndex and maxFirstIndex. No need to change threshold
newFirstIndex = Math.min(firstIndex, maxFirstIndex);
}
return newFirstIndex;
}
}, {
key: "calculateScrollBounds",
value: function calculateScrollBounds(props) {
var clientSize = props.clientSize,
node = this.containerRef.current;
if (!clientSize && !node) {
return;
}
var scrollBounds = this.scrollBounds,
isPrimaryDirectionVertical = this.isPrimaryDirectionVertical,
_ref5 = clientSize || this.getClientSize(node),
clientWidth = _ref5.clientWidth,
clientHeight = _ref5.clientHeight;
var maxPos;
scrollBounds.clientWidth = clientWidth;
scrollBounds.clientHeight = clientHeight;
scrollBounds.scrollWidth = this.getScrollWidth();
scrollBounds.scrollHeight = this.getScrollHeight();
scrollBounds.maxLeft = Math.max(0, scrollBounds.scrollWidth - clientWidth);
scrollBounds.maxTop = Math.max(0, scrollBounds.scrollHeight - clientHeight);
// correct position
maxPos = isPrimaryDirectionVertical ? scrollBounds.maxTop : scrollBounds.maxLeft;
this.syncThreshold(maxPos);
}
}, {
key: "updateMoreInfo",
value: function updateMoreInfo(dataSize, primaryPosition) {
var dimensionToExtent = this.dimensionToExtent,
moreInfo = this.moreInfo,
_this$primary = this.primary,
itemSize = _this$primary.itemSize,
gridSize = _this$primary.gridSize,
clientSize = _this$primary.clientSize;
if (dataSize <= 0) {
moreInfo.firstVisibleIndex = null;
moreInfo.lastVisibleIndex = null;
} else if (this.props.itemSizes) {
var _this$state3 = this.state,
firstIndex = _this$state3.firstIndex,
numOfItems = _this$state3.numOfItems;
var isPrimaryDirectionVertical = this.isPrimaryDirectionVertical,
_this$scrollBounds2 = this.scrollBounds,
clientWidth = _this$scrollBounds2.clientWidth,
clientHeight = _this$scrollBounds2.clientHeight,
scrollPosition = this.scrollPosition;
var size = isPrimaryDirectionVertical ? clientHeight : clientWidth;
var firstVisibleIndex = null,
lastVisibleIndex = null;
for (var i = firstIndex; i < firstIndex + numOfItems; i++) {
if (scrollPosition <= this.getItemBottomPosition(i)) {
firstVisibleIndex = i;
break;
}
}
for (var _i = firstIndex + numOfItems - 1; _i >= firstIndex; _i--) {
if (scrollPosition + size >= this.getItemBottomPosition(_i) - this.props.itemSizes[_i]) {
lastVisibleIndex = _i;
break;
}
}
if (firstVisibleIndex > lastVisibleIndex) {
firstVisibleIndex = null;
lastVisibleIndex = null;
}
moreInfo.firstVisibleIndex = firstVisibleIndex;
moreInfo.lastVisibleIndex = lastVisibleIndex;
} else {
moreInfo.firstVisibleIndex = (Math.floor((primaryPosition - itemSize) / gridSize) + 1) * dimensionToExtent;
moreInfo.lastVisibleIndex = Math.min(dataSize - 1, Math.ceil((primaryPosition + clientSize) / gridSize) * dimensionToExtent - 1);
}
}
}, {
key: "syncThreshold",
value: function syncThreshold(maxPos) {
var threshold = this.threshold;
if (threshold.max > maxPos) {
if (maxPos < threshold.base) {
threshold.max = threshold.base;
threshold.min = -Infinity;
} else {
threshold.max = maxPos;
threshold.min = maxPos - threshold.base;
}
}
}
// Native only
}, {
key: "scrollToPosition",
value: function scrollToPosition(x, y) {
var rtl = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.props.rtl;
if (this.containerRef.current) {
if (this.isPrimaryDirectionVertical) {
this.scrollPositionTarget = y;
} else {
this.scrollPositionTarget = x;
}
if (rtl) {
x = _platform.platform.ios || _platform.platform.safari || _platform.platform.chrome >= 85 || _platform.platform.androidChrome >= 85 ? -x : this.scrollBounds.maxLeft - x;
}
this.containerRef.current.scrollTo(x, y);
}
}
// JS only
}, {
key: "setScrollPosition",
value: function setScrollPosition(x, y) {
var rtl = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.props.rtl;
var targetX = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
var targetY = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
if (this.contentRef.current) {
this.contentRef.current.style.transform = "translate3d(".concat(rtl ? x : -x, "px, -").concat(y, "px, 0)");
// The `x`, `y` as parameters in scrollToPosition() are the position when stopping scrolling.
// But the `x`, `y` as parameters in setScrollPosition() are the position between current position and the position stopping scrolling.
// To know the position when stopping scrolling here, `targetX` and `targetY` are passed and cached in `this.scrollPositionTarget`.
if (this.isPrimaryDirectionVertical) {
this.scrollPositionTarget = targetY;
} else {
this.scrollPositionTarget = targetX;
}
this.didScroll(x, y);
}
}
}, {
key: "didScroll",
value: function didScroll(x, y) {
var _this$props3 = this.props,
dataSize = _this$props3.dataSize,
spacing = _this$props3.spacing,
itemSizes = _this$props3.itemSizes,
firstIndex = this.state.firstIndex,
isPrimaryDirectionVertical = this.isPrimaryDirectionVertical,
threshold = this.threshold,
dimensionToExtent = this.dimensionToExtent,
maxFirstIndex = this.maxFirstIndex,
scrollBounds = this.scrollBounds,
itemPositions = this.itemPositions,
_this$primary2 = this.primary,
clientSize = _this$primary2.clientSize,
gridSize = _this$primary2.gridSize,
maxPos = isPrimaryDirectionVertical ? scrollBounds.maxTop : scrollBounds.maxLeft;
var newFirstIndex = firstIndex,
index,
pos,
size,
itemPosition;
if (isPrimaryDirectionVertical) {
pos = y;
} else {
pos = x;
}
if (pos > threshold.max || pos < threshold.min) {
var newThresholdMin = -Infinity,
newThresholdMax = Infinity;
if (this.props.itemSizes) {
var overhangBefore = Math.floor(this.props.overhang / 2);
var firstRenderedIndex = -1;
// find an item which is known as placed the first rendered item's position
for (index = 0; index < dataSize; index += dimensionToExtent) {
itemPosition = itemPositions[index];
size = itemSizes[index];
if (itemPosition && size && itemPosition.position + size >= pos && itemPosition.position <= pos + clientSize) {
firstRenderedIndex = index;
break;
}
}
// found an item which is visible within a current viewport
if (index < dataSize) {
if (itemPosition.position <= pos) {
newFirstIndex = firstRenderedIndex - overhangBefore * dimensionToExtent;
newThresholdMin = itemPosition.position;
newThresholdMax = newThresholdMin + size + spacing;
} else {
var diffToFirstIndex = Math.ceil((itemPosition.position - pos) / gridSize);
newFirstIndex = firstRenderedIndex - (diffToFirstIndex + overhangBefore) * dimensionToExtent;
newThresholdMin = itemPosition.position - diffToFirstIndex * gridSize;
newThresholdMax = newThresholdMin + gridSize;
}
} else {
// calculate the first index based on assuming that all items have minimal size
var firstExtent = Math.max(0, Math.min(Math.floor(maxFirstIndex / dimensionToExtent), Math.floor((pos - gridSize * overhangBefore) / gridSize)));
newFirstIndex = firstExtent * dimensionToExtent;
newThresholdMin = (firstExtent + overhangBefore) * gridSize;
newThresholdMax = newThresholdMin + gridSize;
}
newFirstIndex = Math.max(0, Math.min(maxFirstIndex, newFirstIndex));
} else {
var _overhangBefore = Math.floor(this.props.overhang / 2),
_firstExtent = Math.max(0, Math.min(Math.floor(maxFirstIndex / dimensionToExtent), Math.floor((pos - gridSize * _overhangBefore) / gridSize)));
newFirstIndex = _firstExtent * dimensionToExtent;
newThresholdMin = (_firstExtent + _overhangBefore) * gridSize;
newThresholdMax = newThresholdMin + gridSize;
}
threshold.min = newFirstIndex === 0 ? -Infinity : newThresholdMin;
threshold.max = newFirstIndex === maxFirstIndex ? Infinity : newThresholdMax;
}
this.syncThreshold(maxPos);
this.scrollPosition = pos;
this.updateMoreInfo(dataSize, pos);
if (this.shouldUpdateBounds || firstIndex !== newFirstIndex) {
this.setState({
firstIndex: newFirstIndex
});
}
}
// For individually sized item
}, {
key: "calculateAndCacheItemPosition",
value: function calculateAndCacheItemPosition(index) {
var itemSizes = this.props.itemSizes;
if (!this.itemPositions[index] && itemSizes[index]) {
var spacing = this.props.spacing,
position = this.getItemTopPositionFromPreviousItemBottomPosition(index, spacing);
this.itemPositions[index] = {
position: position
};
}
}
// For individually sized item
}, {
key: "applyItemPositionToDOMElement",
value: function applyItemPositionToDOMElement(index) {
var _this$props4 = this.props,
direction = _this$props4.direction,
rtl = _this$props4.rtl,
numOfItems = this.state.numOfItems,
itemPositions = this.itemPositions,
childNode = this.itemContainerRef.current.children[index % numOfItems];
if (childNode && itemPositions[index]) {
var position = itemPositions[index].position;
if (direction === 'vertical') {
childNode.style.transform = "translate3d(0, ".concat(position, "px, 0)");
} else {
childNode.style.transform = "translate3d(".concat(position * (rtl ? -1 : 1), "px, 0, 0)");
}
}
}
// For individually sized item
}, {
key: "updateThresholdWithItemPosition",
value: function updateThresholdWithItemPosition() {
var overhang = this.props.overhang,
firstIndex = this.state.firstIndex,
maxFirstIndex = this.maxFirstIndex,
numOfUpperLine = Math.floor(overhang / 2);
this.threshold.min = firstIndex === 0 ? -Infinity : this.getItemBottomPosition(firstIndex + numOfUpperLine);
this.threshold.max = firstIndex === maxFirstIndex ? Infinity : this.getItemBottomPosition(firstIndex + (numOfUpperLine + 1));
}
// For individually sized item
}, {
key: "updateScrollBoundsWithItemPositions",
value: function updateScrollBoundsWithItemPositions() {
var _this$props5 = this.props,
dataSize = _this$props5.dataSize,
itemSizes = _this$props5.itemSizes,
spacing = _this$props5.spacing,
_this$state4 = this.state,
firstIndex = _this$state4.firstIndex,
numOfItems = _this$state4.numOfItems,
isPrimaryDirectionVertical = this.isPrimaryDirectionVertical,
itemPositions = this.itemPositions,
scrollBoundsDimension = isPrimaryDirectionVertical ? 'scrollHeight' : 'scrollWidth';
if (itemPositions.length === dataSize) {
// all item sizes are known
this.scrollBounds[scrollBoundsDimension] = itemSizes.reduce(function (acc, cur) {
return acc + cur;
}, 0) + (dataSize - 1) * spacing;
} else {
for (var index = firstIndex + numOfItems - 1; index < dataSize; index++) {
var nextInfo = itemPositions[index + 1];
if (!nextInfo) {
var endPosition = this.getItemBottomPosition(index);
if (endPosition > this.scrollBounds[scrollBoundsDimension]) {
this.scrollBounds[scrollBoundsDimension] = endPosition;
}
break;
}
}
}
this.scrollBounds.maxTop = Math.max(0, this.scrollBounds.scrollHeight - this.scrollBounds.clientHeight);
}
// For individually sized item
}, {
key: "adjustItemPositionWithItemSize",
value: function adjustItemPositionWithItemSize() {
if (this.itemContainerRef.current) {
var dataSize = this.props.dataSize,
_this$state5 = this.state,
firstIndex = _this$state5.firstIndex,
numOfItems = _this$state5.numOfItems,
lastIndex = firstIndex + numOfItems - 1;
// Cache individually sized item positions
// and adjust item DOM element positions
for (var index = firstIndex; index <= lastIndex; index++) {
this.calculateAndCacheItemPosition(index);
this.applyItemPositionToDOMElement(index);
}
// Update threshold based on this.itemPositions
this.updateThresholdWithItemPosition();
// Update scroll bounds based on this.itemPositions
this.updateScrollBoundsWithItemPositions();
// Set container size based on this.scrollbounds
this.setContainerSize();
// Update moreInfo based on this.itemPositions
this.updateMoreInfo(dataSize, this.scrollPosition);
}
}
}, {
key: "composeStyle",
value: function composeStyle(width, height, primaryPosition, secondaryPosition) {
var _this$getXY2 = this.getXY(primaryPosition, secondaryPosition),
x = _this$getXY2.x,
y = _this$getXY2.y,
style = {
position: 'absolute',
/* FIXME: RTL / this calculation only works for Chrome */
transform: "translate3d(".concat(this.props.rtl ? -x : x, "px, ").concat(y, "px, 0)")
};
if (this.isItemSized) {
style.width = width;
style.height = height;
}
return style;
}
}, {
key: "positionItems",
value: function positionItems() {
var _this$props6 = this.props,
dataSize = _this$props6.dataSize,
itemSizes = _this$props6.itemSizes,
_this$state6 = this.state,
firstIndex = _this$state6.firstIndex,
numOfItems = _this$state6.numOfItems,
cc = this.cc,
isPrimaryDirectionVertical = this.isPrimaryDirectionVertical,
dimensionToExtent = this.dimensionToExtent,
primary = this.primary,
secondary = this.secondary,
itemPositions = this.itemPositions;
var hideTo = 0,
updateFrom = cc.length ? this.state.updateFrom : firstIndex,
updateTo = cc.length ? this.state.updateTo : firstIndex + numOfItems;
if (updateFrom >= updateTo) {
return;
} else if (updateTo > dataSize) {
hideTo = updateTo;
updateTo = dataSize;
}
var width,
height,
_this$getGridPosition = this.getGridPosition(updateFrom),
primaryPosition = _this$getGridPosition.primaryPosition,
secondaryPosition = _this$getGridPosition.secondaryPosition;
width = (isPrimaryDirectionVertical ? secondary.itemSize : primary.itemSize) + 'px';
height = (isPrimaryDirectionVertical ? primary.itemSize : secondary.itemSize) + 'px';
// positioning items
for (var i = updateFrom, j = updateFrom % dimensionToExtent; i < updateTo; i++) {
this.applyStyleToNewNode(i, width, height, primaryPosition, secondaryPosition);
if (++j === dimensionToExtent) {
secondaryPosition = 0;
if (this.props.itemSizes) {
if (itemPositions[i + 1] || itemPositions[i + 1] === 0) {
primaryPosition = itemPositions[i + 1].position;
} else if (itemSizes[i]) {
primaryPosition += itemSizes[i] + this.props.spacing;
} else {
primaryPosition += primary.gridSize;
}
} else {
primaryPosition += primary.gridSize;
}
j = 0;
} else {
secondaryPosition += secondary.gridSize;
}
}
for (var _i2 = updateTo; _i2 < hideTo; _i2++) {
this.applyStyleToHideNode(_i2);
}
}
}, {
key: "getContainerClasses",
value:
// render
function getContainerClasses(className) {
var containerClass = null;
if (type === Native) {
containerClass = this.isPrimaryDirectionVertical ? _UiVirtualListModule["default"].vertical : _UiVirtualListModule["default"].horizontal;
}
return (0, _classnames["default"])(_UiVirtualListModule["default"].virtualList, containerClass, className);
}
}, {
key: "getContentClasses",
value: function getContentClasses() {
return type === Native ? null : _UiVirtualListModule["default"].content;
}
}, {
key: "render",
value: function render() {
var _this$props7 = this.props,
className = _this$props7.className,
containerProps = _this$props7.containerProps,
itemsRenderer = _this$props7.itemsRenderer,
style = _this$props7.style,
rest = _objectWithoutProperties(_this$props7, _excluded),
cc = this.cc,
itemContainerRef = this.itemContainerRef,
primary = this.primary,
containerClasses = this.getContainerClasses(className),
contentClasses = this.getContentClasses();
delete rest.cbScrollTo;
delete rest.childProps;
delete rest.clientSize;
delete rest.dataSize;
delete rest.direction;
delete rest.getComponentProps;
delete rest.isHorizontalScrollbarVisible;
delete rest.isVerticalScrollbarVisible;
delete rest.itemRenderer;
delete rest.itemSize;
delete rest.itemSizes;
delete rest.onUpdate;
delete rest.onUpdateItems;
delete rest.overhang;
delete rest.pageScroll;
delete rest.rtl;
delete rest.spacing;
delete rest.updateStatesAndBounds;
if (primary) {
this.positionItems();
}
return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", _objectSpread(_objectSpread({
className: containerClasses
}, containerProps), {}, {
ref: this.containerRef,
style: style,
children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", _objectSpread(_objectSpread({}, rest), {}, {
className: contentClasses,
ref: this.contentRef,
children: itemsRenderer({
cc: cc,
itemContainerRef: itemContainerRef,
primary: primary
})
}))
}));
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(props, state) {
var shouldInvalidate = state.prevFirstIndex === state.firstIndex || state.prevChildProps !== props.childProps,
diff = state.firstIndex - state.prevFirstIndex,
upd