text: import React, { useEffect, useState } from "react";
  import { Link } from "gatsby";
  import kebabCase from "lodash/kebabCase";
  import styles from "./TOC.module.scss";
  
  type Props = {
    title: string,
    slug: string,
    headers: string[],
  };
  
  const TOC = ({ title, slug, headers }: Props) => {
    const [currentHeaderUrl, setCurrentHeaderUrl] = useState(undefined);
    useEffect(() => {
      const handleScroll = () => {
        let aboveHeaderUrl;
        const currentOffsetY = window.pageYOffset;
        const headerElements = Array.prototype.slice
          .call(document.querySelectorAll(".anchor-header"))
          .filter(function(el) {
            return !el.closest(
              "blockquote > h1, blockquote > h2, blockquote > h3, blockquote > h4, blockquote > h5, blockquote > h6"
            );
          });
  
        for (const elem of headerElements) {
          const { top } = elem.getBoundingClientRect();
          const elemTop = top + currentOffsetY;
          const isLast = elem === headerElements[headerElements.length - 1];
          if (currentOffsetY < elemTop - 300) {
            aboveHeaderUrl && setCurrentHeaderUrl(aboveHeaderUrl);
            !aboveHeaderUrl && setCurrentHeaderUrl(undefined);
            break;
          } else {
            isLast && setCurrentHeaderUrl(elem.offsetParent.innerText);
            !isLast && (aboveHeaderUrl = elem.offsetParent.innerText);
          }
        }
      };
      window.addEventListener("scroll", handleScroll);
      return () => {
        window.removeEventListener("scroll", handleScroll);
      };
    }, []);
    //${header.value==currentHeaderUrl?styles["toc__list-item-link-active"]:styles["toc__list-item-link"]}
  
    return (
      <div className={styles["toc"]}>
        <ul className={styles["toc__list"]}>
          <li>
            <label>{title}</label>
          </li>
          {headers.map((header) => (
            <li
              className={styles["toc__list-item"]}
              key={header.value}
              title={header.value}
              style={{ paddingLeft: `${header.depth - 0.5}rem` }}
            >
              <Link
                to={`${slug}#${kebabCase(header.value)}`}
                className={`${
                  header.value == currentHeaderUrl
                    ? styles["toc__list-item-link-active"]
                    : styles["toc__list-item-link"]
                }`}
              >
                {header.value == currentHeaderUrl ? "-" : null}
                {header.value}
              </Link>
            </li>
          ))}
        </ul>
      </div>
    );
  };
  
  export default TOC;
  