| 3 | import type { CachedBounds, SizeFunction } from "./types"; |
| 4 | |
| 5 | export function getOffsetForIndex<Props extends object>({ |
| 6 | align, |
| 7 | cachedBounds, |
| 8 | clamp = true, |
| 9 | index, |
| 10 | itemCount, |
| 11 | itemSize, |
| 12 | containerScrollOffset, |
| 13 | containerSize |
| 14 | }: { |
| 15 | align: Align; |
| 16 | cachedBounds: CachedBounds; |
| 17 | /** |
| 18 | * Clamp the offset to the list's own scrollable range. |
| 19 | * Lists that scroll with an outer element can scroll beyond their own bounds (e.g. to show content above the list); |
| 20 | * the outer element's scrollable range is enforced by the browser instead. |
| 21 | */ |
| 22 | clamp?: boolean; |
| 23 | index: number; |
| 24 | itemCount: number; |
| 25 | itemSize: number | SizeFunction<Props>; |
| 26 | containerScrollOffset: number; |
| 27 | containerSize: number; |
| 28 | }) { |
| 29 | if (index < 0 || index >= itemCount) { |
| 30 | throw RangeError(`Invalid index specified: ${index}`, { |
| 31 | cause: `Index ${index} is not within the range of 0 - ${itemCount - 1}` |
| 32 | }); |
| 33 | } |
| 34 | |
| 35 | // Populate the target bounds before estimating the total from cached sizes. |
| 36 | const bounds = cachedBounds.get(index); |
| 37 | const estimatedTotalSize = getEstimatedSize({ |
| 38 | cachedBounds, |
| 39 | itemCount, |
| 40 | itemSize |
| 41 | }); |
| 42 | |
| 43 | const clampOffset = (offset: number) => |
| 44 | clamp |
| 45 | ? Math.max(0, Math.min(estimatedTotalSize - containerSize, offset)) |
| 46 | : offset; |
| 47 | |
| 48 | const maxOffset = clampOffset(bounds.scrollOffset); |
| 49 | const minOffset = clamp |
| 50 | ? Math.max(0, bounds.scrollOffset - containerSize + bounds.size) |
| 51 | : bounds.scrollOffset - containerSize + bounds.size; |
| 52 | |
| 53 | // Visibility depends on the row itself, not the estimated scroll extent. |
| 54 | // For oversized rows, leave the offset alone when the row fills the viewport. |
| 55 | const isVisible = |
| 56 | bounds.size > containerSize |
| 57 | ? containerScrollOffset >= bounds.scrollOffset && |
| 58 | containerScrollOffset <= minOffset |
| 59 | : containerScrollOffset >= minOffset && |
| 60 | containerScrollOffset <= bounds.scrollOffset; |
| 61 | |
| 62 | if (align === "smart") { |