@@ -14,9 +14,11 @@ export const TableOfContents: React.FC<TableOfContentsProps> = (props) => {
1414 ] = React . useState ( - 1 )
1515 const { toc } : { toc : TOC } = props
1616 const items : TOC = React . useMemo ( ( ) => {
17- return toc . filter ( ( item ) => ( item . level === 2 || item . level === 3 ) )
17+ return toc . filter ( ( item ) => item . level === 2 || item . level === 3 )
1818 } , [ toc ] )
1919
20+ const navRef : React . RefObject < HTMLElement > = React . createRef < HTMLElement > ( )
21+
2022 const findActiveIndex : ( ) => void = React . useCallback ( ( ) => {
2123 for ( let i : number = 0 ; i < items . length ; i ++ ) {
2224 const h : HTMLElement | null = document . getElementById (
@@ -29,27 +31,40 @@ export const TableOfContents: React.FC<TableOfContentsProps> = (props) => {
2931 document . documentElement . clientHeight / 2
3032 ) {
3133 setActiveIndex ( i )
34+ const liNodes : NodeListOf < HTMLLIElement > | undefined =
35+ navRef . current ?. querySelectorAll ( 'li' )
36+ if ( navRef . current && liNodes ) {
37+ navRef . current . scrollTop =
38+ liNodes [ i ] . offsetTop >
39+ document . documentElement . clientHeight - 100
40+ ? liNodes [ liNodes . length - 1 ] . offsetTop
41+ : 0
42+ }
3243 }
3344 }
34- } , [ items ] )
45+ } , [ items , navRef ] )
3546
3647 useOnScroll ( { onScroll : findActiveIndex } )
3748
3849 return (
39- < nav className = { styles [ 'nav' ] } >
50+ < nav ref = { navRef } className = { styles [ 'nav' ] } >
4051 < div className = { styles [ 'navLabel' ] } > ON THIS PAGE</ div >
4152 { items . length > 0 ? (
4253 < ul >
4354 { items . map ( ( item , index ) => (
4455 < li
45- key = { item . title }
56+ key = { ` ${ item . title } - ${ index } ` }
4657 className = { `${ styles [ 'navListItem' ] } ${
4758 index === activeIndex ? styles [ 'active' ] : ''
4859 } `}
4960 >
5061 < a
5162 href = { `#${ item . headingId } ` }
52- className = { `${ styles [ 'navListItem-link' ] } ${ styles [ `navListItem-link-padding-level${ item . level } ` ] } ` }
63+ className = { `${ styles [ 'navListItem-link' ] } ${
64+ styles [
65+ `navListItem-link-padding-level${ item . level } `
66+ ]
67+ } `}
5368 >
5469 { item . title }
5570 </ a >
0 commit comments