GitHub TOC

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

当前为 2016-12-29 提交的版本,查看 最新版本

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