GitHub Collapse Markdown

A userscript that collapses markdown headers

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

  1. // ==UserScript==
  2. // @name GitHub Collapse Markdown
  3. // @version 1.1.4
  4. // @description A userscript that collapses markdown headers
  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. // @include https://help.github.com/*
  10. // @run-at document-idle
  11. // @grant GM_addStyle
  12. // @grant GM_getValue
  13. // @grant GM_setValue
  14. // @grant GM_registerMenuCommand
  15. // @author Rob Garrison
  16. // ==/UserScript==
  17. /* global GM_addStyle, GM_getValue, GM_setValue, GM_registerMenuCommand */
  18. /* jshint esnext:true, unused:true */
  19. (() => {
  20. "use strict";
  21.  
  22. const defaultColors = [
  23. // palette generated by http://tools.medialab.sciences-po.fr/iwanthue/
  24. // (colorblind friendly, soft)
  25. "#6778d0", "#ac9c3d", "#b94a73", "#56ae6c", "#9750a1", "#ba543d"
  26. ],
  27.  
  28. headers = "H1 H2 H3 H4 H5 H6".split(" "),
  29. collapsed = "ghcm-collapsed",
  30. arrowColors = document.createElement("style");
  31.  
  32. let startCollapsed = GM_getValue("ghcm-collapsed", false),
  33. colors = GM_getValue("ghcm-colors", defaultColors);
  34.  
  35. GM_addStyle(`
  36. .markdown-body h1, .markdown-body h2, .markdown-body h3,
  37. .markdown-body h4, .markdown-body h5, .markdown-body h6,
  38. .markdown-format h1, .markdown-format h2, .markdown-format h3,
  39. .markdown-format h4, .markdown-format h5, .markdown-format h6 {
  40. position:relative;
  41. padding-right:.8em;
  42. cursor:pointer;
  43. }
  44. .markdown-body h1:after, .markdown-body h2:after, .markdown-body h3:after,
  45. .markdown-body h4:after, .markdown-body h5:after, .markdown-body h6:after,
  46. .markdown-format h1:after, .markdown-format h2:after, .markdown-format h3:after,
  47. .markdown-format h4:after, .markdown-format h5:after, .markdown-format h6:after {
  48. display:inline-block;
  49. position:absolute;
  50. right:0;
  51. top:calc(50% - .5em);
  52. font-size:.8em;
  53. content:"\u25bc";
  54. }
  55. .markdown-body .${collapsed}:after, .markdown-format .${collapsed}:after {
  56. transform: rotate(90deg);
  57. }
  58. /* clicking on header link won't pass svg as the event.target */
  59. .octicon-link, .octicon-link > * {
  60. pointer-events:none;
  61. }
  62. .ghcm-hidden {
  63. display:none !important;
  64. }
  65. `);
  66.  
  67. function addColors() {
  68. arrowColors.textContent = `
  69. .markdown-body h1:after, .markdown-format h1:after { color:${colors[0]} }
  70. .markdown-body h2:after, .markdown-format h2:after { color:${colors[1]} }
  71. .markdown-body h3:after, .markdown-format h3:after { color:${colors[2]} }
  72. .markdown-body h4:after, .markdown-format h4:after { color:${colors[3]} }
  73. .markdown-body h5:after, .markdown-format h5:after { color:${colors[4]} }
  74. .markdown-body h6:after, .markdown-format h6:after { color:${colors[5]} }
  75. `;
  76. }
  77.  
  78. function toggle(el, shifted) {
  79. if (el) {
  80. el.classList.toggle(collapsed);
  81. let els;
  82. const name = el.nodeName || "",
  83. level = parseInt(name.replace(/[^\d]/, ""), 10),
  84. isCollapsed = el.classList.contains(collapsed);
  85. if (shifted) {
  86. // collapse all same level anchors
  87. els = $$(`.markdown-body ${name}, .markdown-format ${name}`);
  88. for (el of els) {
  89. nextHeader(el, level, isCollapsed);
  90. }
  91. } else {
  92. nextHeader(el, level, isCollapsed);
  93. }
  94. removeSelection();
  95. }
  96. }
  97.  
  98. function nextHeader(el, level, isCollapsed) {
  99. el.classList[isCollapsed ? "add" : "remove"](collapsed);
  100. const selector = headers.slice(0, level).join(","),
  101. name = [collapsed, "ghcm-hidden"],
  102. els = [];
  103. el = el.nextElementSibling;
  104. while (el && !el.matches(selector)) {
  105. els[els.length] = el;
  106. el = el.nextElementSibling;
  107. }
  108. if (els.length) {
  109. if (isCollapsed) {
  110. els.forEach(el => {
  111. el.classList.add("ghcm-hidden");
  112. });
  113. } else {
  114. els.forEach(el => {
  115. el.classList.remove(...name);
  116. });
  117. }
  118. }
  119. }
  120.  
  121. // show siblings of hash target
  122. function siblings(target) {
  123. let el = target.nextElementSibling,
  124. els = [target];
  125. const level = parseInt((target.nodeName || "").replace(/[^\d]/, ""), 10),
  126. selector = headers.slice(0, level - 1).join(",");
  127. while (el && !el.matches(selector)) {
  128. els[els.length] = el;
  129. el = el.nextElementSibling;
  130. }
  131. el = target.previousElementSibling;
  132. while (el && !el.matches(selector)) {
  133. els[els.length] = el;
  134. el = el.previousElementSibling;
  135. }
  136. if (els.length) {
  137. els = els.filter(el => {
  138. return el.nodeName === target.nodeName;
  139. });
  140. removeClass(els, "ghcm-hidden");
  141. }
  142. nextHeader(target, level, false);
  143. }
  144.  
  145. function removeSelection() {
  146. // remove text selection - http://stackoverflow.com/a/3171348/145346
  147. const sel = window.getSelection ? window.getSelection() : document.selection;
  148. if (sel) {
  149. if (sel.removeAllRanges) {
  150. sel.removeAllRanges();
  151. } else if (sel.empty) {
  152. sel.empty();
  153. }
  154. }
  155. }
  156.  
  157. function addBinding() {
  158. document.addEventListener("click", event => {
  159. let target = event.target;
  160. const name = (target && (target.nodeName || "")).toLowerCase();
  161. if (name === "path") {
  162. target = closest(target, "svg");
  163. }
  164. if (!target || target.classList.contains("anchor") ||
  165. name === "a" || name === "img" ||
  166. // add support for "pointer-events:none" applied to "anchor" in
  167. // https://github.com/StylishThemes/GitHub-FixedHeader
  168. target.classList.contains("octicon-link")) {
  169. return;
  170. }
  171. // check if element is inside a header
  172. target = closest(event.target, headers.join(","));
  173. if (target && headers.indexOf(target.nodeName || "") > -1) {
  174. // make sure the header is inside of markdown
  175. if (closest(target, ".markdown-body, .markdown-format")) {
  176. toggle(target, event.shiftKey);
  177. }
  178. }
  179. });
  180. }
  181.  
  182. function checkHash() {
  183. let el, els, md;
  184. const mds = $$(".markdown-body, .markdown-format"),
  185. tmp = (window.location.hash || "").replace(/#/, "");
  186. for (md of mds) {
  187. els = $$(headers.join(","), md);
  188. if (els.length > 1) {
  189. for (el of els) {
  190. if (el && !el.classList.contains(collapsed)) {
  191. toggle(el, true);
  192. }
  193. }
  194. }
  195. }
  196. // open up
  197. if (tmp) {
  198. els = $(`#user-content-${tmp}`);
  199. if (els && els.classList.contains("anchor")) {
  200. el = els.parentNode;
  201. if (el.matches(headers.join(","))) {
  202. siblings(el);
  203. document.documentElement.scrollTop = el.offsetTop;
  204. // set scrollTop a second time, in case of browser lag
  205. setTimeout(() => {
  206. document.documentElement.scrollTop = el.offsetTop;
  207. }, 500);
  208. }
  209. }
  210. }
  211. }
  212.  
  213. function checkColors() {
  214. if (!colors || colors.length !== 6) {
  215. colors = [].concat(defaultColors);
  216. }
  217. }
  218.  
  219. function init() {
  220. document.querySelector("head").appendChild(arrowColors);
  221. checkColors();
  222. addColors();
  223. addBinding();
  224. if (startCollapsed) {
  225. checkHash();
  226. }
  227. }
  228.  
  229. function $(selector, el) {
  230. return (el || document).querySelector(selector);
  231. }
  232.  
  233. function $$(selectors, el) {
  234. return Array.from((el || document).querySelectorAll(selectors));
  235. }
  236.  
  237. function closest(el, selector) {
  238. while (el && el.nodeName !== "BODY" && !el.matches(selector)) {
  239. el = el.parentNode;
  240. }
  241. return el && el.matches(selector) ? el : null;
  242. }
  243.  
  244. // Add GM options
  245. GM_registerMenuCommand("Set collapse markdown state", () => {
  246. const val = prompt(
  247. "Set initial state to (c)ollapsed or (e)xpanded (first letter necessary):",
  248. startCollapsed ? "collapsed" : "expanded"
  249. );
  250. if (val !== null) {
  251. startCollapsed = /^c/.test(val);
  252. GM_setValue("ghcm-collapsed", startCollapsed);
  253. console.log(
  254. `GitHub Collapse Markdown: Headers will ${startCollapsed ? "be" : "not be"} initially collapsed`
  255. );
  256. }
  257. });
  258.  
  259. GM_registerMenuCommand("Set collapse markdown colors", () => {
  260. let val = prompt("Set header arrow colors:", JSON.stringify(colors));
  261. if (val !== null) {
  262. // allow pasting in a JSON format
  263. try {
  264. val = JSON.parse(val);
  265. if (val && val.length === 6) {
  266. colors = val;
  267. GM_setValue("ghcm-colors", colors);
  268. console.log("GitHub Collapse Markdown: colors set to", colors);
  269. addColors();
  270. return;
  271. }
  272. console.error(
  273. "GitHub Collapse Markdown: invalid color definition (6 colors)",
  274. val
  275. );
  276. // reset colors to default (in case colors variable is corrupted)
  277. checkColors();
  278. } catch (err) {
  279. console.error("GitHub Collapse Markdown: invalid JSON");
  280. }
  281. }
  282. });
  283.  
  284. init();
  285. })();