Skip to content

Commit

Permalink
refactor: extract common measureItems method
Browse files Browse the repository at this point in the history
  • Loading branch information
wellyshen committed May 30, 2021
1 parent aaaff2e commit 78dfd4d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/grumpy-news-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-cool-virtual": patch
---

refactor: extract common `measureItems` method
27 changes: 18 additions & 9 deletions src/useVirtual.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,20 @@ export default <
[keyExtractorRef]
);

const measureItems = useCallback(
(useCache = true) => {
for (let i = 0; i < itemCount; i += 1) {
msDataRef.current[i] = getMeasure(
i,
useCache && msDataRef.current[i]
? msDataRef.current[i].size
: getItemSize(i)
);
}
},
[getItemSize, getMeasure, itemCount]
);

const getCalcData = useCallback(
(scrollOffset: number) => {
const { current: msData } = msDataRef;
Expand Down Expand Up @@ -372,9 +386,7 @@ export default <

isScrollToItemRef.current = true;

if (hasDynamicSizeRef.current)
for (let i = 0; i < msDataRef.current.length; i += 1)
msDataRef.current[i] = getMeasure(i, msDataRef.current[i].size);
if (hasDynamicSizeRef.current) measureItems();

const ms = msDataRef.current[Math.max(0, Math.min(index, itemCount - 1))];

Expand Down Expand Up @@ -427,7 +439,7 @@ export default <
}
});
},
[getMeasure, itemCount, scrollTo, sizeKey]
[itemCount, measureItems, scrollTo, sizeKey]
);

useResizeEffect<O>(
Expand All @@ -437,10 +449,7 @@ export default <
const { current: prevMsData } = msDataRef;

outerRectRef.current = rect;

for (let i = 0; i < itemCount; i += 1)
msDataRef.current[i] = getMeasure(i, getItemSize(i));

measureItems(false);
handleScroll(scrollOffsetRef.current);

if (onResizeRef.current) onResizeRef.current(rect);
Expand All @@ -453,7 +462,7 @@ export default <

if (ratio) scrollTo(scrollOffsetRef.current * ratio);
},
[getItemSize, getMeasure, handleScroll, itemCount, scrollTo]
[itemCount, handleScroll, measureItems, onResizeRef, scrollTo]
);

useIsoLayoutEffect(() => {
Expand Down

0 comments on commit 78dfd4d

Please sign in to comment.