-
Notifications
You must be signed in to change notification settings - Fork 353
Expand file tree
/
Copy pathsidebar-nav.component.tsx
More file actions
75 lines (68 loc) · 2.13 KB
/
sidebar-nav.component.tsx
File metadata and controls
75 lines (68 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"use client";
import React, { useEffect, useState } from "react";
import { getIntroductionDictionary } from "@/features/localization/services/language-dictionary.service";
import styles from "./sidebar-nav.module.scss";
import clsx from "clsx";
interface SidebarNavComponentProps {
languageCode: string;
}
const scrollToElementWithOffset = (id: string, offset = 0) => {
const element = document.getElementById(id);
if (element) {
const y = element.getBoundingClientRect().top + window.pageYOffset + offset;
window.scrollTo({ top: y, behavior: "smooth" });
}
};
export const SidebarNavComponent: React.FC<SidebarNavComponentProps> = ({
languageCode,
}) => {
const introductionDictionary = getIntroductionDictionary(languageCode);
const headings = introductionDictionary.content.headings;
const [activeId, setActiveId] = useState<string | null>(null);
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const id = entry.target.id;
setActiveId(id);
history.replaceState(null, "", `#${id}`);
}
});
},
{
rootMargin: "0px 0px -40% 0px",
threshold: 1,
}
);
const elements = headings
.map((heading) => document.getElementById(heading.id))
.filter(Boolean) as HTMLElement[];
elements.forEach((el) => observer.observe(el));
return () => {
elements.forEach((el) => observer.unobserve(el));
};
}, [headings]);
const handleClick = (id: string) => {
scrollToElementWithOffset(id, -120);
history.replaceState(null, "", `#${id}`);
};
return (
<div className={styles.container}>
<ul className={styles.list}>
{introductionDictionary.content.headings.map((heading, index) => (
<li
key={index}
className={clsx(
styles.title,
activeId === heading.id && styles.title__active
)}
onClick={() => handleClick(heading.id)}
>
{heading.title}
</li>
))}
</ul>
</div>
);
};