GitHub Table of Contents

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

当前为 2021-01-31 提交的版本,查看 最新版本

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