GitHub Code Folding

A userscript that adds code folding to GitHub files

当前为 2020-05-12 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name GitHub Code Folding
  3. // @version 1.1.0
  4. // @description A userscript that adds code folding to GitHub files
  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.addStyle
  12. // @grant GM_addStyle
  13. // @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js?updated=20180103
  14. // @require https://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=666427
  15. // @icon https://github.githubassets.com/pinned-octocat.svg
  16. // ==/UserScript==
  17. /**
  18. * This userscript has been heavily modified from the "github-code-folding"
  19. * Chrome extension Copyright 2016 by Noam Lustiger; under an MIT license
  20. * https://github.com/noam3127/github-code-folding
  21. */
  22. (() => {
  23. "use strict";
  24.  
  25. GM.addStyle(`
  26. td.blob-code.blob-code-inner { position:relative; padding-left:10px; }
  27. .ghcf-collapser { position:absolute; left:2px; width:22px; cursor:pointer; }
  28. .ghcf-collapser:after { display: inline-block; vertical-align: middle; content:"\u25bc"; opacity:.5; transition:.15s; }
  29. .ghcf-collapser:hover:after { opacity:1; }
  30. .ghcf-collapsed.ghcf-collapser:after { transform:rotate(-90deg); opacity:.8; }
  31. .ghcf-hidden-line { display:none; }
  32. .ghcf-ellipsis { padding:1px 2px; margin-left:2px; cursor:pointer;
  33. background:rgba(255,235,59,.4); position:relative; z-index:1; }
  34. .ghcf-ellipsis:hover { background:rgba(255,235,59,.7); }
  35. `);
  36.  
  37. const blocks = {};
  38. const ellipsis = document.createElement("span");
  39. const triangle = document.createElement("span");
  40.  
  41. triangle.className = "ghcf-collapser";
  42. ellipsis.className = "pl-smi ghcf-ellipsis";
  43. ellipsis.innerHTML = "…";
  44.  
  45. function countInitialWhiteSpace(arr) {
  46. const getWhiteSpaceIndex = i => {
  47. if (arr[i] !== " " && arr[i] !== "\t" && arr[i] !== "\xa0") {
  48. return i;
  49. }
  50. return getWhiteSpaceIndex(++i);
  51. };
  52. return getWhiteSpaceIndex(0);
  53. }
  54.  
  55. function getPreviousSpaces(map, lineNum) {
  56. let prev = map.get(lineNum - 1);
  57. return prev === -1
  58. ? getPreviousSpaces(map, lineNum - 1)
  59. : {
  60. lineNum: lineNum - 1,
  61. count: prev
  62. };
  63. }
  64.  
  65. function getLineNumber(el) {
  66. let elm = el.closest("tr");
  67. if (elm) {
  68. elm = elm.querySelector("[data-line-number]");
  69. return elm ? parseInt(elm.dataset.lineNumber, 10) : "";
  70. }
  71. return "";
  72. }
  73.  
  74. function getCodeLines(codeBlock) {
  75. return $$(".blob-code-inner", codeBlock);
  76. }
  77.  
  78. function toggleCode({ action, codeBlock, index, depth }) {
  79. let els, lineNums;
  80. const codeLines = getCodeLines(codeBlock) || [];
  81. const pairs = blocks[codeBlock.dataset.blockIndex];
  82. if (!pairs || codeLines.length === 0) {
  83. return;
  84. }
  85. // depth is a string containing a specific depth number to toggle
  86. if (depth) {
  87. els = $$(`.ghcf-collapser[data-depth="${depth}"]`, codeBlock);
  88. lineNums = els.map(el => {
  89. el.classList.toggle("ghcf-collapsed", action === "hide");
  90. return getLineNumber(el);
  91. });
  92. } else {
  93. lineNums = [index];
  94. }
  95.  
  96. if (action === "hide") {
  97. lineNums.forEach(start => {
  98. let elm;
  99. let end = pairs.get(start - 1);
  100. codeLines.slice(start, end).forEach(el => {
  101. elm = el.closest("tr");
  102. if (elm) {
  103. elm.classList.add("ghcf-hidden-line");
  104. }
  105. });
  106. if (!$(".ghcf-ellipsis", codeLines[start - 1])) {
  107. elm = $(".ghcf-collapser", codeLines[start - 1]);
  108. elm.parentNode.insertBefore(
  109. ellipsis.cloneNode(true),
  110. elm.nextSibling
  111. );
  112. }
  113. });
  114. } else if (action === "show") {
  115. lineNums.forEach(start => {
  116. let end = pairs.get(start - 1);
  117. codeLines.slice(start, end).forEach(el => {
  118. let elm = el.closest("tr");
  119. if (elm) {
  120. elm.classList.remove("ghcf-hidden-line");
  121. removeEls(".ghcf-ellipsis", elm);
  122. }
  123. elm = $(".ghcf-collapsed", elm);
  124. if (elm) {
  125. elm.classList.remove("ghcf-collapsed");
  126. }
  127. });
  128. removeEls(".ghcf-ellipsis", codeLines[start - 1]);
  129. });
  130. }
  131. // shift ends up selecting text on the page, so clear it
  132. if (lineNums.length > 1) {
  133. removeSelection();
  134. }
  135. }
  136.  
  137. function addBindings() {
  138. document.addEventListener("click", event => {
  139. let index, elm, isCollapsed;
  140. const el = event.target;
  141. const codeBlock = el.closest(".highlight");
  142.  
  143. // click on collapser
  144. if (el && el.classList.contains("ghcf-collapser")) {
  145. isCollapsed = el.classList.contains("ghcf-collapsed");
  146. index = getLineNumber(el);
  147. // Shift + click to toggle them all
  148. if (index && event.getModifierState("Shift")) {
  149. return toggleCode({
  150. action: isCollapsed ? "show" : "hide",
  151. codeBlock,
  152. index,
  153. depth: el.dataset.depth
  154. });
  155. }
  156. if (index) {
  157. if (isCollapsed) {
  158. el.classList.remove("ghcf-collapsed");
  159. toggleCode({ action: "show", codeBlock, index });
  160. } else {
  161. el.classList.add("ghcf-collapsed");
  162. toggleCode({ action: "hide", codeBlock, index });
  163. }
  164. }
  165. return;
  166. }
  167.  
  168. // click on ellipsis
  169. if (el && el.classList.contains("ghcf-ellipsis")) {
  170. elm = $(".ghcf-collapsed", el.parentNode);
  171. if (elm) {
  172. elm.classList.remove("ghcf-collapsed");
  173. }
  174. index = getLineNumber(el);
  175. if (index) {
  176. toggleCode({ action: "show", codeBlock, index });
  177. }
  178. }
  179. });
  180. }
  181.  
  182. function addCodeFolding() {
  183. // Keep .file in case someone needs this userscript for GitHub Enterprise
  184. if ($(".file table.highlight, .blob-wrapper table.highlight")) {
  185. $$("table.highlight").forEach((codeBlock, blockIndex) => {
  186. if (codeBlock && codeBlock.classList.contains("ghcf-processed")) {
  187. // Already processed
  188. return;
  189. }
  190. const codeLines = getCodeLines(codeBlock);
  191. removeEls("span.ghcf-collapser", codeBlock);
  192. if (codeLines) {
  193. // In case this script has already been run and modified the DOM on a
  194. // previous page in github, make sure to reset it.
  195. codeBlock.classList.add("ghcf-processed");
  196. codeBlock.dataset.blockIndex = blockIndex;
  197.  
  198. const spaceMap = new Map();
  199. const stack = [];
  200. const pairs = blocks[blockIndex] = new Map();
  201.  
  202. codeLines.forEach((el, lineNum) => {
  203. let prevSpaces;
  204. let line = el.textContent;
  205. let count = line.trim().length
  206. ? countInitialWhiteSpace(line.split(""))
  207. : -1;
  208. spaceMap.set(lineNum, count);
  209.  
  210. function tryPair() {
  211. let el;
  212. let top = stack[stack.length - 1];
  213. if (count !== -1 && count <= spaceMap.get(top)) {
  214. pairs.set(top, lineNum);
  215. // prepend triangle
  216. el = triangle.cloneNode();
  217. el.dataset.depth = count + 1;
  218. codeLines[top].appendChild(el, codeLines[top].childNodes[0]);
  219. stack.pop();
  220. return tryPair();
  221. }
  222. }
  223. tryPair();
  224.  
  225. prevSpaces = getPreviousSpaces(spaceMap, lineNum);
  226. if (count > prevSpaces.count) {
  227. stack.push(prevSpaces.lineNum);
  228. }
  229. });
  230. }
  231. });
  232. }
  233. }
  234.  
  235. function $(selector, el) {
  236. return (el || document).querySelector(selector);
  237. }
  238.  
  239. function $$(selector, el) {
  240. return Array.from((el || document).querySelectorAll(selector));
  241. }
  242.  
  243. function removeEls(selector, el) {
  244. let els = $$(selector, el);
  245. let index = els.length;
  246. while (index--) {
  247. els[index].parentNode.removeChild(els[index]);
  248. }
  249. }
  250.  
  251. function removeSelection() {
  252. // remove text selection - https://stackoverflow.com/a/3171348/145346
  253. const sel = window.getSelection
  254. ? window.getSelection()
  255. : document.selection;
  256. if (sel) {
  257. if (sel.removeAllRanges) {
  258. sel.removeAllRanges();
  259. } else if (sel.empty) {
  260. sel.empty();
  261. }
  262. }
  263. }
  264.  
  265. document.addEventListener("ghmo:container", addCodeFolding);
  266. addCodeFolding();
  267. addBindings();
  268.  
  269. })();