GitHub TOC

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

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

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