GitHub TOC

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

当前为 2017-04-04 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址