GitHub Table of Contents

A userscript that adds a table of contents to readme & wiki pages

当前为 2022-10-24 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name GitHub Table of Contents
  3. // @version 2.1.5
  4. // @description A userscript that adds a table of contents to readme & wiki pages
  5. // @license MIT
  6. // @author Rob Garrison
  7. // @namespace https://github.com/Mottie
  8. // @include https://github.com/*
  9. // @include https://gist.github.com/*
  10. // @run-at document-idle
  11. // @grant GM_registerMenuCommand
  12. // @grant GM.registerMenuCommand
  13. // @grant GM_getValue
  14. // @grant GM.getValue
  15. // @grant GM_setValue
  16. // @grant GM.setValue
  17. // @grant GM_addStyle
  18. // @grant GM.addStyle
  19. // @require https://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=1108163
  20. // @require https://greasyfork.org/scripts/398877-utils-js/code/utilsjs.js?version=1079637
  21. // @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js?updated=20180103
  22. // @icon https://github.githubassets.com/pinned-octocat.svg
  23. // @supportURL https://github.com/Mottie/GitHub-userscripts/issues
  24. // ==/UserScript==
  25. /* global $ $$ on addClass removeClass */
  26. (async () => {
  27. "use strict";
  28.  
  29. const defaults = {
  30. title: "Table of Contents", // popup title
  31. top: "64px", // popup top position when reset
  32. left: "auto", // popup left position when reset
  33. right: "10px", // popup right position when reset
  34. headerPad: "48px", // padding added to header when TOC is collapsed
  35. headerSelector: [".header", ".Header", ".header-logged-out > div"],
  36. headerWrap: ".js-header-wrapper",
  37. toggle: "g+t", // keyboard toggle shortcut
  38. restore: "g+r", // keyboard reset popup position shortcut
  39. delay: 1000, // ms between keyboard shortcuts
  40. };
  41.  
  42. GM.addStyle(`
  43. /* z-index > 1000 to be above the */
  44. .ghus-toc { position:fixed; z-index:1001; min-width:200px; min-height:100px; top:${defaults.top};
  45. right:${defaults.right}; resize:both; overflow:hidden; padding: 0 3px 38px 0; margin:0; }
  46. .ghus-toc h3 { cursor:move; }
  47. .ghus-toc-title { padding-left:20px; }
  48. /* icon toggles TOC container & subgroups */
  49. .ghus-toc .ghus-toc-icon { vertical-align:baseline; }
  50. .ghus-toc h3 .ghus-toc-icon, .ghus-toc li.collapsible .ghus-toc-icon { cursor:pointer; }
  51. .ghus-toc .ghus-toc-toggle { position:absolute; width:28px; height:38px; top:0px; left:0px; }
  52. .ghus-toc .ghus-toc-toggle svg { margin-top:10px; margin-left:9px; }
  53. .ghus-toc .ghus-toc-docs { float:right; }
  54. /* move collapsed TOC to top right corner */
  55. .ghus-toc.collapsed {
  56. width:30px !important; height:34px !important; min-width:auto; min-height:auto; overflow:hidden;
  57. top:16px !important; left:auto !important; right:10px !important; margin:0; padding:0;
  58. border:1px solid rgba(128, 128, 128, 0.5); border-radius:3px; resize:none;
  59. }
  60. .ghus-toc.collapsed > h3 { cursor:pointer; padding-top:5px; border:none; background:#222; color:#ddd; }
  61. .ghus-toc.collapsed .ghus-toc-docs, .ghus-toc.collapsed .ghus-toc-title { display:none; }
  62. .ghus-toc:not(.ghus-toc-hidden).collapsed + .Header { padding-right: ${defaults.headerPad} !important; }
  63. /* move header text out-of-view when collapsed */
  64. .ghus-toc.collapsed > h3 svg { margin-top:6px; }
  65. .ghus-toc-hidden, .ghus-toc.collapsed .boxed-group-inner { display:none; }
  66. .ghus-toc .boxed-group-inner { width:100%; height:100%; overflow-x:hidden; overflow-y:auto;
  67. margin-bottom:50px; }
  68. .ghus-toc ul { list-style:none; }
  69. .ghus-toc li { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; position:relative; }
  70. .ghus-toc .ghus-toc-h1 { padding-left:15px; }
  71. .ghus-toc .ghus-toc-h2 { padding-left:30px; }
  72. .ghus-toc .ghus-toc-h3 { padding-left:45px; }
  73. .ghus-toc .ghus-toc-h4 { padding-left:60px; }
  74. .ghus-toc .ghus-toc-h5 { padding-left:75px; }
  75. .ghus-toc .ghus-toc-h6 { padding-left:90px; }
  76. /* anchor collapsible icon */
  77. .ghus-toc li.collapsible .ghus-toc-icon:before {
  78. content:' '; position:absolute; width:20px; height:20px; display:inline-block; left:-16px; top:-14px;
  79. background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGNsYXNzPSdvY3RpY29uJyBoZWlnaHQ9JzE0JyB2aWV3Qm94PScwIDAgMTIgMTYnPjxwYXRoIGQ9J00wIDVsNiA2IDYtNkgweic+PC9wYXRoPjwvc3ZnPg==) left center no-repeat;
  80. }
  81. .ghus-toc li.collapsible.collapsed .ghus-toc-icon:before { -webkit-transform:rotate(-90deg);
  82. transform:rotate(-90deg); top:-20px; left:-20px; }
  83. .ghus-toc-icon svg, .ghus-toc-docs svg { pointer-events:none; }
  84. .ghus-toc-no-selection { -webkit-user-select:none !important; -moz-user-select:none !important;
  85. user-select:none !important; }
  86. /* prevent google translate from breaking links */
  87. .ghus-toc li a font { pointer-events:none; }
  88. `);
  89.  
  90. let tocInit = false;
  91.  
  92. // modifiable title
  93. let title = await GM.getValue("github-toc-title", defaults.title);
  94.  
  95. const container = document.createElement("div");
  96.  
  97. // keyboard shortcuts
  98. const keyboard = {
  99. timer: null,
  100. lastKey: null
  101. };
  102.  
  103. // drag variables
  104. const drag = {
  105. el: null,
  106. elmX: 0,
  107. elmY: 0,
  108. time: 0,
  109. unsel: null
  110. };
  111.  
  112. const regex = {
  113. quote: /'/g,
  114. doubleQuote: /"/g,
  115. number: /\d/,
  116. toggle: /\+/g,
  117. header: /ghus-toc-h\d/,
  118. collapsible: /collapsible-(\d+)/,
  119. ignore: /(input|textarea)/i,
  120. };
  121.  
  122. const stopPropag = event => {
  123. event.preventDefault();
  124. event.stopPropagation();
  125. };
  126.  
  127. // drag code adapted from http://jsfiddle.net/tovic/Xcb8d/light/
  128. function dragInit(event) {
  129. if (!container.classList.contains("collapsed")) {
  130. drag.el = container;
  131. drag.elmX = event.pageX - drag.el.offsetLeft;
  132. drag.elmY = event.pageY - drag.el.offsetTop;
  133. selectionToggle(true);
  134. } else {
  135. drag.el = null;
  136. }
  137. drag.time = new Date().getTime() + 500;
  138. }
  139.  
  140. function dragMove(event) {
  141. if (drag.el !== null) {
  142. drag.el.style.left = `${event.pageX - drag.elmX}px`;
  143. drag.el.style.top = `${event.pageY - drag.elmY}px`;
  144. drag.el.style.right = "auto";
  145. }
  146. }
  147.  
  148. async function dragStop(event) {
  149. if (drag.el !== null) {
  150. dragSave();
  151. selectionToggle();
  152. }
  153. drag.el = null;
  154.  
  155. if (event.target === container) {
  156. // save container size on mouseup
  157. await GM.setValue(
  158. "github-toc-size",
  159. [container.clientWidth, container.clientHeight]
  160. );
  161. }
  162. }
  163.  
  164. async function dragSave(restore) {
  165. let adjLeft = null;
  166. let top = null;
  167. let val = null;
  168. if (restore) {
  169. // position restore (reset) popup to default position
  170. setPosition(defaults.left, defaults.top, defaults.right);
  171. } else {
  172. // Adjust saved left position to be measured from the center of the window
  173. // See issue #102
  174. const winHalf = window.innerWidth / 2;
  175. const left = winHalf - parseInt(container.style.left, 10);
  176. adjLeft = left * (left > winHalf ? 1 : -1);
  177. top = parseInt(container.style.top, 10);
  178. val = [adjLeft, top];
  179. }
  180. drag.elmX = adjLeft;
  181. drag.elmY = top;
  182. await GM.setValue("github-toc-location", val);
  183. }
  184.  
  185. function resize(_, left = drag.elmX, top = drag.elmY) {
  186. if (left !== null) {
  187. drag.elmX = left;
  188. drag.elmY = top;
  189. setPosition(((window.innerWidth / 2) + left) + "px", top + "px");
  190. }
  191. }
  192.  
  193. function setPosition(left, top, right = "auto") {
  194. container.style.left = left;
  195. container.style.right = right;
  196. container.style.top = top;
  197. }
  198.  
  199. async function setSize() {
  200. const size = await GM.getValue("github-toc-size", [250, 250]);
  201. container.style.width = `${size[0]}px`;
  202. container.style.height = `${size[1]}px`;
  203. }
  204.  
  205. // stop text selection while dragging
  206. function selectionToggle(disable) {
  207. const body = $("body");
  208. if (disable) {
  209. // save current "unselectable" value
  210. drag.unsel = body.getAttribute("unselectable");
  211. body.setAttribute("unselectable", "on");
  212. body.classList.add("ghus-toc-no-selection");
  213. on(body, "onselectstart", stopPropag);
  214. } else {
  215. if (drag.unsel) {
  216. body.setAttribute("unselectable", drag.unsel);
  217. }
  218. body.classList.remove("ghus-toc-no-selection");
  219. off(body, "onselectstart", stopPropag);
  220. }
  221. removeSelection();
  222. }
  223.  
  224. function removeSelection() {
  225. // remove text selection - http://stackoverflow.com/a/3171348/145346
  226. const sel = window.getSelection ? window.getSelection() : document.selection;
  227. if (sel) {
  228. if (sel.removeAllRanges) {
  229. sel.removeAllRanges();
  230. } else if (sel.empty) {
  231. sel.empty();
  232. }
  233. }
  234. }
  235.  
  236. async function tocShow() {
  237. container.classList.remove("collapsed");
  238. await GM.setValue("github-toc-hidden", false);
  239. }
  240.  
  241. async function tocHide() {
  242. container.classList.add("collapsed");
  243. await GM.setValue("github-toc-hidden", true);
  244. }
  245.  
  246. function tocToggle() {
  247. // don't toggle content on long clicks
  248. if (drag.time > new Date().getTime()) {
  249. if (container.classList.contains("collapsed")) {
  250. tocShow();
  251. } else {
  252. tocHide();
  253. }
  254. }
  255. }
  256. // hide TOC entirely, if no rendered markdown detected
  257. function tocView(isVisible) {
  258. const toc = $(".ghus-toc");
  259. if (toc) {
  260. toc.classList.toggle("ghus-toc-hidden", !isVisible);
  261. }
  262. }
  263.  
  264. function tocAdd() {
  265. if (!tocInit) {
  266. return;
  267. }
  268. const wrapper = $("#wiki-body, #readme");
  269. if (wrapper) {
  270. let indx, header, anchor, txt;
  271. let content = "<ul>";
  272. const anchors = $$(".markdown-body .anchor", wrapper);
  273. const len = anchors.length;
  274. if (len > 1) {
  275. for (indx = 0; indx < len; indx++) {
  276. anchor = anchors[indx];
  277. if (anchor.parentElement) {
  278. header = anchor.parentElement;
  279. // replace single & double quotes with right angled quotes
  280. txt = header.textContent
  281. .trim()
  282. .replace(regex.quote, "&#8217;")
  283. .replace(regex.doubleQuote, "&#8221;");
  284. content += `
  285. <li class="ghus-toc-${header.nodeName.toLowerCase()}">
  286. <span class="ghus-toc-icon octicon ghd-invert"></span>
  287. <a href="${anchor.hash}" title="${txt}">${txt}</a>
  288. </li>
  289. `;
  290. }
  291. }
  292. $(".boxed-group-inner", container).innerHTML = content + "</ul>";
  293. tocView(true);
  294. listCollapsible();
  295. } else {
  296. tocView();
  297. }
  298. } else {
  299. tocView();
  300. }
  301. }
  302.  
  303. function listCollapsible() {
  304. let indx, el, next, count, num, group;
  305. const els = $$("li", container);
  306. const len = els.length;
  307. for (indx = 0; indx < len; indx++) {
  308. count = 0;
  309. group = [];
  310. el = els[indx];
  311. next = el?.nextElementSibling;
  312. if (next) {
  313. num = el.className.match(regex.number)[0];
  314. while (next && !next.classList.contains("ghus-toc-h" + num)) {
  315. if (next.className.match(regex.number)[0] > num) {
  316. count++;
  317. group[group.length] = next;
  318. }
  319. next = next.nextElementSibling;
  320. }
  321. if (count > 0) {
  322. el.className += " collapsible collapsible-" + indx;
  323. addClass(group, "ghus-toc-childof-" + indx);
  324. }
  325. }
  326. }
  327. group = [];
  328. }
  329.  
  330. function toggleChildrenHandler(event) {
  331. // Allow doc link to work
  332. if (event.target.nodeName === "A") {
  333. return;
  334. }
  335. stopPropag(event);
  336. // click on icon, then target LI parent
  337. let els, name, indx;
  338. const el = event.target.closest("li");
  339. const collapse = el?.classList.contains("collapsed");
  340. if (event.target.classList.contains("ghus-toc-icon")) {
  341. if (event.shiftKey) {
  342. name = el.className.match(regex.header);
  343. els = name ? $$("." + name, container) : [];
  344. indx = els.length;
  345. while (indx--) {
  346. collapseChildren(els[indx], collapse);
  347. }
  348. } else {
  349. collapseChildren(el, collapse);
  350. }
  351. removeSelection();
  352. }
  353. }
  354.  
  355. function collapseChildren(el, collapse) {
  356. const name = el?.className.match(regex.collapsible);
  357. const children = name ? $$(".ghus-toc-childof-" + name[1], container) : null;
  358. if (children) {
  359. if (collapse) {
  360. el.classList.remove("collapsed");
  361. removeClass(children, "ghus-toc-hidden");
  362. } else {
  363. el.classList.add("collapsed");
  364. addClass(children, "ghus-toc-hidden");
  365. }
  366. }
  367. }
  368.  
  369. // keyboard shortcuts
  370. // GitHub hotkeys are set up to only go to a url, so rolling our own
  371. function keyboardCheck(event) {
  372. clearTimeout(keyboard.timer);
  373. // use "g+t" to toggle the panel; "g+r" to reset the position
  374. // keypress may be needed for non-alphanumeric keys
  375. const tocToggleKeys = defaults.toggle.split("+");
  376. const tocReset = defaults.restore.split("+");
  377. const key = String.fromCharCode(event.which).toLowerCase();
  378. const panelHidden = container.classList.contains("collapsed");
  379.  
  380. // press escape to close the panel
  381. if (event.which === 27 && !panelHidden) {
  382. tocHide();
  383. return;
  384. }
  385. // prevent opening panel while typing in comments
  386. if (regex.ignore.test(document.activeElement.nodeName)) {
  387. return;
  388. }
  389. // toggle TOC (g+t)
  390. if (keyboard.lastKey === tocToggleKeys[0] && key === tocToggleKeys[1]) {
  391. if (panelHidden) {
  392. tocShow();
  393. } else {
  394. tocHide();
  395. }
  396. }
  397. // reset TOC window position (g+r)
  398. if (keyboard.lastKey === tocReset[0] && key === tocReset[1]) {
  399. container.setAttribute("style", "");
  400. setSize();
  401. dragSave(true);
  402. }
  403. keyboard.lastKey = key;
  404. keyboard.timer = setTimeout(() => {
  405. keyboard.lastKey = null;
  406. }, defaults.delay);
  407. }
  408.  
  409. async function init() {
  410. // there is no ".header" on github.com/contact; and some other pages
  411. const header = $([...defaults.headerSelector, defaults.headerWrap].join(","));
  412. if (!header || tocInit) {
  413. return;
  414. }
  415. // insert TOC after header
  416. const location = await GM.getValue("github-toc-location", null);
  417. // restore last position
  418. resize(null, ...(location ? location : [null]));
  419.  
  420. // TOC saved state
  421. const hidden = await GM.getValue("github-toc-hidden", false);
  422. setSize();
  423. container.className = "ghus-toc boxed-group wiki-pages-box readability-sidebar" + (hidden ? " collapsed" : "");
  424. container.setAttribute("role", "navigation");
  425. container.setAttribute("unselectable", "on");
  426. container.setAttribute("index", "0");
  427. container.innerHTML = `
  428. <h3 class="js-wiki-toggle-collapse wiki-auxiliary-content" data-hotkey="${defaults.toggle.replace(regex.toggle, " ")}">
  429. <span class="ghus-toc-toggle ghus-toc-icon">
  430. <svg class="octicon" height="14" width="14" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 16 12">
  431. <path d="M2 13c0 .6 0 1-.6 1H.6c-.6 0-.6-.4-.6-1s0-1 .6-1h.8c.6 0 .6.4.6 1zm2.6-9h6.8c.6 0 .6-.4.6-1s0-1-.6-1H4.6C4 2 4 2.4 4 3s0 1 .6 1zM1.4 7H.6C0 7 0 7.4 0 8s0 1 .6 1h.8C2 9 2 8.6 2 8s0-1-.6-1zm0-5H.6C0 2 0 2.4 0 3s0 1 .6 1h.8C2 4 2 3.6 2 3s0-1-.6-1zm10 5H4.6C4 7 4 7.4 4 8s0 1 .6 1h6.8c.6 0 .6-.4.6-1s0-1-.6-1zm0 5H4.6c-.6 0-.6.4-.6 1s0 1 .6 1h6.8c.6 0 .6-.4.6-1s0-1-.6-1z"/>
  432. </svg>
  433. </span>
  434. <span class="ghus-toc-title">${title}</span>
  435. <a class="ghus-toc-docs tooltipped tooltipped-w" aria-label="Go to documentation" href="https://github.com/Mottie/GitHub-userscripts/wiki/GitHub-table-of-contents">
  436. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" height="16" width="14" viewBox="0 0 16 14">
  437. <path d="M6 10h2v2H6V10z m4-3.5c0 2.14-2 2.5-2 2.5H6c0-0.55 0.45-1 1-1h0.5c0.28 0 0.5-0.22 0.5-0.5v-1c0-0.28-0.22-0.5-0.5-0.5h-1c-0.28 0-0.5 0.22-0.5 0.5v0.5H4c0-1.5 1.5-3 3-3s3 1 3 2.5zM7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z" />
  438. </svg>
  439. </a>
  440. </h3>
  441. <div class="boxed-group-inner wiki-auxiliary-content wiki-auxiliary-content-no-bg"></div>
  442. `;
  443.  
  444. // add container
  445. const el = $(defaults.headerSelector.join(","));
  446. el.parentElement.insertBefore(container, el);
  447.  
  448. // make draggable
  449. on($("h3", container), "mousedown", dragInit);
  450. on(document, "mousemove", dragMove);
  451. on(document, "mouseup", dragStop);
  452. // toggle TOC
  453. on($(".ghus-toc-icon", container), "mouseup", tocToggle);
  454. on($("h3", container), "dblclick", tocHide);
  455. // prevent container content selection
  456. on(container, "onselectstart", stopPropag);
  457. on(container, "click", toggleChildrenHandler);
  458. // keyboard shortcuts
  459. on(document, "keydown", keyboardCheck);
  460. // keep window relative to middle on resize
  461. on(window, "resize", resize);
  462.  
  463. tocInit = true;
  464. tocAdd();
  465. }
  466.  
  467. // Add GM options
  468. GM.registerMenuCommand("Set Table of Contents Title", async () => {
  469. title = prompt("Table of Content Title:", title);
  470. await GM.setValue("github-toc-title", title);
  471. $("h3 .ghus-toc-title", container).textContent = title;
  472. });
  473.  
  474. on(document, "ghmo:container", tocAdd);
  475. on(document, "ghmo:preview", tocAdd);
  476. init();
  477.  
  478. })();