@@ -37,10 +37,9 @@ export function useScrollToActiveTOCItem(tocItem: {
37
37
38
38
const hash = useHash ( ) ;
39
39
const scrollContainerRef = React . useContext ( TOCScrollContainerContext ) ;
40
+ const isScrolled = React . useRef ( false ) ;
40
41
41
- React . useLayoutEffect ( ( ) => {
42
- if ( ! isActive ) { return ; }
43
-
42
+ const isOutOfView = React . useCallback ( ( ) => {
44
43
if ( linkRef . current && scrollContainerRef ?. current ) {
45
44
const tocItem = linkRef . current ;
46
45
const tocContainer = scrollContainerRef . current ;
@@ -49,17 +48,31 @@ export function useScrollToActiveTOCItem(tocItem: {
49
48
const containerTop = tocContainer . scrollTop ;
50
49
const containerBottom = containerTop + tocContainer . clientHeight ;
51
50
52
- // Only scroll if the TOC item is outside the viewable area of the container
53
- if (
51
+ return (
54
52
tocItemTop < containerTop + TOC_ITEM_OFFSET ||
55
53
tocItemTop > containerBottom - TOC_ITEM_OFFSET
56
- ) {
57
- tocItem . scrollIntoView ( {
58
- behavior : 'instant' , // using instant as smooth can interrupt or get interrupted by other `scrollIntoView` changes
59
- block : 'center' ,
60
- } ) ;
61
- }
54
+ ) ;
55
+ }
56
+ return false ;
57
+ } , [ linkRef , scrollContainerRef ] ) ;
58
+
59
+ React . useLayoutEffect ( ( ) => {
60
+ if ( ! isActive ) {
61
+ isScrolled . current = false ;
62
+ return ;
63
+ }
64
+
65
+ if ( ! isOutOfView ( ) || isScrolled . current ) {
66
+ return ;
62
67
}
68
+
69
+ const tocItem = linkRef . current ;
70
+ console . log ( { isActive, scrollToView : tocItem ?. textContent } ) ;
71
+ tocItem ?. scrollIntoView ( {
72
+ behavior : 'instant' , // using instant as smooth can interrupt or get interrupted by other `scrollIntoView` changes
73
+ block : 'center' ,
74
+ } ) ;
75
+ isScrolled . current = true ;
63
76
// We've included `hash` from `useHash` hook as a dependency so we trigger the effect in response to changes to the url hash
64
- } , [ isActive , hash , linkRef , scrollContainerRef ] ) ;
77
+ } , [ hash , isActive , isOutOfView , linkRef ] ) ;
65
78
}
0 commit comments