aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/TrackActiveSection.tsx
blob: bb1b2ee1ccbb61fa68375f7b0e27622873835bb6 (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
/*
 * 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)
      .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>;
}