blob: f27d32e0a667821b62978f75b37b439d4f333bd4 (
plain) (
blame)
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
|
/*
* SPDX-FileCopyrightText: 2023 Kristóf Marussy
*
* SPDX-License-Identifier: MIT
*/
import { type ReactNode, useEffect, useCallback, useRef } from 'react';
import { useActiveSection } from './ActiveSectionProvider';
export default function TrackActiveSection({
children,
}: {
children: ReactNode;
}) {
const { setHash } = useActiveSection();
const elementRef = useRef<HTMLDivElement | null>(null);
const callback = useCallback(() => {
const { current: element } = elementRef;
if (!element) {
return;
}
const currentID = Array.from(element.children)
.map((element) => {
// Allow wrapper `div` elements around `section` elements.
return element.id === '' ? element.firstElementChild : element;
})
.reverse()
.find((child) => child.getBoundingClientRect().top <= 60)?.id;
const currentHash =
currentID === undefined || currentID === '' ? '' : `#${currentID}`;
setHash(currentHash);
}, [setHash]);
const setElement = useCallback(
(element: HTMLDivElement | null) => {
elementRef.current = element;
if (element) {
callback();
} else {
setHash(undefined);
}
},
[setHash],
);
useEffect(() => {
window.addEventListener('scroll', callback);
return () => window.removeEventListener('scroll', callback);
});
return <div ref={setElement}>{children}</div>;
}
|