11"use client" ;
22
3- import React from "react" ;
3+ import React , { useEffect , useState } from "react" ;
44import { getIntroductionDictionary } from "@/features/localization/services/language-dictionary.service" ;
55import styles from "./sidebar-nav.module.scss" ;
6- import { useRouter } from "next/navigation " ;
6+ import clsx from "clsx " ;
77
88interface SidebarNavComponentProps {
99 languageCode : string ;
@@ -21,7 +21,33 @@ export const SidebarNavComponent: React.FC<SidebarNavComponentProps> = ({
2121 languageCode,
2222} ) => {
2323 const introductionDictionary = getIntroductionDictionary ( languageCode ) ;
24- const router = useRouter ( ) ;
24+ const headings = introductionDictionary . content . headings ;
25+ const [ activeId , setActiveId ] = useState < string | null > ( null ) ;
26+
27+ useEffect ( ( ) => {
28+ const observer = new IntersectionObserver (
29+ ( entries ) => {
30+ entries . forEach ( ( entry ) => {
31+ if ( entry . isIntersecting ) {
32+ const id = entry . target . id ;
33+ setActiveId ( id ) ;
34+ history . replaceState ( null , "" , `#${ id } ` ) ;
35+ }
36+ } ) ;
37+ } ,
38+ {
39+ threshold : 0 ,
40+ }
41+ ) ;
42+ const elements = headings
43+ . map ( ( heading ) => document . getElementById ( heading . id ) )
44+ . filter ( Boolean ) as HTMLElement [ ] ;
45+ elements . forEach ( ( el ) => observer . observe ( el ) ) ;
46+ return ( ) => {
47+ elements . forEach ( ( el ) => observer . unobserve ( el ) ) ;
48+ } ;
49+ } , [ headings ] ) ;
50+
2551 const handleClick = ( id : string ) => {
2652 scrollToElementWithOffset ( id , - 120 ) ;
2753 history . replaceState ( null , "" , `#${ id } ` ) ;
@@ -33,7 +59,10 @@ export const SidebarNavComponent: React.FC<SidebarNavComponentProps> = ({
3359 { introductionDictionary . content . headings . map ( ( heading , index ) => (
3460 < li
3561 key = { index }
36- className = { styles . title }
62+ className = { clsx (
63+ styles . title ,
64+ activeId === heading . id && styles . title__active
65+ ) }
3766 onClick = { ( ) => handleClick ( heading . id ) }
3867 >
3968 { heading . title }
0 commit comments