Greasy Fork is available in English.

TS中文官网文档目录

TS中文官网文档二级标题目录

// ==UserScript==
// @name                TS中文官网文档目录
// @namespace           http://tampermonkey.net/
// @version             0.6
// @description         TS中文官网文档二级标题目录
// @author              pogusanqian
// @match               https://www.tslang.cn/docs/*
// @icon                data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant               none
// @license             MIT
// ==/UserScript==

(() => {
  class Title {
    constructor(titleDom, titleChilds) {
      this.titleDom = titleDom;
      this.titleChilds = titleChilds;
    }
  }

  function getTitleList(data, flag) {
    const peers = [];
    const nextFlag = flag + 1;
    const flagArr = data.reduce((prev, item, index) => {
      if (item.tagName === 'H' + flag) prev.unshift(index);
      return prev;
    }, []);

    const splitArr = flagArr.reduce((prev, item) => {
      prev.unshift(data.splice(item));
      return prev;
    }, []);

    splitArr.forEach(item => {
      const titleDom = item[0];
      let titleChilds = item.splice(1);
      titleChilds = titleChilds.length ? getTitleList(titleChilds, nextFlag) : [];
      const people = new Title(titleDom, titleChilds);
      peers.push(people);
    });
    return peers;
  }

  // 获取数据源(并给元素添加上id标识)
  const data = Array.from(document.querySelectorAll("article > h1,h2"));
  data.forEach((item, index) => {
    item.id = `${Date.now()}_${index}`;
    // 防止锚点定位后被顶部固定导航栏遮住
    item.style.cssText = 'margin-top: -50px; padding-top: 50px';
  });
  const titleList = getTitleList(data, 1);

  // 创建dom对象
  const listWapper = document.body.appendChild(document.createElement('div'));
  titleList.forEach(item => listWapper.insertAdjacentHTML('beforeend', `<div class="card">
  <div class="card-header" data-toggle="collapse" data-target="#collapse${item.titleDom.id}">
    <a href="#${item.titleDom.id}">
      <button class="btn btn-link btn-block collapsed" style="text-align: left">${item.titleDom.innerHTML}</button>
    </a>
  </div>
  <div id="collapse${item.titleDom.id}" class="collapse">
    <div class="card-body">
      ${item.titleChilds.map(item2 => `<a href="#${item2.titleDom.id}" style="margin-left:30px; text-decoration:none"><span style="font-size: 15px">${item2.titleDom.innerHTML}</span></a><br>`)}
    </div>
  </div>
</div>`));

  // 设置浮动样式
  listWapper.classList.add('accordion');
  listWapper.style.cssText = `position: fixed; right: 10px; top: 50px; right: 0px; width: 200px`;
  // 删除两个影响视觉的原有DOM元素
  document.querySelector("body > header > nav > div > a").remove();
  document.querySelector("body > div.container-fluid.update-banner").remove();
  document.querySelector("#content > div").style.cssText = 'width: 80%; margin-left: 50px';
})();