Skip to content

Commit ef5a074

Browse files
committed
chore: scrollTo will trigger at once
1 parent 45074ce commit ef5a074

File tree

1 file changed

+27
-29
lines changed

1 file changed

+27
-29
lines changed

src/hooks/useScrollTo.tsx

Lines changed: 27 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -31,45 +31,43 @@ export default function useScrollTo<T>(
3131

3232
// We will retry 3 times in case dynamic height shaking
3333
const syncScroll = (times = 3) => {
34-
if (times < 0) return;
34+
if (times < 0 || !containerRef.current) return;
3535

36-
scrollRef.current = raf(() => {
37-
if (!containerRef.current) return;
36+
// Get top & bottom
37+
let stackTop = 0;
38+
let itemTop = 0;
39+
let itemBottom = 0;
3840

39-
// Get top & bottom
40-
let stackTop = 0;
41-
let itemTop = 0;
42-
let itemBottom = 0;
41+
for (let i = 0; i <= index; i += 1) {
42+
const key = getKey(data[i]);
43+
itemTop = stackTop;
44+
const cacheHeight = heights.get(key);
45+
itemBottom = itemTop + (cacheHeight === undefined ? itemHeight : cacheHeight);
4346

44-
for (let i = 0; i <= index; i += 1) {
45-
const key = getKey(data[i]);
46-
itemTop = stackTop;
47-
const cacheHeight = heights.get(key);
48-
itemBottom = itemTop + (cacheHeight === undefined ? itemHeight : cacheHeight);
47+
stackTop = itemBottom;
48+
}
4949

50-
stackTop = itemBottom;
51-
}
50+
// Scroll to
51+
switch (align) {
52+
case 'top':
53+
containerRef.current.scrollTop = itemTop;
54+
break;
55+
case 'bottom':
56+
containerRef.current.scrollTop = itemBottom - height;
57+
break;
5258

53-
// Scroll to
54-
switch (align) {
55-
case 'top':
59+
default: {
60+
const { scrollTop } = containerRef.current;
61+
const scrollBottom = scrollTop + height;
62+
if (itemTop < scrollTop) {
5663
containerRef.current.scrollTop = itemTop;
57-
break;
58-
case 'bottom':
64+
} else if (itemBottom > scrollBottom) {
5965
containerRef.current.scrollTop = itemBottom - height;
60-
break;
61-
62-
default: {
63-
const { scrollTop } = containerRef.current;
64-
const scrollBottom = scrollTop + height;
65-
if (itemTop < scrollTop) {
66-
containerRef.current.scrollTop = itemTop;
67-
} else if (itemBottom > scrollBottom) {
68-
containerRef.current.scrollTop = itemBottom - height;
69-
}
7066
}
7167
}
68+
}
7269

70+
scrollRef.current = raf(() => {
7371
syncScroll(times - 1);
7472
});
7573
};

0 commit comments

Comments
 (0)