fix: ToC highlights only topmost visible heading
This commit is contained in:
parent
9dfbbe71e8
commit
a3dafa971a
1 changed files with 15 additions and 1 deletions
|
|
@ -8,13 +8,27 @@ export function TableOfContents({ headings }: { headings: Heading[] }) {
|
||||||
const observerRef = useRef<IntersectionObserver | null>(null);
|
const observerRef = useRef<IntersectionObserver | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
const visibleHeadings = new Map<string, number>();
|
||||||
|
|
||||||
const callback: IntersectionObserverCallback = (entries) => {
|
const callback: IntersectionObserverCallback = (entries) => {
|
||||||
entries.forEach((entry) => {
|
entries.forEach((entry) => {
|
||||||
if (entry.isIntersecting) {
|
if (entry.isIntersecting) {
|
||||||
setActiveId(entry.target.id);
|
visibleHeadings.set(entry.target.id, entry.boundingClientRect.top);
|
||||||
|
} else {
|
||||||
|
visibleHeadings.delete(entry.target.id);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Find the topmost visible heading
|
||||||
|
if (visibleHeadings.size > 0) {
|
||||||
|
const sortedHeadings = Array.from(visibleHeadings.entries())
|
||||||
|
.sort((a, b) => a[1] - b[1]);
|
||||||
|
setActiveId(sortedHeadings[0][0]);
|
||||||
|
} else {
|
||||||
|
setActiveId(null);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const observer = new IntersectionObserver(callback, {
|
const observer = new IntersectionObserver(callback, {
|
||||||
rootMargin: "-40% 0px -55% 0px",
|
rootMargin: "-40% 0px -55% 0px",
|
||||||
threshold: 0.1,
|
threshold: 0.1,
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue