| 20 | * how they are rendered (e.g. absolute positioning or spacer elements) is up to the caller. |
| 21 | */ |
| 22 | export function useVirtualizer({ |
| 23 | count, |
| 24 | defaultScrollOffset = 0, |
| 25 | defaultSize = 0, |
| 26 | dir, |
| 27 | direction = "vertical", |
| 28 | element, |
| 29 | itemSize: itemSizeOption, |
| 30 | onItemsRendered, |
| 31 | overscanCount = 3, |
| 32 | scrollElement |
| 33 | }: VirtualizerOptions): Virtualizer { |
| 34 | const isDynamicSize = isDynamicRowHeight(itemSizeOption); |
| 35 | assert( |
| 36 | !isDynamicSize || direction === "vertical", |
| 37 | "Dynamic item sizes are only supported for vertical content" |
| 38 | ); |
| 39 | |
| 40 | const itemSize = useMemo(() => { |
| 41 | if (isDynamicRowHeight(itemSizeOption)) { |
| 42 | return (index: number) => |
| 43 | itemSizeOption.getRowHeight(index) ?? |
| 44 | itemSizeOption.getAverageRowHeight(); |
| 45 | } |
| 46 | |
| 47 | return itemSizeOption; |
| 48 | }, [itemSizeOption]); |
| 49 | |
| 50 | const isRtl = useIsRtl(element, dir); |
| 51 | |
| 52 | const { |
| 53 | getCellBounds, |
| 54 | getEstimatedSize, |
| 55 | scrollTarget, |
| 56 | getScrollPositionForIndex, |
| 57 | startIndexOverscan, |
| 58 | startIndexVisible, |
| 59 | stopIndexOverscan, |
| 60 | stopIndexVisible |
| 61 | } = useVirtualizerCore({ |
| 62 | containerElement: element, |
| 63 | defaultContainerSize: defaultSize, |
| 64 | defaultScrollOffset, |
| 65 | direction, |
| 66 | isRtl: direction === "horizontal" && isRtl, |
| 67 | itemCount: count, |
| 68 | itemProps: ITEM_PROPS, |
| 69 | itemSize, |
| 70 | onResize: undefined, |
| 71 | overscanCount, |
| 72 | scrollElement |
| 73 | }); |
| 74 | |
| 75 | // Elements passed to measureElement; React 18 doesn't say which element unmounted (it passes null), |
| 76 | // so disconnected elements are pruned after each render instead |
| 77 | const measuredElementsRef = useRef(new Set<Element>()); |
| 78 | const warnedElementsRef = useRef(new WeakSet<Element>()); |
| 79 | const itemElementsRef = useRef<Element[]>([]); |