GitHub Table of Contents

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

当前为 2019-09-06 提交的版本,查看 最新版本

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