GitHub Table of Contents

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

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

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

QingJ © 2025

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