github-md-catalog

generate catalog in Github readme page

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         github-md-catalog
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  generate catalog in Github readme page
// @author       fengxxc
// @match        https://github.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function main() {
        // 目录树缩进的步长
        const PADDINGLEFT_STEP_LENGTH = 20;

        if (window.location.hostname != 'github.com') return;
        const mdDom = document.querySelector('article.markdown-body');
        if (!mdDom) return;
        let catalogs = [];
        const titles = mdDom.querySelectorAll('h1,h2,h3,h4,h5,h6');
        for (let i = 0; i < titles.length; i++) {
            catalogs.push(
                getPaddingLeftEl(parseInt(titles[i].tagName.slice(1)), PADDINGLEFT_STEP_LENGTH)
                + '<a href="#' + titles[i].innerText + '">' + titles[i].innerText + '</a><br>'
            );
            titles[i].insertAdjacentHTML('afterbegin', '<a name="' + titles[i].innerText + '"></a>');
        }
        document.body.insertAdjacentHTML('beforeend', '<nav id="github_md_catalog" style="position: fixed; top: 115px; right: 5px; max-width: 257px">' + catalogs.join('') + '</nav>');
    }

    function getPaddingLeftEl(tabStep, stepLength) {
        return '<span style="display: inline-block; width: ' + tabStep * stepLength + 'px;"></span>';
    }

    main();
})();