({
itemCount,
itemProps,
itemSize
}: {
itemCount: number;
itemProps: Props;
itemSize: number | SizeFunction<Props>;
})
| 2 | import type { Bounds, CachedBounds, SizeFunction } from "./types"; |
| 3 | |
| 4 | export function createCachedBounds<Props extends object>({ |
| 5 | itemCount, |
| 6 | itemProps, |
| 7 | itemSize |
| 8 | }: { |
| 9 | itemCount: number; |
| 10 | itemProps: Props; |
| 11 | itemSize: number | SizeFunction<Props>; |
| 12 | }): CachedBounds { |
| 13 | const cache = new Map<number, Bounds>(); |
| 14 | |
| 15 | return { |
| 16 | get(index: number) { |
| 17 | assert(index < itemCount, `Invalid index ${index}`); |
| 18 | |
| 19 | while (cache.size - 1 < index) { |
| 20 | const currentIndex = cache.size; |
| 21 | |
| 22 | let size: number; |
| 23 | switch (typeof itemSize) { |
| 24 | case "function": { |
| 25 | size = itemSize(currentIndex, itemProps); |
| 26 | break; |
| 27 | } |
| 28 | case "number": { |
| 29 | size = itemSize; |
| 30 | break; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | if (currentIndex === 0) { |
| 35 | cache.set(currentIndex, { |
| 36 | size, |
| 37 | scrollOffset: 0 |
| 38 | }); |
| 39 | } else { |
| 40 | const previousRowBounds = cache.get(currentIndex - 1); |
| 41 | assert( |
| 42 | previousRowBounds !== undefined, |
| 43 | `Unexpected bounds cache miss for index ${index}` |
| 44 | ); |
| 45 | |
| 46 | cache.set(currentIndex, { |
| 47 | scrollOffset: |
| 48 | previousRowBounds.scrollOffset + previousRowBounds.size, |
| 49 | size |
| 50 | }); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | const bounds = cache.get(index); |
| 55 | assert( |
| 56 | bounds !== undefined, |
| 57 | `Unexpected bounds cache miss for index ${index}` |
| 58 | ); |
| 59 | |
| 60 | return bounds; |
| 61 | }, |
no outgoing calls
searching dependent graphs…