UNPKG

react-window-reversed

Version:

React components for efficiently rendering large, scrollable lists and tabular data

1,260 lines (1,061 loc) 63.8 kB
import _extends from '@babel/runtime/helpers/esm/extends'; import _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose'; import _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized'; import memoizeOne from 'memoize-one'; import { createElement, PureComponent } from 'react'; var IS_SCROLLING_DEBOUNCE_INTERVAL = 150; var defaultItemKey = function defaultItemKey(_ref) { var columnIndex = _ref.columnIndex, rowIndex = _ref.rowIndex; return rowIndex + ":" + columnIndex; }; function createGridComponent(_ref2) { var _class, _temp; var getColumnOffset = _ref2.getColumnOffset, getColumnStartIndexForOffset = _ref2.getColumnStartIndexForOffset, getColumnStopIndexForStartIndex = _ref2.getColumnStopIndexForStartIndex, getColumnWidth = _ref2.getColumnWidth, getEstimatedTotalHeight = _ref2.getEstimatedTotalHeight, getEstimatedTotalWidth = _ref2.getEstimatedTotalWidth, getOffsetForColumnAndAlignment = _ref2.getOffsetForColumnAndAlignment, getOffsetForRowAndAlignment = _ref2.getOffsetForRowAndAlignment, getRowHeight = _ref2.getRowHeight, getRowOffset = _ref2.getRowOffset, getRowStartIndexForOffset = _ref2.getRowStartIndexForOffset, getRowStopIndexForStartIndex = _ref2.getRowStopIndexForStartIndex, initInstanceProps = _ref2.initInstanceProps, shouldResetStyleCacheOnItemSizeChange = _ref2.shouldResetStyleCacheOnItemSizeChange, validateProps = _ref2.validateProps; return _temp = _class = /*#__PURE__*/ function (_PureComponent) { _inheritsLoose(Grid, _PureComponent); // Always use explicit constructor for React components. // It produces less code after transpilation. (#26) // eslint-disable-next-line no-useless-constructor function Grid(props) { var _this; _this = _PureComponent.call(this, props) || this; _this._instanceProps = initInstanceProps(_this.props, _assertThisInitialized(_assertThisInitialized(_this))); _this._resetIsScrollingTimeoutId = null; _this._outerRef = void 0; _this.state = { isScrolling: false, horizontalScrollDirection: 'forward', scrollLeft: typeof _this.props.initialScrollLeft === 'number' ? _this.props.initialScrollLeft : 0, scrollTop: typeof _this.props.initialScrollTop === 'number' ? _this.props.initialScrollTop : 0, scrollUpdateWasRequested: false, verticalScrollDirection: 'forward' }; _this._callOnItemsRendered = void 0; _this._callOnItemsRendered = memoizeOne(function (overscanColumnStartIndex, overscanColumnStopIndex, overscanRowStartIndex, overscanRowStopIndex, visibleColumnStartIndex, visibleColumnStopIndex, visibleRowStartIndex, visibleRowStopIndex) { return _this.props.onItemsRendered({ overscanColumnStartIndex: overscanColumnStartIndex, overscanColumnStopIndex: overscanColumnStopIndex, overscanRowStartIndex: overscanRowStartIndex, overscanRowStopIndex: overscanRowStopIndex, visibleColumnStartIndex: visibleColumnStartIndex, visibleColumnStopIndex: visibleColumnStopIndex, visibleRowStartIndex: visibleRowStartIndex, visibleRowStopIndex: visibleRowStopIndex }); }); _this._callOnScroll = void 0; _this._callOnScroll = memoizeOne(function (scrollLeft, scrollTop, horizontalScrollDirection, verticalScrollDirection, scrollUpdateWasRequested) { return _this.props.onScroll({ horizontalScrollDirection: horizontalScrollDirection, scrollLeft: scrollLeft, scrollTop: scrollTop, verticalScrollDirection: verticalScrollDirection, scrollUpdateWasRequested: scrollUpdateWasRequested }); }); _this._getItemStyle = void 0; _this._getItemStyle = function (rowIndex, columnIndex) { var key = rowIndex + ":" + columnIndex; var itemStyleCache = _this._getItemStyleCache(shouldResetStyleCacheOnItemSizeChange && _this.props.columnWidth, shouldResetStyleCacheOnItemSizeChange && _this.props.rowHeight); var style; if (itemStyleCache.hasOwnProperty(key)) { style = itemStyleCache[key]; } else { itemStyleCache[key] = style = { position: 'absolute', left: getColumnOffset(_this.props, columnIndex, _this._instanceProps), top: getRowOffset(_this.props, rowIndex, _this._instanceProps), height: getRowHeight(_this.props, rowIndex, _this._instanceProps), width: getColumnWidth(_this.props, columnIndex, _this._instanceProps) }; } return style; }; _this._getItemStyleCache = void 0; _this._getItemStyleCache = memoizeOne(function (_, __) { return {}; }); _this._onScroll = function (event) { var _event$currentTarget = event.currentTarget, scrollLeft = _event$currentTarget.scrollLeft, scrollTop = _event$currentTarget.scrollTop; _this.setState(function (prevState) { if (prevState.scrollLeft === scrollLeft && prevState.scrollTop === scrollTop) { // Scroll position may have been updated by cDM/cDU, // In which case we don't need to trigger another render, // And we don't want to update state.isScrolling. return null; } return { isScrolling: true, horizontalScrollDirection: prevState.scrollLeft < scrollLeft ? 'forward' : 'backward', scrollLeft: scrollLeft, scrollTop: scrollTop, verticalScrollDirection: prevState.scrollTop < scrollTop ? 'forward' : 'backward', scrollUpdateWasRequested: false }; }, _this._resetIsScrollingDebounced); }; _this._outerRefSetter = function (ref) { var outerRef = _this.props.outerRef; _this._outerRef = ref; if (typeof outerRef === 'function') { outerRef(ref); } else if (outerRef != null && typeof outerRef === 'object' && outerRef.hasOwnProperty('current')) { outerRef.current = ref; } }; _this._resetIsScrollingDebounced = function () { if (_this._resetIsScrollingTimeoutId !== null) { clearTimeout(_this._resetIsScrollingTimeoutId); } _this._resetIsScrollingTimeoutId = setTimeout(_this._resetIsScrolling, IS_SCROLLING_DEBOUNCE_INTERVAL); }; _this._resetIsScrollingDebounced = function () { if (_this._resetIsScrollingTimeoutId !== null) { clearTimeout(_this._resetIsScrollingTimeoutId); } _this._resetIsScrollingTimeoutId = setTimeout(_this._resetIsScrolling, IS_SCROLLING_DEBOUNCE_INTERVAL); }; _this._resetIsScrolling = function () { _this._resetIsScrollingTimeoutId = null; _this.setState({ isScrolling: false }, function () { // Clear style cache after state update has been committed. // This way we don't break pure sCU for items that don't use isScrolling param. _this._getItemStyleCache(-1); }); }; return _this; } Grid.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) { validateSharedProps(nextProps); validateProps(nextProps); return null; }; var _proto = Grid.prototype; _proto.scrollTo = function scrollTo(_ref3) { var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop; this.setState(function (prevState) { if (scrollLeft === undefined) { scrollLeft = prevState.scrollLeft; } if (scrollTop === undefined) { scrollTop = prevState.scrollTop; } return { horizontalScrollDirection: prevState.scrollLeft < scrollLeft ? 'forward' : 'backward', scrollLeft: scrollLeft, scrollTop: scrollTop, scrollUpdateWasRequested: true, verticalScrollDirection: prevState.scrollTop < scrollTop ? 'forward' : 'backward' }; }, this._resetIsScrollingDebounced); }; _proto.scrollToItem = function scrollToItem(_ref4) { var _ref4$align = _ref4.align, align = _ref4$align === void 0 ? 'auto' : _ref4$align, columnIndex = _ref4.columnIndex, rowIndex = _ref4.rowIndex; var _this$state = this.state, scrollLeft = _this$state.scrollLeft, scrollTop = _this$state.scrollTop; this.scrollTo({ scrollLeft: getOffsetForColumnAndAlignment(this.props, columnIndex, align, scrollLeft, this._instanceProps), scrollTop: getOffsetForRowAndAlignment(this.props, rowIndex, align, scrollTop, this._instanceProps) }); }; _proto.componentDidMount = function componentDidMount() { var _this$props = this.props, initialScrollLeft = _this$props.initialScrollLeft, initialScrollTop = _this$props.initialScrollTop; if (typeof initialScrollLeft === 'number' && this._outerRef != null) { this._outerRef.scrollLeft = initialScrollLeft; } if (typeof initialScrollTop === 'number' && this._outerRef != null) { this._outerRef.scrollTop = initialScrollTop; } this._callPropsCallbacks(); }; _proto.componentDidUpdate = function componentDidUpdate() { var _this$state2 = this.state, scrollLeft = _this$state2.scrollLeft, scrollTop = _this$state2.scrollTop, scrollUpdateWasRequested = _this$state2.scrollUpdateWasRequested; if (scrollUpdateWasRequested && this._outerRef !== null) { this._outerRef.scrollLeft = scrollLeft; this._outerRef.scrollTop = scrollTop; } this._callPropsCallbacks(); }; _proto.componentWillUnmount = function componentWillUnmount() { if (this._resetIsScrollingTimeoutId !== null) { clearTimeout(this._resetIsScrollingTimeoutId); } }; _proto.render = function render() { var _this$props2 = this.props, children = _this$props2.children, className = _this$props2.className, columnCount = _this$props2.columnCount, height = _this$props2.height, innerRef = _this$props2.innerRef, innerTagName = _this$props2.innerTagName, itemData = _this$props2.itemData, _this$props2$itemKey = _this$props2.itemKey, itemKey = _this$props2$itemKey === void 0 ? defaultItemKey : _this$props2$itemKey, outerTagName = _this$props2.outerTagName, rowCount = _this$props2.rowCount, style = _this$props2.style, useIsScrolling = _this$props2.useIsScrolling, width = _this$props2.width; var isScrolling = this.state.isScrolling; var _this$_getHorizontalR = this._getHorizontalRangeToRender(), columnStartIndex = _this$_getHorizontalR[0], columnStopIndex = _this$_getHorizontalR[1]; var _this$_getVerticalRan = this._getVerticalRangeToRender(), rowStartIndex = _this$_getVerticalRan[0], rowStopIndex = _this$_getVerticalRan[1]; var items = []; if (columnCount > 0 && rowCount) { for (var _rowIndex = rowStartIndex; _rowIndex <= rowStopIndex; _rowIndex++) { for (var _columnIndex = columnStartIndex; _columnIndex <= columnStopIndex; _columnIndex++) { items.push(createElement(children, { columnIndex: _columnIndex, data: itemData, isScrolling: useIsScrolling ? isScrolling : undefined, key: itemKey({ columnIndex: _columnIndex, rowIndex: _rowIndex }), rowIndex: _rowIndex, style: this._getItemStyle(_rowIndex, _columnIndex) })); } } } // Read this value AFTER items have been created, // So their actual sizes (if variable) are taken into consideration. var estimatedTotalHeight = getEstimatedTotalHeight(this.props, this._instanceProps); var estimatedTotalWidth = getEstimatedTotalWidth(this.props, this._instanceProps); return createElement(outerTagName, { className: className, onScroll: this._onScroll, ref: this._outerRefSetter, style: _extends({ position: 'relative', height: height, width: width, overflow: 'auto', WebkitOverflowScrolling: 'touch', willChange: 'transform' }, style) }, createElement(innerTagName, { children: items, ref: innerRef, style: { height: estimatedTotalHeight, pointerEvents: isScrolling ? 'none' : '', width: estimatedTotalWidth } })); }; _proto._callPropsCallbacks = function _callPropsCallbacks() { var _this$props3 = this.props, columnCount = _this$props3.columnCount, onItemsRendered = _this$props3.onItemsRendered, onScroll = _this$props3.onScroll, rowCount = _this$props3.rowCount; if (typeof onItemsRendered === 'function') { if (columnCount > 0 && rowCount > 0) { var _this$_getHorizontalR2 = this._getHorizontalRangeToRender(), _overscanColumnStartIndex = _this$_getHorizontalR2[0], _overscanColumnStopIndex = _this$_getHorizontalR2[1], _visibleColumnStartIndex = _this$_getHorizontalR2[2], _visibleColumnStopIndex = _this$_getHorizontalR2[3]; var _this$_getVerticalRan2 = this._getVerticalRangeToRender(), _overscanRowStartIndex = _this$_getVerticalRan2[0], _overscanRowStopIndex = _this$_getVerticalRan2[1], _visibleRowStartIndex = _this$_getVerticalRan2[2], _visibleRowStopIndex = _this$_getVerticalRan2[3]; this._callOnItemsRendered(_overscanColumnStartIndex, _overscanColumnStopIndex, _overscanRowStartIndex, _overscanRowStopIndex, _visibleColumnStartIndex, _visibleColumnStopIndex, _visibleRowStartIndex, _visibleRowStopIndex); } } if (typeof onScroll === 'function') { var _this$state3 = this.state, _horizontalScrollDirection = _this$state3.horizontalScrollDirection, _scrollLeft = _this$state3.scrollLeft, _scrollTop = _this$state3.scrollTop, _scrollUpdateWasRequested = _this$state3.scrollUpdateWasRequested, _verticalScrollDirection = _this$state3.verticalScrollDirection; this._callOnScroll(_scrollLeft, _scrollTop, _horizontalScrollDirection, _verticalScrollDirection, _scrollUpdateWasRequested); } }; // Lazily create and cache item styles while scrolling, // So that pure component sCU will prevent re-renders. // We maintain this cache, and pass a style prop rather than index, // So that List can clear cached styles and force item re-render if necessary. _proto._getHorizontalRangeToRender = function _getHorizontalRangeToRender() { var _this$props4 = this.props, columnCount = _this$props4.columnCount, overscanCount = _this$props4.overscanCount, rowCount = _this$props4.rowCount; var _this$state4 = this.state, horizontalScrollDirection = _this$state4.horizontalScrollDirection, scrollLeft = _this$state4.scrollLeft; if (columnCount === 0 || rowCount === 0) { return [0, 0, 0, 0]; } var startIndex = getColumnStartIndexForOffset(this.props, scrollLeft, this._instanceProps); var stopIndex = getColumnStopIndexForStartIndex(this.props, startIndex, scrollLeft, this._instanceProps); // Overscan by one item in each direction so that tab/focus works. // If there isn't at least one extra item, tab loops back around. var overscanBackward = horizontalScrollDirection === 'backward' ? Math.max(1, overscanCount) : 1; var overscanForward = horizontalScrollDirection === 'forward' ? Math.max(1, overscanCount) : 1; return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(columnCount - 1, stopIndex + overscanForward)), startIndex, stopIndex]; }; _proto._getVerticalRangeToRender = function _getVerticalRangeToRender() { var _this$props5 = this.props, columnCount = _this$props5.columnCount, rowCount = _this$props5.rowCount, overscanCount = _this$props5.overscanCount; var _this$state5 = this.state, verticalScrollDirection = _this$state5.verticalScrollDirection, scrollTop = _this$state5.scrollTop; if (columnCount === 0 || rowCount === 0) { return [0, 0, 0, 0]; } var startIndex = getRowStartIndexForOffset(this.props, scrollTop, this._instanceProps); var stopIndex = getRowStopIndexForStartIndex(this.props, startIndex, scrollTop, this._instanceProps); // Overscan by one item in each direction so that tab/focus works. // If there isn't at least one extra item, tab loops back around. var overscanBackward = verticalScrollDirection === 'backward' ? Math.max(1, overscanCount) : 1; var overscanForward = verticalScrollDirection === 'forward' ? Math.max(1, overscanCount) : 1; return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(rowCount - 1, stopIndex + overscanForward)), startIndex, stopIndex]; }; return Grid; }(PureComponent), _class.defaultProps = { innerTagName: 'div', itemData: undefined, outerTagName: 'div', overscanCount: 1, useIsScrolling: false }, _temp; } var validateSharedProps = function validateSharedProps(_ref5) { var children = _ref5.children, height = _ref5.height, width = _ref5.width; if (process.env.NODE_ENV !== 'production') { if (children == null) { throw Error('An invalid "children" prop has been specified. ' + 'Value should be a React component. ' + ("\"" + (children === null ? 'null' : typeof children) + "\" was specified.")); } if (typeof width !== 'number') { throw Error('An invalid "width" prop has been specified. ' + 'Grids must specify a number for width. ' + ("\"" + (width === null ? 'null' : typeof width) + "\" was specified.")); } if (typeof height !== 'number') { throw Error('An invalid "height" prop has been specified. ' + 'Grids must specify a number for height. ' + ("\"" + (height === null ? 'null' : typeof height) + "\" was specified.")); } } }; var DEFAULT_ESTIMATED_ITEM_SIZE = 50; var getEstimatedTotalHeight = function getEstimatedTotalHeight(_ref, _ref2) { var rowCount = _ref.rowCount; var rowMetadataMap = _ref2.rowMetadataMap, estimatedRowHeight = _ref2.estimatedRowHeight, lastMeasuredRowIndex = _ref2.lastMeasuredRowIndex; var totalSizeOfMeasuredRows = 0; if (lastMeasuredRowIndex >= 0) { var itemMetadata = rowMetadataMap[lastMeasuredRowIndex]; totalSizeOfMeasuredRows = itemMetadata.offset + itemMetadata.size; } var numUnmeasuredItems = rowCount - lastMeasuredRowIndex - 1; var totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedRowHeight; return totalSizeOfMeasuredRows + totalSizeOfUnmeasuredItems; }; var getEstimatedTotalWidth = function getEstimatedTotalWidth(_ref3, _ref4) { var columnCount = _ref3.columnCount; var columnMetadataMap = _ref4.columnMetadataMap, estimatedColumnWidth = _ref4.estimatedColumnWidth, lastMeasuredColumnIndex = _ref4.lastMeasuredColumnIndex; var totalSizeOfMeasuredRows = 0; if (lastMeasuredColumnIndex >= 0) { var itemMetadata = columnMetadataMap[lastMeasuredColumnIndex]; totalSizeOfMeasuredRows = itemMetadata.offset + itemMetadata.size; } var numUnmeasuredItems = columnCount - lastMeasuredColumnIndex - 1; var totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedColumnWidth; return totalSizeOfMeasuredRows + totalSizeOfUnmeasuredItems; }; var getItemMetadata = function getItemMetadata(itemType, props, index, instanceProps) { var itemMetadataMap, itemSize, lastMeasuredIndex; if (itemType === 'column') { itemMetadataMap = instanceProps.columnMetadataMap; itemSize = props.columnWidth; lastMeasuredIndex = instanceProps.lastMeasuredColumnIndex; } else { itemMetadataMap = instanceProps.rowMetadataMap; itemSize = props.rowHeight; lastMeasuredIndex = instanceProps.lastMeasuredRowIndex; } if (index > lastMeasuredIndex) { var offset = 0; if (lastMeasuredIndex >= 0) { var itemMetadata = itemMetadataMap[lastMeasuredIndex]; offset = itemMetadata.offset + itemMetadata.size; } for (var i = lastMeasuredIndex + 1; i <= index; i++) { var size = itemSize(i); itemMetadataMap[i] = { offset: offset, size: size }; offset += size; } if (itemType === 'column') { instanceProps.lastMeasuredColumnIndex = index; } else { instanceProps.lastMeasuredRowIndex = index; } } return itemMetadataMap[index]; }; var findNearestItem = function findNearestItem(itemType, props, instanceProps, offset) { var itemMetadataMap, lastMeasuredIndex; if (itemType === 'column') { itemMetadataMap = instanceProps.columnMetadataMap; lastMeasuredIndex = instanceProps.lastMeasuredColumnIndex; } else { itemMetadataMap = instanceProps.rowMetadataMap; lastMeasuredIndex = instanceProps.lastMeasuredRowIndex; } var lastMeasuredItemOffset = lastMeasuredIndex > 0 ? itemMetadataMap[lastMeasuredIndex].offset : 0; if (lastMeasuredItemOffset >= offset) { // If we've already measured items within this range just use a binary search as it's faster. return findNearestItemBinarySearch(itemType, props, instanceProps, lastMeasuredIndex, 0, offset); } else { // If we haven't yet measured this high, fallback to an exponential search with an inner binary search. // The exponential search avoids pre-computing sizes for the full set of items as a binary search would. // The overall complexity for this approach is O(log n). return findNearestItemExponentialSearch(itemType, props, instanceProps, Math.max(0, lastMeasuredIndex), offset); } }; var findNearestItemBinarySearch = function findNearestItemBinarySearch(itemType, props, instanceProps, high, low, offset) { while (low <= high) { var middle = low + Math.floor((high - low) / 2); var currentOffset = getItemMetadata(itemType, props, middle, instanceProps).offset; if (currentOffset === offset) { return middle; } else if (currentOffset < offset) { low = middle + 1; } else if (currentOffset > offset) { high = middle - 1; } } if (low > 0) { return low - 1; } else { return 0; } }; var findNearestItemExponentialSearch = function findNearestItemExponentialSearch(itemType, props, instanceProps, index, offset) { var itemCount = itemType === 'column' ? props.columnCount : props.rowCount; var interval = 1; while (index < itemCount && getItemMetadata(itemType, props, index, instanceProps).offset < offset) { index += interval; interval *= 2; } return findNearestItemBinarySearch(itemType, props, instanceProps, Math.min(index, itemCount - 1), Math.floor(index / 2), offset); }; var getOffsetForIndexAndAlignment = function getOffsetForIndexAndAlignment(itemType, props, index, align, scrollOffset, instanceProps) { var size = itemType === 'column' ? props.width : props.height; var itemMetadata = getItemMetadata(itemType, props, index, instanceProps); // Get estimated total size after ItemMetadata is computed, // To ensure it reflects actual measurements instead of just estimates. var estimatedTotalSize = itemType === 'column' ? getEstimatedTotalWidth(props, instanceProps) : getEstimatedTotalHeight(props, instanceProps); var maxOffset = Math.max(0, Math.min(estimatedTotalSize - size, itemMetadata.offset)); var minOffset = Math.max(0, itemMetadata.offset - size + itemMetadata.size); switch (align) { case 'start': return maxOffset; case 'end': return minOffset; case 'center': return Math.round(minOffset + (maxOffset - minOffset) / 2); case 'auto': default: if (scrollOffset >= minOffset && scrollOffset <= maxOffset) { return scrollOffset; } else if (scrollOffset - minOffset < maxOffset - scrollOffset) { return minOffset; } else { return maxOffset; } } }; var VariableSizeGrid = /*#__PURE__*/ createGridComponent({ getColumnOffset: function getColumnOffset(props, index, instanceProps) { return getItemMetadata('column', props, index, instanceProps).offset; }, getColumnStartIndexForOffset: function getColumnStartIndexForOffset(props, scrollLeft, instanceProps) { return findNearestItem('column', props, instanceProps, scrollLeft); }, getColumnStopIndexForStartIndex: function getColumnStopIndexForStartIndex(props, startIndex, scrollLeft, instanceProps) { var columnCount = props.columnCount, width = props.width; var itemMetadata = getItemMetadata('column', props, startIndex, instanceProps); var maxOffset = scrollLeft + width; var offset = itemMetadata.offset + itemMetadata.size; var stopIndex = startIndex; while (stopIndex < columnCount - 1 && offset < maxOffset) { stopIndex++; offset += getItemMetadata('column', props, stopIndex, instanceProps).size; } return stopIndex; }, getColumnWidth: function getColumnWidth(props, index, instanceProps) { return instanceProps.columnMetadataMap[index].size; }, getEstimatedTotalHeight: getEstimatedTotalHeight, getEstimatedTotalWidth: getEstimatedTotalWidth, getOffsetForColumnAndAlignment: function getOffsetForColumnAndAlignment(props, index, align, scrollOffset, instanceProps) { return getOffsetForIndexAndAlignment('column', props, index, align, scrollOffset, instanceProps); }, getOffsetForRowAndAlignment: function getOffsetForRowAndAlignment(props, index, align, scrollOffset, instanceProps) { return getOffsetForIndexAndAlignment('row', props, index, align, scrollOffset, instanceProps); }, getRowOffset: function getRowOffset(props, index, instanceProps) { return getItemMetadata('row', props, index, instanceProps).offset; }, getRowHeight: function getRowHeight(props, index, instanceProps) { return instanceProps.rowMetadataMap[index].size; }, getRowStartIndexForOffset: function getRowStartIndexForOffset(props, scrollTop, instanceProps) { return findNearestItem('row', props, instanceProps, scrollTop); }, getRowStopIndexForStartIndex: function getRowStopIndexForStartIndex(props, startIndex, scrollTop, instanceProps) { var rowCount = props.rowCount, height = props.height; var itemMetadata = getItemMetadata('row', props, startIndex, instanceProps); var maxOffset = scrollTop + height; var offset = itemMetadata.offset + itemMetadata.size; var stopIndex = startIndex; while (stopIndex < rowCount - 1 && offset < maxOffset) { stopIndex++; offset += getItemMetadata('row', props, stopIndex, instanceProps).size; } return stopIndex; }, initInstanceProps: function initInstanceProps(props, instance) { var _ref5 = props, estimatedColumnWidth = _ref5.estimatedColumnWidth, estimatedRowHeight = _ref5.estimatedRowHeight; var instanceProps = { columnMetadataMap: {}, estimatedColumnWidth: estimatedColumnWidth || DEFAULT_ESTIMATED_ITEM_SIZE, estimatedRowHeight: estimatedRowHeight || DEFAULT_ESTIMATED_ITEM_SIZE, lastMeasuredColumnIndex: -1, lastMeasuredRowIndex: -1, rowMetadataMap: {} }; instance.resetAfterColumnIndex = function (columnIndex, shouldForceUpdate) { if (shouldForceUpdate === void 0) { shouldForceUpdate = true; } instance.resetAfterIndices({ columnIndex: columnIndex, shouldForceUpdate: shouldForceUpdate }); }; instance.resetAfterRowIndex = function (rowIndex, shouldForceUpdate) { if (shouldForceUpdate === void 0) { shouldForceUpdate = true; } instance.resetAfterIndices({ rowIndex: rowIndex, shouldForceUpdate: shouldForceUpdate }); }; instance.resetAfterIndices = function (_ref6) { var columnIndex = _ref6.columnIndex, rowIndex = _ref6.rowIndex, _ref6$shouldForceUpda = _ref6.shouldForceUpdate, shouldForceUpdate = _ref6$shouldForceUpda === void 0 ? true : _ref6$shouldForceUpda; if (typeof columnIndex === 'number') { instanceProps.lastMeasuredColumnIndex = Math.min(instanceProps.lastMeasuredColumnIndex, columnIndex - 1); } if (typeof rowIndex === 'number') { instanceProps.lastMeasuredRowIndex = Math.min(instanceProps.lastMeasuredRowIndex, rowIndex - 1); } // We could potentially optimize further by only evicting styles after this index, // But since styles are only cached while scrolling is in progress- // It seems an unnecessary optimization. // It's unlikely that resetAfterIndex() will be called while a user is scrolling. instance._getItemStyleCache(-1); if (shouldForceUpdate) { instance.forceUpdate(); } }; return instanceProps; }, shouldResetStyleCacheOnItemSizeChange: false, validateProps: function validateProps(_ref7) { var columnWidth = _ref7.columnWidth, rowHeight = _ref7.rowHeight; if (process.env.NODE_ENV !== 'production') { if (typeof columnWidth !== 'function') { throw Error('An invalid "columnWidth" prop has been specified. ' + 'Value should be a function. ' + ("\"" + (columnWidth === null ? 'null' : typeof columnWidth) + "\" was specified.")); } else if (typeof rowHeight !== 'function') { throw Error('An invalid "rowHeight" prop has been specified. ' + 'Value should be a function. ' + ("\"" + (rowHeight === null ? 'null' : typeof rowHeight) + "\" was specified.")); } } } }); var IS_SCROLLING_DEBOUNCE_INTERVAL$1 = 150; var REVERSE_HORIZONTAL_MATRIX = 'matrix(-1, 0, 0, 1, 0, 0)'; var REVERSE_VERTICAL_MATRIX = 'matrix(1, 0, 0, -1, 0, 0)'; var defaultItemKey$1 = function defaultItemKey(index) { return index; }; function createListComponent(_ref) { var _class, _temp; var getItemOffset = _ref.getItemOffset, getEstimatedTotalSize = _ref.getEstimatedTotalSize, getItemSize = _ref.getItemSize, getOffsetForIndexAndAlignment = _ref.getOffsetForIndexAndAlignment, getStartIndexForOffset = _ref.getStartIndexForOffset, getStopIndexForStartIndex = _ref.getStopIndexForStartIndex, initInstanceProps = _ref.initInstanceProps, shouldResetStyleCacheOnItemSizeChange = _ref.shouldResetStyleCacheOnItemSizeChange, validateProps = _ref.validateProps; return _temp = _class = /*#__PURE__*/ function (_PureComponent) { _inheritsLoose(List, _PureComponent); var _proto = List.prototype; _proto._getScrollLength = function _getScrollLength(elem) { var scrollHeight = elem.scrollHeight, scrollWidth = elem.scrollWidth, clientHeight = elem.clientHeight, clientWidth = elem.clientWidth, scrollTop = elem.scrollTop, scrollLeft = elem.scrollLeft; return { scrollHeight: scrollHeight, scrollWidth: scrollWidth, clientHeight: clientHeight, clientWidth: clientWidth, scrollTop: scrollTop, scrollLeft: scrollLeft, scrollBottom: scrollHeight - clientHeight - scrollTop, scrollRight: scrollWidth - clientWidth - scrollLeft }; }; _proto._setScrollLeft = function _setScrollLeft(elem, scrollLeft) { var scrollWidth = elem.scrollWidth, clientWidth = elem.clientWidth; elem.scrollLeft = Math.min(scrollWidth - clientWidth, Math.max(0, scrollLeft)); }; _proto._setScrollRight = function _setScrollRight(elem, scrollRight) { var scrollWidth = elem.scrollWidth, clientWidth = elem.clientWidth; this._setScrollLeft(elem, scrollWidth - clientWidth - Math.max(0, scrollRight)); }; _proto._setScrollTop = function _setScrollTop(elem, scrollTop) { var scrollHeight = elem.scrollHeight, clientHeight = elem.clientHeight; elem.scrollTop = Math.min(scrollHeight - clientHeight, Math.max(0, scrollTop)); }; _proto._setScrollBottom = function _setScrollBottom(elem, scrollBottom) { var scrollHeight = elem.scrollHeight, clientHeight = elem.clientHeight; this._setScrollTop(elem, scrollHeight - clientHeight - Math.max(0, scrollBottom)); }; _proto._maybeSetScrollOffset = function _maybeSetScrollOffset(scrollOffset) { if (this._outerRef !== null) { var elem = this._outerRef; var _this$props = this.props, direction = _this$props.direction, reversed = _this$props.reversed; if (direction === 'horizontal') { if (reversed) { this._setScrollRight(elem, scrollOffset); } else { this._setScrollLeft(elem, scrollOffset); } } else { if (reversed) { this._setScrollBottom(elem, scrollOffset); } else { this._setScrollTop(elem, scrollOffset); } } } }; // Always use explicit constructor for React components. // It produces less code after transpilation. (#26) // eslint-disable-next-line no-useless-constructor function List(props) { var _this; _this = _PureComponent.call(this, props) || this; _this._instanceProps = initInstanceProps(_this.props, _assertThisInitialized(_assertThisInitialized(_this))); _this._outerRef = void 0; _this._resetIsScrollingTimeoutId = null; _this.state = { isScrolling: false, scrollDirection: 'forward', scrollOffset: typeof _this.props.initialScrollOffset === 'number' ? _this.props.initialScrollOffset : 0, scrollUpdateWasRequested: false }; _this._callOnItemsRendered = void 0; _this._callOnItemsRendered = memoizeOne(function (overscanStartIndex, overscanStopIndex, visibleStartIndex, visibleStopIndex) { return _this.props.onItemsRendered({ overscanStartIndex: overscanStartIndex, overscanStopIndex: overscanStopIndex, visibleStartIndex: visibleStartIndex, visibleStopIndex: visibleStopIndex }); }); _this._callOnScroll = void 0; _this._callOnScroll = memoizeOne(function (scrollDirection, scrollOffset, scrollUpdateWasRequested) { return _this.props.onScroll({ scrollDirection: scrollDirection, scrollOffset: scrollOffset, scrollUpdateWasRequested: scrollUpdateWasRequested }); }); _this._getItemStyle = void 0; _this._getItemStyle = function (index) { var _this$props2 = _this.props, direction = _this$props2.direction, itemSize = _this$props2.itemSize, reversed = _this$props2.reversed; var itemStyleCache = _this._getItemStyleCache(shouldResetStyleCacheOnItemSizeChange && itemSize); var style; if (itemStyleCache.hasOwnProperty(index)) { style = itemStyleCache[index]; } else { style = { position: 'absolute', left: direction === 'horizontal' ? getItemOffset(_this.props, index, _this._instanceProps) : 0, top: direction === 'vertical' ? getItemOffset(_this.props, index, _this._instanceProps) : 0, height: direction === 'vertical' ? getItemSize(_this.props, index, _this._instanceProps) : '100%', width: direction === 'horizontal' ? getItemSize(_this.props, index, _this._instanceProps) : '100%', transform: '' }; if (reversed) { style.transform = direction === 'horizontal' ? REVERSE_HORIZONTAL_MATRIX // horizontally reverse : REVERSE_VERTICAL_MATRIX; // vertically reverse } itemStyleCache[index] = style; } return style; }; _this._getItemStyleCache = void 0; _this._getItemStyleCache = memoizeOne(function (_) { return {}; }); _this._onScrollHorizontal = function (event) { var target = event.currentTarget; var _this$_getScrollLengt = _this._getScrollLength(target), scrollLeft = _this$_getScrollLengt.scrollLeft, scrollRight = _this$_getScrollLengt.scrollRight; var reversed = _this.props.reversed; var scrollOffset = reversed ? scrollRight : scrollLeft; _this.setState(function (prevState) { if (prevState.scrollOffset === scrollOffset) { // Scroll position may have been updated by cDM/cDU, // In which case we don't need to trigger another render, // And we don't want to update state.isScrolling. return null; } return { isScrolling: true, scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward', scrollOffset: scrollOffset, scrollUpdateWasRequested: false }; }, _this._resetIsScrollingDebounced); }; _this._onScrollVertical = function (event) { var target = event.currentTarget; var _this$_getScrollLengt2 = _this._getScrollLength(target), scrollTop = _this$_getScrollLengt2.scrollTop, scrollBottom = _this$_getScrollLengt2.scrollBottom; var reversed = _this.props.reversed; var scrollOffset = reversed ? scrollBottom : scrollTop; _this.setState(function (prevState) { if (prevState.scrollOffset === scrollOffset) { // Scroll position may have been updated by cDM/cDU, // In which case we don't need to trigger another render, // And we don't want to update state.isScrolling. return null; } return { isScrolling: true, scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward', scrollOffset: scrollOffset, scrollUpdateWasRequested: false }; }, _this._resetIsScrollingDebounced); }; _this._outerRefSetter = function (ref) { var outerRef = _this.props.outerRef; _this._outerRef = ref; if (typeof outerRef === 'function') { outerRef(ref); } else if (outerRef != null && typeof outerRef === 'object' && outerRef.hasOwnProperty('current')) { outerRef.current = ref; } }; _this._resetIsScrollingDebounced = function () { if (_this._resetIsScrollingTimeoutId !== null) { clearTimeout(_this._resetIsScrollingTimeoutId); } _this._resetIsScrollingTimeoutId = setTimeout(_this._resetIsScrolling, IS_SCROLLING_DEBOUNCE_INTERVAL$1); }; _this._resetIsScrolling = function () { _this._resetIsScrollingTimeoutId = null; _this.setState({ isScrolling: false }, function () { // Clear style cache after state update has been committed. // This way we don't break pure sCU for items that don't use isScrolling param. _this._getItemStyleCache(-1); }); }; return _this; } List.getDerivedStateFromProps = function getDerivedStateFromProps(props, state) { validateSharedProps$1(props); validateProps(props); return null; }; _proto.scrollTo = function scrollTo(scrollOffset) { this.setState(function (prevState) { return { scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward', scrollOffset: scrollOffset, scrollUpdateWasRequested: true }; }, this._resetIsScrollingDebounced); }; _proto.scrollToItem = function scrollToItem(index, align) { if (align === void 0) { align = 'auto'; } var scrollOffset = this.state.scrollOffset; this.scrollTo(getOffsetForIndexAndAlignment(this.props, index, align, scrollOffset, this._instanceProps)); }; _proto.componentDidMount = function componentDidMount() { var initialScrollOffset = this.props.initialScrollOffset; if (typeof initialScrollOffset === 'number') { this._maybeSetScrollOffset(initialScrollOffset); } this._callPropsCallbacks(); }; _proto.componentDidUpdate = function componentDidUpdate() { var _this$state = this.state, scrollOffset = _this$state.scrollOffset, scrollUpdateWasRequested = _this$state.scrollUpdateWasRequested; /*if (scrollUpdateWasRequested && this._outerRef !== null) { if (direction === 'horizontal') { ((this._outerRef: any): HTMLDivElement).scrollLeft = scrollOffset; } else { ((this._outerRef: any): HTMLDivElement).scrollTop = scrollOffset; } }*/ // if (scrollUpdateWasRequested) { this._maybeSetScrollOffset(scrollOffset); // } this._callPropsCallbacks(); }; _proto.componentWillUnmount = function componentWillUnmount() { if (this._resetIsScrollingTimeoutId !== null) { clearTimeout(this._resetIsScrollingTimeoutId); } }; _proto.render = function render() { var _this$props3 = this.props, children = _this$props3.children, className = _this$props3.className, direction = _this$props3.direction, reversed = _this$props3.reversed, height = _this$props3.height, innerRef = _this$props3.innerRef, innerTagName = _this$props3.innerTagName, itemCount = _this$props3.itemCount, itemData = _this$props3.itemData, _this$props3$itemKey = _this$props3.itemKey, itemKey = _this$props3$itemKey === void 0 ? defaultItemKey$1 : _this$props3$itemKey, outerTagName = _this$props3.outerTagName, style = _this$props3.style, useIsScrolling = _this$props3.useIsScrolling, width = _this$props3.width; var isScrolling = this.state.isScrolling; var onScroll = direction === 'vertical' ? this._onScrollVertical : this._onScrollHorizontal; var _this$_getRangeToRend = this._getRangeToRender(), startIndex = _this$_getRangeToRend[0], stopIndex = _this$_getRangeToRend[1]; var items = []; if (itemCount > 0) { for (var _index = startIndex; _index <= stopIndex; _index++) { items.push(createElement(children, { data: itemData, key: itemKey(_index), index: _index, isScrolling: useIsScrolling ? isScrolling : undefined, style: this._getItemStyle(_index) })); } } // Read this value AFTER items have been created, // So their actual sizes (if variable) are taken into consideration. var estimatedTotalSize = getEstimatedTotalSize(this.props, this._instanceProps); return createElement(outerTagName, { className: className, onScroll: onScroll, ref: this._outerRefSetter, style: _extends({ position: 'relative', height: height, width: width, overflow: 'auto', WebkitOverflowScrolling: 'touch', willChange: 'transform' }, style) }, createElement(innerTagName, { children: items, ref: innerRef, style: { height: direction === 'horizontal' ? '100%' : estimatedTotalSize, pointerEvents: isScrolling ? 'none' : '', width: direction === 'horizontal' ? estimatedTotalSize : '100%', transform: reversed ? direction === 'horizontal' ? REVERSE_HORIZONTAL_MATRIX : REVERSE_VERTICAL_MATRIX : '' } })); }; _proto._callPropsCallbacks = function _callPropsCallbacks() { if (typeof this.props.onItemsRendered === 'function') { var itemCount = this.props.itemCount; if (itemCount > 0) { var _this$_getRangeToRend2 = this._getRangeToRender(), _overscanStartIndex = _this$_getRangeToRend2[0], _overscanStopIndex = _this$_getRangeToRend2[1], _visibleStartIndex = _this$_getRangeToRend2[2], _visibleStopIndex = _this$_getRangeToRend2[3]; this._callOnItemsRendered(_overscanStartIndex, _overscanStopIndex, _visibleStartIndex, _visibleStopIndex); } } if (typeof this.props.onScroll === 'function') { var _this$state2 = this.state, _scrollDirection = _this$state2.scrollDirection, _scrollOffset = _this$state2.scrollOffset, _scrollUpdateWasRequested = _this$state2.scrollUpdateWasRequested; this._callOnScroll(_scrollDirection, _scrollOffset, _scrollUpdateWasRequested); } }; // Lazily create and cache item styles while scrolling, // So that pure component sCU will prevent re-renders. // We maintain this cache, and pass a style prop rather than index, // So that List can clear cached styles and force item re-render if necessary. _proto._getRangeToRender = function _getRangeToRender() { var _this$props4 = this.props, itemCount = _this$props4.itemCount, overscanCount = _this$props4.overscanCount; var _this$state3 = this.state, scrollDirection = _this$state3.scrollDirection, scrollOffset = _this$state3.scrollOffset; if (itemCount === 0) { return [0, 0, 0, 0]; } var startIndex = getStartIndexForOffset(this.props, scrollOffset, this._instanceProps); var stopIndex = getStopIndexForStartIndex(this.props, startIndex, scrollOffset, this._instanceProps); // Overscan by one item in each direction so that tab/focus works. // If there isn't at least one extra item, tab loops back around. var overscanBackward = scrollDirection === 'backward' ? Math.max(1, overscanCount) : 1; var overscanForward = scrollDirection === 'forward' ? Math.max(1, overscanCount) : 1; return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(itemCount - 1, stopIndex + overscanForward)), startIndex, stopIndex]; }; return List; }(PureComponent), _class.defaultProps = { direction: 'vertical', reversed: false, innerTagName: 'div', itemData: undefined, outerTagName: 'div', overscanCount: 2, useIsScrolling: false }, _temp; } // NOTE: I considered further wrapping individual items with a pure ListItem component. // This would avoid ever calling the render function for the same index more than once, // But it would also add the overhead of a lot of components/fibers. // I assume people already do this (render function returning a class component), // So my doing it would just unnecessarily double the wrappers. var validateSharedProps$1 = function validateSharedProps(_ref2) { var children = _ref2.children, direction = _ref2.direction, height = _ref2.height, width = _ref2.width; if (process.env.NODE_ENV !== 'production') { if (direction !== 'horizontal' && direction !== 'vertical') { throw Error('An invalid "direction" prop has been specified. ' + 'Value should be either "horizontal" or "vertical". ' + ("\"" + direction + "\" was specified.")); } if (children == null) { throw Error('An invalid "children" prop has been specified. ' + 'Value should be a React component. ' + ("\"" + (children === null ? 'null' : typeof children) + "\" was specified.")); } if (direction === 'horizontal' && typeof width !== 'number') { throw Error('An invalid "width" prop has been specified. ' + 'Horizontal lists must specify a number for width. ' + ("\"" + (width === null ? 'null' : typeof width) + "\" was specified.")); } else if (direction === 'vertical' && typeof height !== 'number') { throw Error('An invalid "height" prop has been specified. ' + 'Vertical lists must specify a number for height. ' + ("\"" + (height === null ? 'null' : typeof height) + "\" was specified.")); } } }; var DEFAULT_ESTIMATED_ITEM_SIZE$1 = 50; var getItemMetadata$1 = function getItemMetadata(props, index, instanceProps) { var _ref = props, itemSize = _ref.itemSize, onUpdateMetadata = _ref.onUpdateMetadata; var itemMetadataMap = instanceProps.itemMetadataMap, lastMeasuredIndex = instanceProps.lastMeasuredIndex; if (index > lastMeasuredIndex) { var offset = 0; if (lastMeasuredIndex >= 0) { var itemMetadata = itemMetadataMap[lastMeasuredIndex]; offset = itemMetadata.offset + itemMetadata.size; } for (var i = lastMeasuredIndex + 1; i <= index; i++) { var size = itemSize(i); itemMetadataMap[i] = { offset: offset, size: size }; offset += size; } instanceProps.lastMeasuredIndex = index; if (onUpdateMetadata) { onUpdateMetadata({ itemMetadataMap: itemMetadataMap, lastMeasuredIndex: lastMeasuredIndex }); } } return itemMetadataMap[index]; }; var findNearestItem$1 = function findNearestItem(props, instanceProps, offset) { var itemMetadataMap = instanceProps.itemMetadataMap, lastMeasuredIndex = instanceProps.lastMeasuredIndex; var lastMeasuredItemOffset = lastMeasuredIndex > 0 ? itemMetadataMap[lastMeasuredIndex].offset : 0; if (lastMeasuredItemOffset >= offset) { // If we've already measured items within this range just use a binary search as it's faster. return findNearestItemBinarySearch$1(props, instanceProps, lastMeasuredIndex, 0, offset);