({
defaultRowHeight,
key
}: {
defaultRowHeight: number;
key?: string | number;
})
| 5 | import type { DynamicRowHeight } from "./types"; |
| 6 | |
| 7 | export function useDynamicRowHeight({ |
| 8 | defaultRowHeight, |
| 9 | key |
| 10 | }: { |
| 11 | defaultRowHeight: number; |
| 12 | key?: string | number; |
| 13 | }) { |
| 14 | const [state, setState] = useState<{ |
| 15 | key: string | number | undefined; |
| 16 | map: Map<number, number>; |
| 17 | }>({ |
| 18 | key, |
| 19 | map: new Map() |
| 20 | }); |
| 21 | |
| 22 | if (state.key !== key) { |
| 23 | setState({ |
| 24 | key, |
| 25 | map: new Map() |
| 26 | }); |
| 27 | } |
| 28 | |
| 29 | const { map } = state; |
| 30 | |
| 31 | const getAverageRowHeight = useCallback(() => { |
| 32 | let totalHeight = 0; |
| 33 | |
| 34 | map.forEach((height) => { |
| 35 | totalHeight += height; |
| 36 | }); |
| 37 | |
| 38 | if (totalHeight === 0) { |
| 39 | return defaultRowHeight; |
| 40 | } |
| 41 | |
| 42 | return totalHeight / map.size; |
| 43 | }, [defaultRowHeight, map]); |
| 44 | |
| 45 | const getRowHeight = useCallback( |
| 46 | (index: number) => { |
| 47 | const measuredHeight = map.get(index); |
| 48 | if (measuredHeight !== undefined) { |
| 49 | return measuredHeight; |
| 50 | } |
| 51 | |
| 52 | // Temporarily store default height in the cache map to avoid scroll jumps if rowProps change |
| 53 | // Else rowProps changes can impact the average height, and cause rows to shift up or down within the list |
| 54 | // see github.com/bvaughn/react-window/issues/863 |
| 55 | map.set(index, defaultRowHeight); |
| 56 | |
| 57 | return defaultRowHeight; |
| 58 | }, |
| 59 | [defaultRowHeight, map] |
| 60 | ); |
| 61 | |
| 62 | const setRowHeight = useCallback((index: number, size: number) => { |
| 63 | setState((prevState) => { |
| 64 | if (prevState.map.get(index) === size) { |
searching dependent graphs…