GitHub TOC

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

As of 2017-04-14. See the latest version.

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