GitHub Table of Contents

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

当前为 2019-03-30 提交的版本,查看 最新版本

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