@@ -31,45 +31,43 @@ export default function useScrollTo<T>(
31
31
32
32
// We will retry 3 times in case dynamic height shaking
33
33
const syncScroll = ( times = 3 ) => {
34
- if ( times < 0 ) return ;
34
+ if ( times < 0 || ! containerRef . current ) return ;
35
35
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 ;
38
40
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 ) ;
43
46
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
+ }
49
49
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 ;
52
58
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 ) {
56
63
containerRef . current . scrollTop = itemTop ;
57
- break ;
58
- case 'bottom' :
64
+ } else if ( itemBottom > scrollBottom ) {
59
65
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
- }
70
66
}
71
67
}
68
+ }
72
69
70
+ scrollRef . current = raf ( ( ) => {
73
71
syncScroll ( times - 1 ) ;
74
72
} ) ;
75
73
} ;
0 commit comments