aboutsummaryrefslogtreecommitdiff
path: root/examples/docs/src/components/DocSidebar.tsx
blob: 076d460ccbc71284e089686a0dc9cec4502696eb (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
52
53
54
55
56
57
58
59
60
61
import type { FunctionalComponent } from 'preact';
import { h } from 'preact';
import { useState, useEffect, useRef } from 'preact/hooks';
import EditOnGithub from './EditOnGithub';

const DocSidebar: FunctionalComponent<{ headers: any[]; editHref: string }> = ({ headers = [], editHref }) => {
  const itemOffsets = useRef([]);
  const [activeId, setActiveId] = useState<string>(undefined);

  useEffect(() => {
    const getItemOffsets = () => {
      const titles = document.querySelectorAll('article :is(h2, h3, h4)');
      itemOffsets.current = Array.from(titles).map((title) => ({
        id: title.id,
        topOffset: title.getBoundingClientRect().top + window.scrollY,
      }));
    };

    const onScroll = () => {
      const itemIndex = itemOffsets.current.findIndex((item) => item.topOffset > window.scrollY + window.innerHeight / 3);
      if (itemIndex === 0) {
        setActiveId(undefined);
      } else if (itemIndex === -1) {
        setActiveId(itemOffsets.current[itemOffsets.current.length - 1].id);
      } else {
        setActiveId(itemOffsets.current[itemIndex - 1].id);
      }
    };

    getItemOffsets();
    window.addEventListener('resize', getItemOffsets);
    window.addEventListener('scroll', onScroll);

    return () => {
      window.removeEventListener('resize', getItemOffsets);
      window.removeEventListener('scroll', onScroll);
    };
  }, []);

  return (
    <nav>
      <div>
        <h4>Contents</h4>
        <ul>
          {headers
            .filter(({ depth }) => depth > 1 && depth < 5)
            .map((header) => (
              <li class={`header-link depth-${header.depth} ${activeId === header.slug ? 'active' : ''}`.trim()}>
                <a href={`#${header.slug}`}>{header.text}</a>
              </li>
            ))}
        </ul>
      </div>
      <div>
        <EditOnGithub href={editHref} />
      </div>
    </nav>
  );
};

export default DocSidebar;