UNPKG

@enact/ui

Version:

A collection of simplified unstyled cross-platform UI components for Enact

1,113 lines (1,083 loc) 55.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.itemSizesShape = exports.gridListItemSizeShape = exports["default"] = exports.VirtualListBasic = void 0; var _classnames = _interopRequireDefault(require("classnames")); var _propTypes = _interopRequireDefault(require("@enact/core/internal/prop-types")); var _handle = require("@enact/core/handle"); var _platform = require("@enact/core/platform"); var _util = require("@enact/core/util"); var _propTypes2 = _interopRequireDefault(require("prop-types")); var _equals = _interopRequireDefault(require("ramda/src/equals")); var _react = require("react"); var _VirtualListModule = _interopRequireDefault(require("./VirtualList.module.css")); var _jsxRuntime = require("react/jsx-runtime"); var _excluded = ["className", "containerProps", "placeholderRenderer", "role", "style", "scrollMode"]; function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } 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(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 _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 _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); } 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); } var nop = function nop() {}; /** * The shape for the grid list item size * in a list for {@link ui/VirtualList.VirtualGridList|VirtualGridList}. * * @typedef {Object} gridListItemSizeShape * @memberof ui/VirtualList * @property {Number} minWidth The minimum width of the grid list item. * @property {Number} minHeight The minimum height of the grid list item. * @public */ var gridListItemSizeShape = exports.gridListItemSizeShape = _propTypes2["default"].shape({ minHeight: _propTypes2["default"].number.isRequired, minWidth: _propTypes2["default"].number.isRequired }); /** * The shape for the list different item size * in a list for {@link ui/VirtualList.VirtualList|VirtualList}. * * @typedef {Object} itemSizesShape * @memberof ui/VirtualList * @property {Number} minSize The minimum size of the list item. * @property {Number[]} size An array of the list item size. If it is not defined, the list items will render with the `minSize` size. * @public */ var itemSizesShape = exports.itemSizesShape = _propTypes2["default"].shape({ minSize: _propTypes2["default"].number.isRequired, size: _propTypes2["default"].arrayOf(_propTypes2["default"].number) }); /** * A basic base component for * {@link ui/VirtualList.VirtualList|VirtualList} and {@link ui/VirtualList.VirtualGridList|VirtualGridList}. * * @class VirtualListBasic * @memberof ui/VirtualList * @ui * @public */ var VirtualListBasic = exports.VirtualListBasic = /*#__PURE__*/function (_Component) { function VirtualListBasic(_props) { var _this; _classCallCheck(this, VirtualListBasic); _this = _callSuper(this, VirtualListBasic, [_props]); _this.displayName = 'ui:VirtualListBasic'; _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; _this.scrollToPositionTarget = -1; // For individually sized item _this.itemPositions = []; _this.indexToScrollIntoView = -1; _this.updateScrollPosition = function (_ref, behavior) { var x = _ref.x, y = _ref.y; if (_this.props.scrollMode === 'native') { _this.scrollToPosition(x, y, behavior); } else { _this.setScrollPositionTarget(x, y); _this.setScrollPosition(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; }; _this.getCenterItemIndexFromScrollPosition = function (scrollPosition) { return Math.floor((scrollPosition + _this.primary.clientSize / 2) / _this.primary.gridSize) * _this.dimensionToExtent + Math.floor(_this.dimensionToExtent / 2); }; // 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 optionalOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var disallowNegativeOffset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var _this2 = _this, isPrimaryDirectionVertical = _this2.isPrimaryDirectionVertical, primary = _this2.primary, scrollBounds = _this2.scrollBounds; var maxPos = isPrimaryDirectionVertical ? scrollBounds.maxTop : scrollBounds.maxLeft; var position = _this.getGridPosition(index); var offset = 0; if (stickTo === 'start') { // 'start' offset = optionalOffset; } else if (_this.props.itemSizes) { // 'end' for different item sizes offset = primary.clientSize - _this.props.itemSizes[index] - optionalOffset; } else if (stickTo === 'center') { // 'center' offset = primary.clientSize / 2 - primary.gridSize / 2 - optionalOffset; } else { // 'end' for same item sizes offset = primary.clientSize - primary.itemSize - optionalOffset; } /* istanbul ignore next */ if (disallowNegativeOffset) { offset = Math.max(0, offset); } position.primaryPosition = (0, _util.clamp)(0, maxPos, 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, _this3 = _this, dimensionToExtent = _this3.dimensionToExtent, primary = _this3.primary, moreInfo = _this3.moreInfo, scrollPosition = _this3.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'; } }; // scrollMode 'native' only _this.getRtlPositionX = function (x) { if (_this.props.rtl) { return _platform.platform.chrome < 85 ? _this.scrollBounds.maxLeft - x : -x; } return x; }; _this.applyStyleToNewNode = function (index) { var _this4; var _this$props = _this.props, childProps = _this$props.childProps, itemRefs = _this$props.itemRefs, itemRenderer = _this$props.itemRenderer, getComponentProps = _this$props.getComponentProps, key = index % _this.state.numOfItems, componentProps = getComponentProps && getComponentProps(index) || {}, itemContainerRef = function itemContainerRef(ref) { if (ref === null) { itemRefs.current[key] = ref; } else { var itemNode = ref.children[0]; itemRefs.current[key] = parseInt(itemNode.dataset.index) === index ? itemNode : ref.querySelector("[data-index=\"".concat(index, "\"]")); _this.itemContainerRefs[key] = ref; } }; 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, _jsxRuntime.jsx)("div", { className: _VirtualListModule["default"].listItem, ref: itemContainerRef, role: "presentation", style: (_this4 = _this).composeStyle.apply(_this4, rest), children: itemRenderer(_objectSpread(_objectSpread(_objectSpread({}, childProps), componentProps), {}, { index: index })) }, key); }; _this.applyStyleToHideNode = function (index) { var itemRefs = _this.props.itemRefs, key = index % _this.state.numOfItems, itemContainerRef = function itemContainerRef() { return itemRefs.current[key] = null; }; _this.cc[key] = /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { ref: itemContainerRef, style: { display: 'none' } }, key); }; _this.getScrollHeight = function () { return _this.isPrimaryDirectionVertical ? _this.getVirtualScrollDimension() + _this.props.getAffordance() : _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 _this5 = _this, dimensionToExtent = _this5.dimensionToExtent, primary = _this5.primary, curDataSize = _this5.curDataSize, spacing = _this.props.spacing; return Math.ceil(curDataSize / dimensionToExtent) * primary.gridSize - spacing; } }; _this.syncClientSize = function () { var _this6 = _this, props = _this6.props, node = _this.props.scrollContentRef.current; if (!props.clientSize && !node) { return false; } var _ref3 = props.clientSize || _this.getClientSize(node), clientWidth = _ref3.clientWidth, clientHeight = _ref3.clientHeight, _this7 = _this, scrollBounds = _this7.scrollBounds; if (clientWidth !== scrollBounds.clientWidth || clientHeight !== scrollBounds.clientHeight) { _this.calculateMetrics(props); _this.setState(_this.getStatesAndUpdateBounds(props)); _this.setContainerSize(); return true; } return false; }; _this.contentRef = /*#__PURE__*/(0, _react.createRef)(); _this.itemContainerRefs = []; _this.state = { firstIndex: 0, numOfItems: 0, prevChildProps: null, prevFirstIndex: 0, updateFrom: 0, updateTo: 0 }; if (_props.clientSize) { _this.calculateMetrics(_props); Object.assign(_this.state, _this.getStatesAndUpdateBounds(_props)); } return _this; } _inherits(VirtualListBasic, _Component); return _createClass(VirtualListBasic, [{ 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 useScroll 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) || !this.hasDataSizeChanged && !(0, _util.shallowEqual)(prevProps.itemSizes, this.props.itemSizes)) { 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 }, 'instant'); 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), 'instant'); } var maxPos = this.isPrimaryDirectionVertical ? this.scrollBounds.maxTop : this.scrollBounds.maxLeft; var currentPos = this.scrollPosition; if (this.props.scrollMode === 'native' && this.scrollToPositionTarget >= 0) { currentPos = this.scrollToPositionTarget; } if (!deferScrollTo && currentPos > maxPos) { this.props.cbScrollTo({ position: this.isPrimaryDirectionVertical ? { y: maxPos } : { x: maxPos }, animate: false }); this.scrollToPositionTarget = -1; } } }, { 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, scrollMode = props.scrollMode, spacing = props.spacing, node = this.props.scrollContentRef.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; this.scrollToPositionTarget = -1; if (scrollMode === 'translate' && this.contentRef.current) { this.contentRef.current.style.transform = null; } else if (scrollMode === 'native' && node) { this.updateScrollPosition(this.getXY(this.scrollPosition, 0), 'instant'); } } }, { 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.props.scrollContentRef.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; } } } }, { key: "scrollToPosition", value: // scrollMode 'native' only function scrollToPosition(left, top, behavior) { if (this.props.scrollContentRef.current && this.props.scrollContentRef.current.scrollTo) { this.props.scrollContentRef.current.scrollTo({ left: this.getRtlPositionX(left), top: top, behavior: behavior }); } } // scrollMode 'native' only }, { key: "setScrollToPositionTarget", value: function setScrollToPositionTarget(x, y) { if (this.isPrimaryDirectionVertical) { this.scrollToPositionTarget = y; } else { this.scrollToPositionTarget = x; } } // scrollMode 'translate' only }, { key: "setScrollPositionTarget", value: function setScrollPositionTarget(x, y) { // The `left`, `top` 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 properly, `x` and `y` are passed and cached in `this.scrollPositionTarget`. if (this.isPrimaryDirectionVertical) { this.scrollPositionTarget = y; } else { this.scrollPositionTarget = x; } } // scrollMode 'translate' only }, { key: "setScrollPosition", value: function setScrollPosition(x, y) { var rtl = this.props.rtl; if (this.contentRef.current) { this.contentRef.current.style.transform = "translate3d(".concat(rtl ? x : -x, "px, -").concat(y, "px, 0)"); 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.itemContainerRefs[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.cc.length) { 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 = { /* 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: "render", value: // render function render() { var _this$props7 = this.props, className = _this$props7.className, containerProps = _this$props7.containerProps, placeholderRenderer = _this$props7.placeholderRenderer, role = _this$props7.role, style = _this$props7.style, scrollMode = _this$props7.scrollMode, rest = _objectWithoutProperties(_this$props7, _excluded), cc = this.cc, isPrimaryDirectionVertical = this.isPrimaryDirectionVertical, primary = this.primary, scrollModeNative = scrollMode === 'native', containerClasses = (0, _classnames["default"])(_VirtualListModule["default"].virtualList, isPrimaryDirectionVertical ? _VirtualListModule["default"].vertical : _VirtualListModule["default"].horizontal, _defineProperty({}, _VirtualListModule["default"]["native"], scrollModeNative), className), contentClasses = scrollModeNative ? null : _VirtualListModule["default"].content; delete rest.cbScrollTo; delete rest.childProps; delete rest.clientSize; delete rest.dataSize; delete rest.direction; delete rest.getAffordance; delete rest.getComponentProps; delete rest.isHorizontalScrollbarVisible; delete rest.isVerticalScrollbarVisible; delete rest.itemRefs; 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.scrollContainerContainsDangerously; delete rest.scrollContentRef; delete rest.scrollMode; delete rest.setThemeScrollContentHandle; delete rest.spacing; delete rest.updateStatesAndBounds; if (primary) { this.positionItems(); } return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", _objectSpread(_objectSpread({ className: containerClasses }, containerProps), {}, { ref: this.props.scrollContentRef, style: style, children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", _objectSpread(_objectSpread({}, rest), {}, { className: contentClasses, ref: this.contentRef, role: role, children: [].concat(_toConsumableArray(cc), [placeholderRenderer && placeholderRenderer(primary)]) })) })); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(props, state) { var shouldInvalidate = state.prevFirstIndex === state.firstIndex || state.prevChildProps !== props.childProps, diff = state.firstIndex - state.prevFirstIndex, updateTo = -state.numOfItems >= diff || diff > 0 || shouldInvalidate ? state.firstIndex + state.numOfItems : state.prevFirstIndex, updateFrom = 0 >= diff || diff >= state.numOfItems || shouldInvalidate ? state.fi