GitHub Table of Contents

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

目前為 2021-02-21 提交的版本,檢視 最新版本

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