MCPcopy Create free account
hub / github.com/bvaughn/react-window / getOffsetForIndex

Function getOffsetForIndex

lib/core/getOffsetForIndex.ts:5–89  ·  view source on GitHub ↗
({
  align,
  cachedBounds,
  clamp = true,
  index,
  itemCount,
  itemSize,
  containerScrollOffset,
  containerSize
}: {
  align: Align;
  cachedBounds: CachedBounds;
  /**
   * Clamp the offset to the list's own scrollable range.
   * Lists that scroll with an outer element can scroll beyond their own bounds (e.g. to show content above the list);
   * the outer element's scrollable range is enforced by the browser instead.
   */
  clamp?: boolean;
  index: number;
  itemCount: number;
  itemSize: number | SizeFunction<Props>;
  containerScrollOffset: number;
  containerSize: number;
})

Source from the content-addressed store, hash-verified

3import type { CachedBounds, SizeFunction } from "./types";
4
5export 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") {

Callers 3

getOffsetFunction · 0.90
createTestHelperFunction · 0.90

Calls 2

getEstimatedSizeFunction · 0.90
clampOffsetFunction · 0.85

Tested by 1

createTestHelperFunction · 0.72