From db8d3aa69484fb10f1475ada0d8dfec55a215a38 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Wed, 25 Nov 2026 15:26:17 +0100 Subject: [PATCH] Stop VirtualizedList re-laying out forever after a width change After the list's width changes while it is scrolled down, rows whose height depends on the width (wrapping text, aspectRatio) made the list fire onContentSizeChange and move its render window forever. The rows that stay mounted are measured again at the new width, but the first row of the spacer below them keeps the offset it had at the old width, so the spacer starts away from where the mounted rows end. Every row after it moves, the list renders another window, and the spacer moves again. ListMetricsAggregator now forgets the metrics of unmounted cells when the list was resized and a mounted cell changes length together with its cross-axis length, and estimates unmeasured cells from the measured cells around them instead of averageLength * index. Each change alone still loops. A cell that changes size while the list keeps its size doesn't affect the metrics of the other cells. --- .../Lists/__tests__/FlatList-itest.js | 187 +++++++++++ .../Lists/ListMetricsAggregator.js | 259 ++++++++++++-- .../Lists/VirtualizedList.js | 4 + .../__tests__/ListMetricsAggregator-test.js | 316 ++++++++++++++++++ 4 files changed, 739 insertions(+), 27 deletions(-) diff --git a/packages/react-native/Libraries/Lists/__tests__/FlatList-itest.js b/packages/react-native/Libraries/Lists/__tests__/FlatList-itest.js index 6d36654fb6ed..1de205343700 100644 --- a/packages/react-native/Libraries/Lists/__tests__/FlatList-itest.js +++ b/packages/react-native/Libraries/Lists/__tests__/FlatList-itest.js @@ -821,6 +821,193 @@ describe('', () => { }); }); + describe('rows whose height depends on the list width', () => { + // Rows that are not mounted when the width changes keep their metrics + // from the old width. Mixed with the new metrics of the mounted rows, they + // made the spacer after the rows kept by initialNumToRender start + // somewhere other than where those rows end, so the rows after it moved on + // every layout and the content size never stopped changing. + const ASPECT_RATIOS = [1.5, 2, 3]; + const DATA = Array.from({length: 200}, (_, i) => ({key: String(i)})); + + for (const [initialWidth, newWidth] of [ + [674, 381], + [381, 674], + ]) { + it(`settle after the width changes from ${initialWidth} to ${newWidth} while scrolled deep`, () => { + const root = Fantom.createRoot({ + viewportWidth: 800, + viewportHeight: 900, + }); + const flatListRef = createRef>(); + let contentSizeChanges = 0; + const render = (width: number) => + Fantom.runTask(() => { + root.render( + + } + renderItem={({index}) => ( + + + + )} + onContentSizeChange={() => { + contentSizeChanges++; + }} + /> + , + ); + }); + + const timers = Fantom.installTimerMock(); + try { + // Delivers layout and lets batched renders run until the content + // size stops changing, and returns whether it did. + const settle = (): boolean => { + const MAX_STEPS = 50; + const QUIET_STEPS = 5; + let quietSteps = 0; + for (let step = 0; step < MAX_STEPS; step++) { + const changesBefore = contentSizeChanges; + Fantom.flushAllNativeEvents(); + timers.advanceTimersByTime(100); + quietSteps = + contentSizeChanges === changesBefore ? quietSteps + 1 : 0; + if (quietSteps === QUIET_STEPS) { + return true; + } + } + return false; + }; + + render(initialWidth); + expect(settle()).toBe(true); + + // Scroll far enough that the rows after the ones kept by + // initialNumToRender unmount. + const scrollView = nullthrows( + nullthrows(flatListRef.current).getNativeScrollRef(), + ); + for (let y = 2000; y <= 30000; y += 2000) { + Fantom.scrollTo(scrollView, {x: 0, y, zoomScale: 1}); + expect(settle()).toBe(true); + } + + render(newWidth); + expect(settle()).toBe(true); + } finally { + timers.uninstall(); + } + }); + } + }); + + it('keeps the size of the rows after the window when one row grows on its own', () => { + // A row that changes size while the list keeps its width doesn't change + // how the other rows lay out, so the list keeps the metrics of the rows + // that aren't mounted, and the spacer after the window keeps its size. + const ROW_HEIGHT = 50; + const DATA = Array.from({length: 200}, (_, i) => ({key: String(i)})); + const root = Fantom.createRoot({viewportWidth: 400, viewportHeight: 500}); + const flatListRef = createRef>(); + let contentHeight = 0; + const render = (firstRowSize: number) => + Fantom.runTask(() => { + root.render( + ( + + )} + onContentSizeChange={(width, height) => { + contentHeight = height; + }} + />, + ); + }); + + const timers = Fantom.installTimerMock(); + try { + const settle = () => { + for (let step = 0; step < 10; step++) { + Fantom.flushAllNativeEvents(); + timers.advanceTimersByTime(100); + } + }; + + render(ROW_HEIGHT); + settle(); + + // Scroll to the end, so that every row is measured, and back to the top. + const scrollView = nullthrows( + nullthrows(flatListRef.current).getNativeScrollRef(), + ); + for (let y = 500; y <= DATA.length * ROW_HEIGHT - 500; y += 500) { + Fantom.scrollTo(scrollView, {x: 0, y, zoomScale: 1}); + settle(); + } + Fantom.scrollTo(scrollView, {x: 0, y: 0, zoomScale: 1}); + settle(); + expect(contentHeight).toBe(DATA.length * ROW_HEIGHT); + + // The rows after the window keep the offsets they were measured at + // until they are measured again, so the content can stay short by the + // height row 0 gained, but not lose those rows. + render(2 * ROW_HEIGHT); + settle(); + expect(contentHeight).toBeGreaterThanOrEqual(DATA.length * ROW_HEIGHT); + } finally { + timers.uninstall(); + } + }); + + it('does not throw when the data is replaced with fewer items after scrolling', () => { + // Cells measured past the end of the new data must not be used to + // estimate the cells that are not measured yet. + const root = Fantom.createRoot({viewportWidth: 400, viewportHeight: 400}); + const flatListRef = createRef>(); + const render = (keyPrefix: string, length: number) => + Fantom.runTask(() => { + root.render( + ({key: `${keyPrefix}${i}`}))} + renderItem={() => } + windowSize={3} + />, + ); + }); + + render('a', 270); + Fantom.flushAllNativeEvents(); + Fantom.scrollTo( + nullthrows(nullthrows(flatListRef.current).getNativeScrollRef()), + {x: 0, y: 5000, zoomScale: 1}, + ); + Fantom.flushAllNativeEvents(); + + render('b', 20); + expect(() => Fantom.flushAllNativeEvents()).not.toThrow(); + }); + describe('imperative methods', () => { const ITEM_HEIGHT = 50; type Item = {key: string, title: string}; diff --git a/packages/virtualized-lists/Lists/ListMetricsAggregator.js b/packages/virtualized-lists/Lists/ListMetricsAggregator.js index b0516e6f7af1..16abb5bcd777 100644 --- a/packages/virtualized-lists/Lists/ListMetricsAggregator.js +++ b/packages/virtualized-lists/Lists/ListMetricsAggregator.js @@ -53,6 +53,11 @@ export type CellMetricProps = { ... }; +// How many measured cells whose metrics no longer match the cell at their +// index (because `data` changed) to skip when looking for the nearest measured +// cells around an unmeasured one. +const MAX_MISMATCHED_CELLS_TO_SKIP = 10; + /** * Provides an interface to query information about the metrics of a list and its cells. */ @@ -60,9 +65,17 @@ export default class ListMetricsAggregator { _averageCellLength = 0; _cellMetrics: Map = new Map(); _contentLength: ?number; + // Cross-axis lengths of each cell in `_cellMetrics` and of the list when the + // cell was last laid out. + _cellCrossAxisLengths: Map = new Map(); _highestMeasuredCellIndex = 0; + _listLayout: ?{width: number, height: number}; _measuredCellsLength = 0; _measuredCellsCount = 0; + // Indices of the cells in `_cellMetrics`, ascending, without duplicates, to + // find the nearest measured cells around an unmeasured one. + _measuredCellIndices: Array = []; + _measuredCellIndexCounts: Map = new Map(); _orientation: ListOrientation = { horizontal: false, rtl: false, @@ -92,7 +105,30 @@ export default class ListMetricsAggregator { isMounted: true, offset: this.flowRelativeOffset(layout), }; - const curr = this._cellMetrics.get(cellKey); + const crossAxisLength = this._selectCrossAxisLength(layout); + const listCrossAxisLength = this._getListCrossAxisLength(); + const prevCrossAxisLengths = this._cellCrossAxisLengths.get(cellKey); + let curr = this._cellMetrics.get(cellKey); + + if ( + curr != null && + prevCrossAxisLengths != null && + prevCrossAxisLengths.list !== listCrossAxisLength && + prevCrossAxisLengths.cell !== crossAxisLength && + curr.length !== next.length + ) { + // The list was resized since the cell was last laid out, and the cell + // changed length with its cross-axis length (e.g. text wrapping or an + // aspect ratio). Cells that are not mounted would change too, but keep + // the metrics they had at the old size. A cell that changes size while + // the list keeps its size doesn't change the other cells. + this._invalidateUnmountedCells(listCrossAxisLength); + curr = this._cellMetrics.get(cellKey); + } + this._cellCrossAxisLengths.set(cellKey, { + cell: crossAxisLength, + list: listCrossAxisLength, + }); if (!curr || next.offset !== curr.offset || next.length !== curr.length) { if (curr) { @@ -114,6 +150,12 @@ export default class ListMetricsAggregator { } else { this._averageCellLength = 0; } + if (!curr) { + this._addMeasuredCellIndex(cellIndex); + } else if (curr.index !== cellIndex) { + this._removeMeasuredCellIndex(curr.index); + this._addMeasuredCellIndex(cellIndex); + } this._cellMetrics.set(cellKey, next); this._highestMeasuredCellIndex = Math.max( this._highestMeasuredCellIndex, @@ -136,6 +178,20 @@ export default class ListMetricsAggregator { } } + /** + * Notify ListMetricsAggregator that the list itself has been laid out. + */ + notifyListLayout({ + orientation, + layout, + }: { + orientation: ListOrientation, + layout: Readonly<{width: number, height: number, ...}>, + }): void { + this._invalidateIfOrientationChanged(orientation); + this._listLayout = {width: layout.width, height: layout.height}; + } + /** * Notify ListMetricsAggregator that the lists content container has been laid out. */ @@ -167,8 +223,10 @@ export default class ListMetricsAggregator { /** * Returns the exact metrics of a cell if it has already been laid out, - * otherwise an estimate based on the average length of previously measured - * cells + * otherwise an estimate from the measured cells around it: an even share of + * the space between the nearest measured cells before and after it, or else + * the average length of measured cells, starting where the nearest measured + * cell before it ends */ getCellMetricsApprox(index: number, props: CellMetricProps): CellMetrics { const frame = this.getCellMetrics(index, props); @@ -176,28 +234,24 @@ export default class ListMetricsAggregator { // check for invalid frames due to row re-ordering return frame; } else { - let offset; - - const highestMeasuredCellIndex = this.getHighestMeasuredCellIndex(); - if (highestMeasuredCellIndex < index) { - // If any of the cells before this one have been laid out already, we - // should use that information in the estimations. - // This is important because if the list has a header, the initial cell - // will have a larger offset that we should take into account here. - const highestMeasuredCellFrame = this.getCellMetrics( - highestMeasuredCellIndex, - props, - ); - if (highestMeasuredCellFrame) { - offset = - highestMeasuredCellFrame.offset + - highestMeasuredCellFrame.length + - this._averageCellLength * (index - highestMeasuredCellIndex - 1); + // Estimate from the measured cells around this one rather than from the + // start of the list, so that the estimate accounts for anything before + // the cells (e.g. a list header) and lines up with the cells around it. + // Otherwise a spacer for unmeasured cells would not span the space + // between the rendered cells around it, and would move every cell after + // it. + let offset = this._averageCellLength * index; + let length = this._averageCellLength; + const prevFrame = this._getMeasuredCellNear(index, -1, props); + if (prevFrame != null) { + const prevEnd = prevFrame.offset + prevFrame.length; + const nextFrame = this._getMeasuredCellNear(index, 1, props); + if (nextFrame != null && nextFrame.offset >= prevEnd) { + length = + (nextFrame.offset - prevEnd) / + (nextFrame.index - prevFrame.index - 1); } - } - - if (offset == null) { - offset = this._averageCellLength * index; + offset = prevEnd + length * (index - prevFrame.index - 1); } const {data, getItemCount} = props; @@ -206,7 +260,7 @@ export default class ListMetricsAggregator { 'Tried to get frame for out of range index ' + index, ); return { - length: this._averageCellLength, + length, offset, index, isMounted: false, @@ -311,13 +365,151 @@ export default class ListMetricsAggregator { } } + /** + * Forgets the metrics of cells that are not mounted and were laid out when + * the list had a different cross-axis length, so that they are estimated + * until they are measured again. + */ + _invalidateUnmountedCells(listCrossAxisLength: ?number): void { + let highestMeasuredCellIndex = 0; + for (const [cellKey, metrics] of this._cellMetrics) { + if ( + metrics.isMounted || + this._cellCrossAxisLengths.get(cellKey)?.list === listCrossAxisLength + ) { + highestMeasuredCellIndex = Math.max( + highestMeasuredCellIndex, + metrics.index, + ); + } else { + this._cellMetrics.delete(cellKey); + this._cellCrossAxisLengths.delete(cellKey); + this._decrementMeasuredCellIndexCount(metrics.index); + this._measuredCellsLength -= metrics.length; + this._measuredCellsCount -= 1; + } + } + // Removing each index from the sorted array separately would shift the + // rest of the array every time. + this._measuredCellIndices = this._measuredCellIndices.filter(index => + this._measuredCellIndexCounts.has(index), + ); + + if (this._measuredCellsCount > 0) { + this._averageCellLength = + this._measuredCellsLength / this._measuredCellsCount; + } else { + this._averageCellLength = 0; + this._measuredCellsLength = 0; + } + this._highestMeasuredCellIndex = highestMeasuredCellIndex; + } + + /** + * Returns the metrics of the nearest measured cell before (`direction` -1) + * or after (`direction` 1) `index`, if any + */ + _getMeasuredCellNear( + index: number, + direction: -1 | 1, + props: CellMetricProps, + ): ?CellMetrics { + const indices = this._measuredCellIndices; + // Metrics stay keyed to the index a cell was measured at until it is + // measured again, so after `data` changes some of them no longer match the + // cell at that index, or are past the end of `data`. Skip a few of those, + // but don't scan every cell. + const itemCount = props.getItemCount(props.data); + let i = + direction < 0 + ? this._lowerBoundMeasuredCellIndex(index) - 1 + : this._lowerBoundMeasuredCellIndex(index + 1); + for ( + let tries = 0; + tries <= MAX_MISMATCHED_CELLS_TO_SKIP && + i >= 0 && + i < indices.length && + indices[i] < itemCount; + tries++, i += direction + ) { + const frame = this.getCellMetrics(indices[i], props); + if (frame != null) { + return frame; + } + } + return null; + } + + _addMeasuredCellIndex(index: number): void { + const count = this._measuredCellIndexCounts.get(index) ?? 0; + this._measuredCellIndexCounts.set(index, count + 1); + if (count === 0) { + this._measuredCellIndices.splice( + this._lowerBoundMeasuredCellIndex(index), + 0, + index, + ); + } + } + + _removeMeasuredCellIndex(index: number): void { + if (this._decrementMeasuredCellIndexCount(index)) { + this._measuredCellIndices.splice( + this._lowerBoundMeasuredCellIndex(index), + 1, + ); + } + } + + /** + * Returns whether no measured cell is left at `index`, in which case it + * must be removed from `_measuredCellIndices` + */ + _decrementMeasuredCellIndexCount(index: number): boolean { + const count = this._measuredCellIndexCounts.get(index) ?? 0; + if (count > 1) { + this._measuredCellIndexCounts.set(index, count - 1); + return false; + } else if (count === 1) { + this._measuredCellIndexCounts.delete(index); + return true; + } + return false; + } + + /** + * Returns the position of the first entry in `_measuredCellIndices` that is + * not below `index` + */ + _lowerBoundMeasuredCellIndex(index: number): number { + const indices = this._measuredCellIndices; + let low = 0; + let high = indices.length; + while (low < high) { + const mid = low + Math.floor((high - low) / 2); + if (indices[mid] < index) { + low = mid + 1; + } else { + high = mid; + } + } + return low; + } + + _clearCellMetrics(): void { + this._cellMetrics.clear(); + this._cellCrossAxisLengths.clear(); + this._measuredCellIndices = []; + this._measuredCellIndexCounts.clear(); + } + _invalidateIfOrientationChanged(orientation: ListOrientation): void { if (orientation.rtl !== this._orientation.rtl) { - this._cellMetrics.clear(); + this._clearCellMetrics(); } if (orientation.horizontal !== this._orientation.horizontal) { - this._cellMetrics.clear(); + this._clearCellMetrics(); this._averageCellLength = 0; this._contentLength = null; this._highestMeasuredCellIndex = 0; @@ -335,6 +527,19 @@ export default class ListMetricsAggregator { return this._orientation.horizontal ? width : height; } + _selectCrossAxisLength({ + width, + height, + }: Readonly<{width: number, height: number, ...}>): number { + return this._orientation.horizontal ? height : width; + } + + _getListCrossAxisLength(): ?number { + return this._listLayout != null + ? this._selectCrossAxisLength(this._listLayout) + : null; + } + _selectOffset({x, y}: Readonly<{x: number, y: number, ...}>): number { return this._orientation.horizontal ? x : y; } diff --git a/packages/virtualized-lists/Lists/VirtualizedList.js b/packages/virtualized-lists/Lists/VirtualizedList.js index b58f45976f1c..69a704783340 100644 --- a/packages/virtualized-lists/Lists/VirtualizedList.js +++ b/packages/virtualized-lists/Lists/VirtualizedList.js @@ -1669,6 +1669,10 @@ class VirtualizedList extends StateSafePureComponent< } _onLayout = (e: LayoutChangeEvent) => { + this._listMetrics.notifyListLayout({ + layout: e.nativeEvent.layout, + orientation: this._orientation(), + }); this._scrollMetrics.crossAxisLength = this._selectCrossAxisLength( e.nativeEvent.layout, ); diff --git a/packages/virtualized-lists/Lists/__tests__/ListMetricsAggregator-test.js b/packages/virtualized-lists/Lists/__tests__/ListMetricsAggregator-test.js index 36b50e88e867..eb1da4ed4b9a 100644 --- a/packages/virtualized-lists/Lists/__tests__/ListMetricsAggregator-test.js +++ b/packages/virtualized-lists/Lists/__tests__/ListMetricsAggregator-test.js @@ -246,6 +246,123 @@ describe('ListMetricsAggregator', () => { }); }); + it('estimates unmeasured cells from the measured cells around them', () => { + const listMetrics = new ListMetricsAggregator(); + const orientation = {horizontal: false, rtl: false}; + const props: CellMetricProps = { + data: [1, 2, 3, 4, 5, 6], + getItemCount: () => nullthrows(props.data).length, + getItem: (i: number) => nullthrows(props.data)[i], + }; + + // The cells start after a 100-long header, and cells 2, 3 and 5 have not + // been measured. + for (const [index, y, height] of [ + [0, 100, 10], + [1, 110, 20], + [4, 200, 30], + ]) { + listMetrics.notifyCellLayout({ + cellIndex: index, + cellKey: String(index), + orientation, + layout: {height, width: 5, x: 0, y}, + }); + } + + // Cells 2 and 3 share the space between cells 1 and 4. + expect(listMetrics.getCellMetricsApprox(2, props)).toEqual({ + index: 2, + length: 35, + offset: 130, + isMounted: false, + }); + expect(listMetrics.getCellMetricsApprox(3, props)).toEqual({ + index: 3, + length: 35, + offset: 165, + isMounted: false, + }); + // Cell 5 has the average length and starts where cell 4 ends. + expect(listMetrics.getCellMetricsApprox(5, props)).toEqual({ + index: 5, + length: 20, + offset: 230, + isMounted: false, + }); + }); + + it('estimates around cells measured again at a new index', () => { + const listMetrics = new ListMetricsAggregator(); + const orientation = {horizontal: false, rtl: false}; + const props: CellMetricProps = { + data: ['a', 'b'], + getItemCount: () => nullthrows(props.data).length, + getItem: (data: Array, i: number) => data[i], + keyExtractor: (item: string) => item, + }; + const layOut = (key: string, index: number, y: number, height: number) => + listMetrics.notifyCellLayout({ + cellIndex: index, + cellKey: key, + orientation, + layout: {height, width: 5, x: 0, y}, + }); + + layOut('a', 0, 0, 10); + layOut('b', 1, 10, 10); + + // Items are inserted before and between the measured ones, which are laid + // out again at their new indices. + props.data = ['x', 'a', 'y', 'b']; + layOut('a', 1, 10, 10); + layOut('b', 3, 40, 20); + + expect(listMetrics.getCellMetricsApprox(2, props)).toEqual({ + index: 2, + length: 20, + offset: 20, + isMounted: false, + }); + expect(listMetrics.getCellMetricsApprox(0, props)).toEqual({ + index: 0, + length: 15, + offset: 0, + isMounted: false, + }); + }); + + it('estimates after data shrinks below measured cells', () => { + const listMetrics = new ListMetricsAggregator(); + const orientation = {horizontal: false, rtl: false}; + const props: CellMetricProps = { + data: ['a', 'b', 'c', 'd', 'e'], + getItemCount: () => nullthrows(props.data).length, + getItem: (data: Array, i: number) => data[i], + keyExtractor: (item: string) => item, + }; + const layOut = (key: string, index: number, y: number) => + listMetrics.notifyCellLayout({ + cellIndex: index, + cellKey: key, + orientation, + layout: {height: 10, width: 5, x: 0, y}, + }); + + layOut('a', 0, 0); + layOut('d', 3, 30); + layOut('e', 4, 40); + + // Cells measured at indices past the end of the data are skipped. + props.data = ['a', 'b', 'c']; + expect(listMetrics.getCellMetricsApprox(1, props)).toEqual({ + index: 1, + length: 10, + offset: 10, + isMounted: false, + }); + }); + it('uses getItemLayout for metrics of unmeasured cell', () => { const listMetrics = new ListMetricsAggregator(); const orientation = {horizontal: false, rtl: false}; @@ -1023,6 +1140,205 @@ describe('ListMetricsAggregator', () => { expect(listMetrics.getContentLength()).toBe(500); }); + it('forgets unmounted cells when a cell changes length with the list width', () => { + const listMetrics = new ListMetricsAggregator(); + const orientation = {horizontal: false, rtl: false}; + const props: CellMetricProps = { + data: [1, 2, 3, 4], + getItemCount: () => nullthrows(props.data).length, + getItem: (i: number) => nullthrows(props.data)[i], + }; + const layOutList = (width: number) => + listMetrics.notifyListLayout({ + orientation, + layout: {height: 500, width, x: 0, y: 0}, + }); + const layOut = (index: number, y: number, height: number, width: number) => + listMetrics.notifyCellLayout({ + cellIndex: index, + cellKey: String(index), + orientation, + layout: {height, width, x: 0, y}, + }); + + layOutList(100); + layOut(0, 0, 10, 100); + layOut(1, 10, 20, 100); + layOut(2, 30, 30, 100); + layOut(3, 60, 40, 100); + listMetrics.notifyCellUnmounted('1'); + listMetrics.notifyCellUnmounted('3'); + + // A cell that changes length without changing width keeps every + // measurement. + layOut(0, 0, 15, 100); + // So does one that changes width with the list but keeps its length. + layOutList(200); + layOut(2, 35, 30, 200); + expect(listMetrics.getCellMetrics(1, props)).not.toBeNull(); + expect(listMetrics.getCellMetrics(3, props)).not.toBeNull(); + expect(listMetrics.getHighestMeasuredCellIndex()).toEqual(3); + + // A cell that changes length with its width after the list was resized + // (e.g. wrapped text) means the unmounted cells would lay out differently + // too, so only the mounted cells are kept. + layOut(0, 0, 5, 200); + expect(listMetrics.getCellMetrics(0, props)).not.toBeNull(); + expect(listMetrics.getCellMetrics(1, props)).toBeNull(); + expect(listMetrics.getCellMetrics(2, props)).not.toBeNull(); + expect(listMetrics.getCellMetrics(3, props)).toBeNull(); + expect(listMetrics.getAverageCellLength()).toEqual(17.5); + expect(listMetrics.getHighestMeasuredCellIndex()).toEqual(2); + expect(listMetrics.getCellMetricsApprox(1, props)).toEqual({ + index: 1, + length: 30, + offset: 5, + isMounted: false, + }); + expect(listMetrics.getCellMetricsApprox(3, props)).toEqual({ + index: 3, + length: 17.5, + offset: 65, + isMounted: false, + }); + }); + + it('keeps unmounted cells when a cell changes size while the list keeps its size', () => { + const listMetrics = new ListMetricsAggregator(); + const orientation = {horizontal: false, rtl: false}; + const props: CellMetricProps = { + data: Array.from({length: 200}, (_, i) => i), + getItemCount: () => nullthrows(props.data).length, + getItem: (i: number) => nullthrows(props.data)[i], + }; + listMetrics.notifyListLayout({ + orientation, + layout: {height: 500, width: 100, x: 0, y: 0}, + }); + // Cell 0 is not stretched across the list. + for (let i = 0; i < 200; i++) { + listMetrics.notifyCellLayout({ + cellIndex: i, + cellKey: String(i), + orientation, + layout: {height: 50, width: i === 0 ? 60 : 100, x: 0, y: i * 50}, + }); + } + for (let i = 10; i < 200; i++) { + listMetrics.notifyCellUnmounted(String(i)); + } + + // Cell 0 grows on its own, which doesn't change how the other cells lay + // out. + listMetrics.notifyCellLayout({ + cellIndex: 0, + cellKey: '0', + orientation, + layout: {height: 100, width: 80, x: 0, y: 0}, + }); + expect(listMetrics.getHighestMeasuredCellIndex()).toEqual(199); + expect(listMetrics.getCellMetrics(199, props)).toEqual({ + index: 199, + length: 50, + offset: 9950, + isMounted: false, + }); + }); + + it('keeps unmounted cells laid out at the current list width', () => { + const listMetrics = new ListMetricsAggregator(); + const orientation = {horizontal: false, rtl: false}; + const props: CellMetricProps = { + data: [1, 2, 3, 4], + getItemCount: () => nullthrows(props.data).length, + getItem: (i: number) => nullthrows(props.data)[i], + }; + const layOutList = (width: number) => + listMetrics.notifyListLayout({ + orientation, + layout: {height: 500, width, x: 0, y: 0}, + }); + const layOut = (index: number, y: number, height: number, width: number) => + listMetrics.notifyCellLayout({ + cellIndex: index, + cellKey: String(index), + orientation, + layout: {height, width, x: 0, y}, + }); + + layOutList(100); + layOut(0, 0, 10, 100); + layOut(1, 10, 10, 100); + layOut(2, 20, 10, 100); + layOut(3, 30, 10, 100); + listMetrics.notifyCellUnmounted('1'); + listMetrics.notifyCellUnmounted('3'); + + // After the list is resized, cell 3 is mounted again and laid out at the + // new width before cell 0 is. + layOutList(200); + layOut(3, 30, 5, 200); + listMetrics.notifyCellUnmounted('3'); + expect(listMetrics.getCellMetrics(1, props)).toBeNull(); + + layOut(0, 0, 5, 200); + expect(listMetrics.getCellMetrics(3, props)).toEqual({ + index: 3, + length: 5, + offset: 30, + isMounted: false, + }); + expect(listMetrics.getHighestMeasuredCellIndex()).toEqual(3); + }); + + it('keeps the index of a mounted cell when forgetting an unmounted cell at that index', () => { + const listMetrics = new ListMetricsAggregator(); + const orientation = {horizontal: false, rtl: false}; + const props: CellMetricProps = { + data: ['a', 'b'], + getItemCount: () => nullthrows(props.data).length, + getItem: (data: Array, i: number) => data[i], + keyExtractor: (item: string) => item, + }; + const layOutList = (width: number) => + listMetrics.notifyListLayout({ + orientation, + layout: {height: 500, width, x: 0, y: 0}, + }); + const layOut = ( + key: string, + index: number, + y: number, + height: number, + width: number, + ) => + listMetrics.notifyCellLayout({ + cellIndex: index, + cellKey: key, + orientation, + layout: {height, width, x: 0, y}, + }); + + layOutList(100); + layOut('a', 0, 100, 10, 100); + layOut('b', 1, 110, 10, 100); + + // The data is replaced, and cell 'x' is laid out at the index of 'a'. + props.data = ['x', 'y', 'z']; + listMetrics.notifyCellUnmounted('a'); + listMetrics.notifyCellUnmounted('b'); + layOut('x', 0, 100, 20, 100); + + layOutList(200); + layOut('x', 0, 100, 40, 200); + expect(listMetrics.getCellMetricsApprox(1, props)).toEqual({ + index: 1, + length: 40, + offset: 140, + isMounted: false, + }); + }); + it('requires contentLength to resolve RTL metrics', () => { const listMetrics = new ListMetricsAggregator(); const orientation = {horizontal: true, rtl: true};