ArticleTOCNavigator

2023/5/23 14:32:33

当前为 2023-05-24 提交的版本,查看 最新版本

// ==UserScript==
// @name        ArticleTOCNavigator
// @namespace   This JavaScript plugin generates a dynamic table of contents for dev website. It uses HTML header tags to create links to respective sections, highlights the current section, and displays it on the sidebar for easy navigation.
// @match       https://dev.to/*
// @grant       none
// @version     1.0.5
// @author      Circle
// @description 2023/5/23 14:32:33
// @license MIT
// ==/UserScript==
const generateTOC = () => {
  const articleBody = document.querySelector('.crayons-article__body');
  if (!articleBody || document.querySelector('#toc-container')) return;

  const sidebarRight = document.querySelector('.crayons-layout__sidebar-right');
  const tocContainer = document.createElement('ul');
  tocContainer.id = 'toc-container';
  tocContainer.style.paddingLeft = '20px';

  const divContainer = document.createElement('div');
  divContainer.className =
    'crayons-article-sticky crayons-card crayons-card--secondary crayons-sponsorship billboard mt-4';
  divContainer.appendChild(tocContainer);

  const hStack = [];
  const regex = /\bH[1-5]\b/g;
  const hHeadings = [...articleBody.childNodes].filter((node) => node.nodeType !== 3 && node.tagName && regex.test(node.tagName));
  if (!hHeadings.length) return;

  const linkTargets = hHeadings.map((hHeading, index) => {
    const hItem = document.createElement('li');
    const hLink = document.createElement('a');
    const level = Number(hHeading.tagName.slice(1));

    hLink.href = '#toc-' + index;
    hLink.textContent = hHeading.textContent;
    hLink.style.color = 'var(--body-color)';
    hLink.onclick = (event) => {
      event.preventDefault();
      hHeading.scrollIntoView({ behavior: "smooth" });
    }

    hItem.appendChild(hLink);
    hItem.className = 'toc-level-' + level;
    hItem.style.marginLeft = (hStack.length) * 15 + 'px';

    hHeading.id = 'toc-' + index;
    tocContainer.appendChild(hItem);

    if (!hStack.length || hStack[hStack.length - 1] < level) {
      hStack.push(level);
    } else if (hStack[hStack.length - 1] > level) {
      hStack.pop();
    }

    return hItem;
  });

  sidebarRight.appendChild(divContainer);

  return { hHeadings, linkTargets };
};

let tocData = generateTOC();

window.addEventListener('scroll', () => {
  if (!tocData) return;

  const { hHeadings, linkTargets } = tocData;
  const currentPosition =
    window.pageYOffset ||
    document.documentElement.scrollTop ||
    document.body.scrollTop ||
    0;

  const currentIndex = hHeadings.findIndex(
    hHeading => hHeading.offsetTop > currentPosition,
  );

  linkTargets.forEach((link, index) =>
    link.classList.toggle('active', index === currentIndex),
  );
});

let oldHref = document.location.href;
const observer = new MutationObserver(() => {
  if (oldHref != document.location.href) {
    oldHref = document.location.href;
    tocData = generateTOC();
  }
});

observer.observe(document.querySelector('body'), {
  childList: true,
  subtree: true,
});

const styleElement = document.createElement('style');
styleElement.textContent = `
  #toc-container .active a {
    color:  var(--link-branded-color)!important;
  }
  .active {
    color:  var(--link-branded-color);
    font-weight: bold;
  }
`;
document.head.appendChild(styleElement);