GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

As of 2018-12-01. See the latest version.

  1. // ==UserScript==
  2. // @name GitHub Dark Script
  3. // @version 2.4.11
  4. // @description GitHub Dark in userscript form, with a settings panel
  5. // @license MIT
  6. // @author StylishThemes
  7. // @namespace https://github.com/StylishThemes
  8. // @include /^https?://((blog|gist|guides|help|raw|status|developer)\.)?github\.com/((?!generated_pages\/preview).)*$/
  9. // @include /^https://*.githubusercontent.com/*$/
  10. // @include /^https://*graphql-explorer.githubapp.com/*$/
  11. // @run-at document-start
  12. // @inject-into content
  13. // @grant GM.addStyle
  14. // @grant GM_addStyle
  15. // @grant GM.getValue
  16. // @grant GM_getValue
  17. // @grant GM.setValue
  18. // @grant GM_setValue
  19. // @grant GM.info
  20. // @grant GM_info
  21. // @grant GM.xmlHttpRequest
  22. // @grant GM_xmlhttpRequest
  23. // @grant GM.registerMenuCommand
  24. // @grant GM_registerMenuCommand
  25. // @connect githubusercontent.com
  26. // @connect raw.githubusercontent.com
  27. // @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
  28. // @require https://greatest.deepsurf.us/scripts/15563-jscolor/code/jscolor.js?version=106439
  29. // @require https://greatest.deepsurf.us/scripts/28721-mutations/code/mutations.js?version=634242
  30. // @icon https://avatars3.githubusercontent.com/u/6145677?v=3&s=200
  31. // ==/UserScript==
  32. /* global GM, jscolor */
  33. /* jshint esnext:true, unused:true */
  34. (async () => {
  35. "use strict";
  36.  
  37. const version = GM.info.script.version,
  38.  
  39. // delay until package.json allowed to load
  40. delay = 8.64e7, // 24 hours in milliseconds
  41.  
  42. // Keyboard shortcut to open ghd panel (only a two key combo coded)
  43. keyboardOpen = "g+0",
  44. keyboardToggle = "g+-",
  45. // keyboard shortcut delay from first to second letter
  46. keyboardDelay = 1000,
  47.  
  48. // base urls to fetch style and package.json
  49. root = "https://raw.githubusercontent.com/StylishThemes/GitHub-Dark/master/",
  50.  
  51. defaults = {
  52. attach : "scroll",
  53. color : "#4183C4",
  54. enable : true,
  55. font : "Menlo",
  56. image : "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAABGBAMAAACDAP+3AAAAGFBMVEUfHx8eHh4dHR0bGxshISEiIiIlJSUjIyM9IpsJAAAFjUlEQVR4AT3UuZLcOBaF4QuI2XJxboIhF/eQFe1WovoBAAqccpkaZpc5+4yrXa8/RGpx/lrIXPjFCYjTp9z8REqF4VYNWB3Av3zQJ6b6xBwlKB/9kRkCjXVwGH3ziK5UcjFHVkmgY6osiBsGDFfseqq2ZbTz7E00qBDpzOxnD7ToABeros1vM6MX0rBQaG1ith1A/HJkvkHxsPGJ82dP8vVCyWmbyPTaAfGzg40bgIdrv2f3pBVPycUcufx+BSUUWDuCZi6zBqdM50ElKYPODqtLDjc31rBb9CZ59lbN/JScuMxHLUBcGiy6QRH9zpwgZGhRj8qSydPVgNNVgbWqYX3HbM9K2rqTnKVmsmwKWzc1ffEd20+Zq3Ji65kl6TSjALNvzmJt4Pi2f1etytGJmy5erLAgbNY4bjykC3YCLIS3nSZMKgwRsBarWgjdeVzIEDzpTkoOUArTF4WFXYHwxY585sT0nmTYMxmXfs8fzwswfnam8TMU49bvqSRnyRPnqlno4tVQQiH2A9Za8tNTfXQ0lxbSxUaZna0uLlj9Q0XzD96CpsOZUftolINKBWJpAOoAJC0T6QqZnOtfvcfJFcDrD4Cuy5Hng316XrqzJ204HynyHwWed6i+XGF40Uw2T7Lc71HyssngEOrgONfBY7wvW0UZdVAma5xmSNjRp3xkvKJkW6aSg7PK4K0+mbKqYB0WYBgWwxCXiS74zBCVlEFpYQDEwjcA1qccb5yO6ZL8ozt/h3wHSCdWzLuqxU2ZZ9ev9MvRMbMvV9BQgN0qrFjlkzPQanI9nuaGCokVK2LV1Y2egyY1aFQGxjM9I7RBBAgyGEJtpKHP0lUySSeWCpyKHMT2pmM/vyP55u2Rw5lcSeabAfgiG5TPDX3uP3QvcoSipJXQByUCjS4C8VXqxEEZOJxzmJoyogFNJBRsCJs2XmoWWrWFqTsnbwtSn43gNFTTob9/SEpaPJNhUBKDGoZGCMINxvBv8vuKbb//lg/sK0wfPgBica/QsSk5F3KK4Ui6Yw+uv4+DWEOFbhdPOnbY5PLFpzrZMhakeqomY0Vz0TO+elQGTWdCk1IYFAOaoZg0IJQhT+YreXF+yia+O1cgtGufjXxQw28f85RPXfd15zv13ABoD15kB7FKJ/7pbHKP6+9TgNgkVj68NeV8Tp24f7OOndCgJzR3RNJBPNFReCmstMVqvjjzBoeK4GOFoBN32CPxu+4TwwBDa4DJTe/OU9c9ku7EGyfOVxh+fw9g/AATxPqKTEXJKEdCIBkB4iBUlO6MjUrWi6M5Kz31YAqFsYaCeB0KJC5d1+foo3LQWSfRaDrwdAQrMEC27yDZXJf7TlOJ2Bczr1di3OWvZB6XrvvqPuWJPDk9dAHgm7LvuZJTEdKqO3J3XgostArEnvkqgUznx3PX7cSzz1FXZyvakTA4XVVMbCPFPK1cFj66S0WoqQI1XG2uoU7CMPquO2VaUDJFQMdVgXKD2bpz6ufzzxXbxszHQ9fGO/F7A998yBQG6cShE+P+Pk7t1FwfF1QHN1Eui1VapRxCdj8tCtI1bog1Fo011Sx9u3o6c9bufI6wAT26Av9xJ+WWpTKbbBPp3K/1LbC4Vuhv396RCbJw4untjxVPndj+dIB9dVD8z2dylZ+6vMeJwbYChHJkvHV2J3fdHsJPASeHhrXq6QheXu1nBhUr5u6ryT0I13BFKD01ViZ/n3oaziRG7c6Ayg7g1LPeztNdT36ueMqcN4XGv3finjfv+7I/kMJ4d046MUanOA1QtMH1kLlfFasm99NiutSw63yNDeH4zeL1Uu8XKHNfcThPSSNwchGMbgUETScwkCcK77pH2jsgrAssvVyB8FLJ7GrmwyD8eVqsHoY/FwIv9T7lPu9+Yf8/9+w4nS1ma78AAAAASUVORK5CYII=')",
  57. tab : 0, // 0 is disabled
  58. theme : "Twilight", // GitHub
  59. themeCm: "Twilight", // CodeMirror
  60. themeJp: "Twilight", // Jupyter
  61. type : "tiled",
  62. wrap : false,
  63.  
  64. // toggle buttons
  65. enableCodeWrap : true,
  66. enableMonospace : true,
  67. // diff toggle + accordion mode
  68. modeDiffToggle : "1",
  69.  
  70. // internal variables
  71. date : 0,
  72. version : 0,
  73. rawCss : "",
  74. cssgithub : "",
  75. csscodemirror: "",
  76. cssjupyter : "",
  77. processedCss : ""
  78. },
  79.  
  80. // extract style & theme name
  81. regex = /\/\*! [^*]+ \*\//,
  82. themesXref = {
  83. github: {
  84. placeholder: "syntax-theme",
  85. folder: "themes/github/"
  86. },
  87. codemirror: {
  88. placeholder: "syntax-codemirror",
  89. folder: "themes/codemirror/"
  90. },
  91. jupyter: {
  92. placeholder: "syntax-jupyter",
  93. folder: "themes/jupyter/"
  94. }
  95. },
  96. // available theme names
  97. themes = {
  98. github: {
  99. "Ambiance": "ambiance",
  100. "Chaos": "chaos",
  101. "Clouds Midnight": "clouds-midnight",
  102. "Cobalt": "cobalt",
  103. "GitHub Dark": "github-dark",
  104. "Idle Fingers": "idle-fingers",
  105. "Kr Theme": "kr-theme",
  106. "Merbivore": "merbivore",
  107. "Merbivore Soft": "merbivore-soft",
  108. "Mono Industrial": "mono-industrial",
  109. "Mono Industrial Clear": "mono-industrial-clear",
  110. "Monokai": "monokai",
  111. "Monokai Spacegray Eighties": "monokai-spacegray-eighties",
  112. "Obsidian": "obsidian",
  113. "One Dark": "one-dark",
  114. "Pastel on Dark": "pastel-on-dark",
  115. "Solarized Dark": "solarized-dark",
  116. "Terminal": "terminal",
  117. "Tomorrow Night": "tomorrow-night",
  118. "Tomorrow Night Blue": "tomorrow-night-blue",
  119. "Tomorrow Night Bright": "tomorrow-night-bright",
  120. "Tomorrow Night Eigthies": "tomorrow-night-eighties",
  121. "Twilight": "twilight",
  122. "Vibrant Ink": "vibrant-ink"
  123. },
  124. // CodeMirror themes
  125. codemirror: {
  126. "Ambiance": "ambiance",
  127. "Base16 Ocean Dark": "base16-ocean-dark",
  128. "Cobalt": "cobalt",
  129. "Dracula": "dracula",
  130. "Material": "material",
  131. "Monokai": "monokai",
  132. "Monokai Spacegray Eighties": "monokai-spacegray-eighties",
  133. "One Dark": "one-dark",
  134. "Pastel on Dark": "pastel-on-dark",
  135. "Solarized Dark": "solarized-dark",
  136. "Tomorrow Night Bright": "tomorrow-night-bright",
  137. "Tomorrow Night Eigthies": "tomorrow-night-eighties",
  138. "Twilight": "twilight",
  139. "Vibrant Ink": "vibrant-ink"
  140. },
  141. // Jupyter (pygments) themes
  142. jupyter: {
  143. "Base16 Ocean Dark": "base16-ocean",
  144. "Dracula": "dracula",
  145. "GitHub Dark": "github-dark",
  146. "Idle Fingers": "idle-fingers",
  147. "Monokai": "monokai",
  148. "Monokai Spacegray Eighties": "monokai-spacegray-eighties",
  149. "Obsidian": "obsidian",
  150. "Pastel on Dark": "pastel-on-dark",
  151. "Solarized Dark": "solarized-dark",
  152. "Tomorrow Night": "tomorrow-night",
  153. "Tomorrow Night Blue": "tomorrow-night-blue",
  154. "Tomorrow Night Bright": "tomorrow-night-bright",
  155. "Tomorrow Night Eigthies": "tomorrow-night-eighties",
  156. "Twilight": "twilight"
  157. }
  158. },
  159.  
  160. type = {
  161. tiled: `
  162. background-repeat: repeat !important;
  163. background-size: auto !important;
  164. background-position: left top !important;
  165. `,
  166. fit: `
  167. background-repeat: no-repeat !important;
  168. background-size: cover !important;
  169. background-position: center top !important;
  170. `
  171. },
  172.  
  173. wrapCss = {
  174. wrapped: `
  175. white-space: pre-wrap !important;
  176. word-break: break-all !important;
  177. overflow-wrap: break-word !important;
  178. display: block !important;
  179. `,
  180. unwrap: `
  181. white-space: pre !important;
  182. word-break: normal !important;
  183. display: block !important;
  184. `
  185. },
  186.  
  187. // https://github.com/StylishThemes/GitHub-code-wrap/blob/master/github-code-wrap.css
  188. wrapCodeCss = `
  189. /* GitHub: Enable wrapping of long code lines */
  190. .blob-code-inner,
  191. .markdown-body pre > code,
  192. .markdown-body .highlight > pre { ${wrapCss.wrapped} }
  193. td.blob-code-inner {
  194. display: table-cell !important;
  195. }
  196. `,
  197.  
  198. wrapIcon = `
  199. <svg xmlns="http://www.w3.org/2000/svg" width="768" height="768" viewBox="0 0 768 768">
  200. <path d="M544.5 352.5q52.5 0 90 37.5t37.5 90-37.5 90-90 37.5H480V672l-96-96 96-96v64.5h72q25.5 0 45-19.5t19.5-45-19.5-45-45-19.5H127.5v-63h417zm96-192v63h-513v-63h513zm-513 447v-63h192v63h-192z"/>
  201. </svg>
  202. `,
  203.  
  204. monospaceIcon = `
  205. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 32 32">
  206. <path d="M5.91 7.31v8.41c0 .66.05 1.09.14 1.31.09.21.23.37.41.48.18.11.52.16 1.02.16v.41H2.41v-.41c.5 0 .86-.05 1.03-.14.16-.11.3-.27.41-.5.11-.23.16-.66.16-1.3V11.7c0-1.14-.04-1.87-.11-2.2-.04-.26-.13-.42-.24-.53-.11-.1-.27-.14-.46-.14-.21 0-.48.05-.77.18l-.18-.41 3.14-1.28h.52v-.01zm-.95-5.46c.32 0 .59.11.82.34.23.23.34.5.34.82 0 .32-.11.59-.34.82-.23.22-.51.34-.82.34-.32 0-.59-.11-.82-.34s-.36-.5-.36-.82c0-.32.11-.59.34-.82.24-.23.51-.34.84-.34zm19.636 19.006h-3.39v-1.64h5.39v9.8h3.43v1.66h-9.18v-1.66h3.77v-8.16h-.02zm.7-6.44c.21 0 .43.04.63.13.18.09.36.2.5.34s.25.3.34.5c.07.18.13.39.13.61 0 .22-.04.41-.13.61s-.19.36-.34.5-.3.25-.5.32c-.2.09-.39.13-.62.13-.21 0-.43-.04-.61-.12-.19-.07-.35-.19-.5-.34-.14-.14-.25-.3-.34-.5-.07-.2-.13-.39-.13-.61s.04-.43.13-.61c.07-.18.2-.36.34-.5s.31-.25.5-.34c.17-.09.39-.12.6-.12zM2 30L27.82 2H30L4.14 30H2z"/>
  207. </svg>
  208. `,
  209.  
  210. fileIcon = `
  211. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="10" height="6.5" viewBox="0 0 10 6.5">
  212. <path d="M0 1.5L1.5 0l3.5 3.7L8.5.0 10 1.5 5 6.5 0 1.5z"/>
  213. </svg>
  214. `,
  215.  
  216. $style = make({
  217. el: "style",
  218. cl4ss: "ghd-style"
  219. });
  220.  
  221. let timer, picker, // jscolor picker
  222. isInitialized = "pending",
  223. // prevent mutationObserver from going nuts
  224. isUpdating = false,
  225. // set when css code to test is pasted into the settings panel
  226. testing = false,
  227. //
  228. debug = true,
  229. data = {};
  230.  
  231. function updatePanel() {
  232. if (!isInitialized || !$("#ghd-settings-inner")) { return; }
  233. // prevent multiple change events from processing
  234. isUpdating = true;
  235.  
  236. let temp, el,
  237. body = $("body"),
  238. panel = $("#ghd-settings-inner");
  239.  
  240. $(".ghd-attach", panel).value = data.attach || defaults.attach;
  241. $(".ghd-font", panel).value = data.font || defaults.font;
  242. $(".ghd-image", panel).value = data.image || defaults.image;
  243. $(".ghd-tab", panel).value = data.tab || defaults.tab;
  244. $(".ghd-theme", panel).value = data.theme || defaults.theme;
  245. $(".ghd-themecm", panel).value = data.themeCm || defaults.themeCm;
  246. $(".ghd-themejp", panel).value = data.themeJp || defaults.themeJp;
  247. $(".ghd-type", panel).value = data.type || defaults.type;
  248.  
  249. $(".ghd-enable", panel).checked = isBool("enable");
  250. $(".ghd-wrap", panel).checked = isBool("wrap");
  251.  
  252. $(".ghd-codewrap-checkbox", panel).checked = isBool("enableCodeWrap");
  253. $(".ghd-monospace-checkbox", panel).checked = isBool("enableMonospace");
  254.  
  255. el = $(".ghd-diff-select", panel);
  256. temp = "" + (data.modeDiffToggle || defaults.modeDiffToggle);
  257. el.value = temp;
  258. toggleClass(el, "enabled", temp !== "0");
  259.  
  260. // update version tooltip
  261. $(".ghd-versions", panel).setAttribute("aria-label", getVersionTooltip());
  262.  
  263. temp = data.color || defaults.color;
  264. $(".ghd-color").value = temp;
  265. // update swatch color & color picker value
  266. $("#ghd-swatch").style.backgroundColor = temp;
  267.  
  268. if (picker) {
  269. picker.fromString(temp);
  270. }
  271. $style.disabled = !data.enable;
  272.  
  273. toggleClass(body, "ghd-disabled", !data.enable);
  274. toggleClass(body, "nowrap", !data.wrap);
  275.  
  276. if (data.enableCodeWrap !== data.lastCW ||
  277. data.enableMonospace !== data.lastMS ||
  278. data.modeDiffToggle !== data.lastDT) {
  279.  
  280. data.lastCW = data.enableCodeWrap;
  281. data.lastMS = data.enableMonospace;
  282. data.lastDT = data.modeDiffToggle;
  283. updateToggles();
  284. }
  285.  
  286. isUpdating = false;
  287. }
  288.  
  289. async function getStoredValues(init) {
  290. data = await GM.getValue("data", defaults);
  291. try {
  292. data = JSON.parse(data);
  293. if (!Object.keys(data).length || ({}).toString.call(data) !== "[object Object]") {
  294. throw new Error();
  295. }
  296. } catch(err) { // compat
  297. data = await GM.getValue("data", defaults);
  298. }
  299. if (debug) {
  300. if (init) {
  301. console.log("GitHub-Dark Script initializing!");
  302. }
  303. console.log("Retrieved stored values", data);
  304. }
  305. }
  306.  
  307. async function setStoredValues(reset) {
  308. data.processedCss = $style.textContent;
  309. await GM.setValue("data", JSON.stringify(reset ? defaults : data));
  310. updatePanel();
  311. if (debug) {
  312. console.log((reset ? "Resetting" : "Saving") + " current values", data);
  313. }
  314. }
  315.  
  316. // modified from http://stackoverflow.com/a/5624139/145346
  317. function hexToRgb(hex) {
  318. let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  319. return result ? [
  320. parseInt(result[1], 16),
  321. parseInt(result[2], 16),
  322. parseInt(result[3], 16)
  323. ].join(", ") : "";
  324. }
  325.  
  326. // convert version "1.2.3" into "001002003" for easier comparison
  327. function convertVersion(val) {
  328. let index,
  329. parts = val ? val.split(".") : "",
  330. str = "",
  331. len = parts.length;
  332. for (index = 0; index < len; index++) {
  333. str += ("000" + parts[index]).slice(-3);
  334. }
  335. if (debug) {
  336. console.log(`Converted version "${val}" to "${str}" for easy comparison`);
  337. }
  338. return val ? str : val;
  339. }
  340.  
  341. function checkVersion() {
  342. if (debug) {
  343. console.log("Fetching package.json");
  344. }
  345. GM.xmlHttpRequest({
  346. method: "GET",
  347. url: root + "package.json",
  348. onload: response => {
  349. let pkg = JSON.parse(response.responseText);
  350.  
  351. // save last loaded date, so package.json is only loaded once a day
  352. data.date = new Date().getTime();
  353.  
  354. let ver = convertVersion(pkg.version);
  355. // if new available, load it & parse
  356. if (ver > data.version) {
  357. if (data.version !== 0 && debug) {
  358. console.log(`Updating from ${data.version} to ${ver}`);
  359. }
  360. data.version = ver;
  361. fetchAndApplyStyle();
  362. } else {
  363. addSavedStyle();
  364. }
  365. // save new date/version
  366. GM.setValue("data", JSON.stringify(data));
  367. }
  368. });
  369. }
  370.  
  371. function fetchAndApplyStyle() {
  372. if (debug) {
  373. console.log(`Fetching ${root}github-dark.css`);
  374. }
  375. GM.xmlHttpRequest({
  376. method: "GET",
  377. url: root + "github-dark.css",
  378. onload: response => {
  379. data.rawCss = response.responseText;
  380. processStyle();
  381. }
  382. });
  383. }
  384.  
  385. // load syntax highlighting theme
  386. function fetchAndApplyTheme(name, group) {
  387. if (!data.enable) {
  388. if (debug) {
  389. console.log("Disabled: stop theme processing");
  390. }
  391. return;
  392. }
  393. if (data["last" + group] === name && data["css" + group] !== "") {
  394. return applyTheme(name, group);
  395. }
  396. let themeUrl = `${root}${themesXref[group].folder}${themes[group][name]}.min.css`;
  397. if (debug) {
  398. console.log(`Fetching ${group} ${name} theme`, themeUrl);
  399. }
  400. GM.xmlHttpRequest({
  401. method: "GET",
  402. url: themeUrl,
  403. onload: response => {
  404. let theme = response.responseText;
  405. if (response.status === 200 && theme) {
  406. data["css" + group] = theme;
  407. data["last" + group] = name;
  408. applyTheme(name, group);
  409. } else {
  410. theme = data["css" + group];
  411. console.error(`Failed to load ${group} theme file: "${name}"`);
  412. console.log(`Falling back to previous ${group} theme of ${theme.substring(0, theme.indexOf("*/") + 2)}`);
  413. }
  414. }
  415. });
  416. }
  417.  
  418. async function applyTheme(name, group) {
  419. let theme, css;
  420. if (debug) {
  421. theme = (data["css" + group] || "").match(regex);
  422. console.log(`Adding syntax ${group} theme "${theme}" to css`);
  423. }
  424. css = data.processedCss || "";
  425. css = css.replace(
  426. `/*[[${themesXref[group].placeholder}]]*/`,
  427. data["css" + group] || ""
  428. );
  429. applyStyle(css);
  430. await setStoredValues();
  431. isUpdating = false;
  432. }
  433.  
  434. function setTabSize() {
  435. return data.tab > 0
  436. ? `pre, .highlight, .diff-table, .tab-size {
  437. tab-size: ${data.tab} !important;
  438. -moz-tab-size: ${data.tab} !important;
  439. }`
  440. : "";
  441. }
  442.  
  443. function processStyle() {
  444. let url = /^url/.test(data.image || "") ? data.image :
  445. (data.image === "none" ? "none" : "url('" + data.image + "')");
  446. if (!data.enable) {
  447. if (debug) {
  448. console.log("Disabled: stop processing");
  449. }
  450. return;
  451. }
  452. if (debug) {
  453. console.log("Processing set styles");
  454. }
  455.  
  456. let processed = (data.rawCss || "")
  457. // remove moz-document wrapper
  458. .replace(/@-moz-document regexp\((.*)\) \{(\n|\r)+/, "")
  459. // replace background image; if no "url" at start, then use "none"
  460. .replace(/\/\*\[\[bg-choice\]\]\*\/ url\(.*\)/, url)
  461. // Add tiled or fit window size css
  462. .replace("/*[[bg-options]]*/", type[data.type || "tiled"])
  463. // set scroll or fixed background image
  464. .replace("/*[[bg-attachment]]*/ fixed", data.attach || "scroll")
  465. // replace base-color
  466. .replace(/\/\*\[\[base-color\]\]\*\/ #\w{3,6}/g, data.color || "#4183C4")
  467. // replace base-color-rgb
  468. .replace(/\/\*\[\[base-color-rgb\]\]\*\//g, hexToRgb(data.color || "#4183c4"))
  469. // add font choice
  470. .replace("/*[[font-choice]]*/", data.font || "Menlo")
  471. // add tab size
  472. .replace(/\/\*\[\[tab-size\]\]\*\//g, setTabSize())
  473. // code wrap css
  474. .replace("/*[[code-wrap]]*/", data.wrap ? wrapCodeCss : "")
  475. // remove default syntax
  476. .replace(/\s+\/\* grunt build - remove to end of file(.*(\n|\r))+\}$/m, "");
  477.  
  478. // see https://github.com/StylishThemes/GitHub-Dark/issues/275
  479. if (/firefox/i.test(navigator.userAgent)) {
  480. processed = processed
  481. // line in github-dark.css = "select, input:not(.btn-link), textarea"
  482. .replace("select, input:not(.btn-link)", "input { color:#eee !important; } select")
  483. .replace(/input\[type="checkbox"\][\s\S]+?}/gm, "");
  484. }
  485. data.processedCss = processed;
  486. fetchAndApplyTheme(data.theme, "github");
  487. fetchAndApplyTheme(data.themeCm, "codemirror");
  488. fetchAndApplyTheme(data.themeJp, "jupyter");
  489. }
  490.  
  491. function applyStyle(css) {
  492. if (debug) {
  493. console.log("Applying style", `"${(css || "").match(regex)}"`);
  494. }
  495. $style.textContent = css || "";
  496. }
  497.  
  498. function addSavedStyle() {
  499. if (debug) {
  500. console.log("Adding previously saved style");
  501. }
  502.  
  503. // apply already processed css to prevent FOUC
  504. $style.textContent = data.processedCss;
  505. }
  506.  
  507. function updateStyle() {
  508. isUpdating = true;
  509.  
  510. if (debug) {
  511. console.log("Updating user settings");
  512. }
  513.  
  514. let body = $("body"),
  515. panel = $("#ghd-settings-inner");
  516.  
  517. data.attach = $(".ghd-attach", panel).value;
  518. // get hex value directly
  519. data.color = picker.toHEXString();
  520. data.enable = $(".ghd-enable", panel).checked;
  521. data.font = $(".ghd-font", panel).value;
  522. data.image = $(".ghd-image", panel).value;
  523. data.tab = $(".ghd-tab", panel).value;
  524. data.theme = $(".ghd-theme", panel).value;
  525. data.themeCm = $(".ghd-themecm", panel).value;
  526. data.themeJp = $(".ghd-themejp", panel).value;
  527. data.type = $(".ghd-type", panel).value;
  528. data.wrap = $(".ghd-wrap", panel).checked;
  529.  
  530. data.enableCodeWrap = $(".ghd-codewrap-checkbox", panel).checked;
  531. data.enableMonospace = $(".ghd-monospace-checkbox", panel).checked;
  532.  
  533. data.modeDiffToggle = $(".ghd-diff-select", panel).value;
  534.  
  535. $style.disabled = !data.enable;
  536.  
  537. toggleClass(body, "ghd-disabled", !data.enable);
  538. toggleClass(body, "nowrap", !data.wrap);
  539.  
  540. if (testing) {
  541. processStyle();
  542. testing = false;
  543. } else {
  544. fetchAndApplyStyle();
  545. }
  546. isUpdating = false;
  547. }
  548.  
  549. // user can force GitHub-dark update
  550. async function forceUpdate(css) {
  551. if (css) {
  552. // add raw css directly for style testing
  553. data.rawCss = css;
  554. processStyle();
  555. } else {
  556. // clear saved date
  557. data.version = 0;
  558. data.cssgithub = "";
  559. data.csscodemirror = "";
  560. data.cssjupyter = "";
  561. await GM.setValue("data", JSON.stringify(data));
  562. closePanel("forced");
  563. }
  564. }
  565.  
  566. function getVersionTooltip() {
  567. let indx,
  568. ver = [],
  569. // convert stored css version from "001014049" into "1.14.49" for tooltip
  570. parts = String(data.version).match(/\d{3}/g),
  571. len = parts && parts.length || 0;
  572. for (indx = 0; indx < len; indx++) {
  573. ver.push(parseInt(parts[indx], 10));
  574. }
  575. return `Script v${version}\nCSS ${(ver.length ? "v" + ver.join(".") : "unknown")}`;
  576. }
  577.  
  578. function buildOptions(group) {
  579. let options = "";
  580. Object.keys(themes[group]).forEach(theme => {
  581. options += `<option value="${theme}">${theme}</option>`;
  582. });
  583. return options;
  584. }
  585.  
  586. async function buildSettings() {
  587. if (debug) {
  588. console.log("Adding settings panel & GitHub Dark link to profile dropdown");
  589. }
  590. // Script-specific CSS
  591. GM.addStyle(`
  592. #ghd-menu:hover { cursor:pointer }
  593. #ghd-settings { position:fixed; z-index:65535; top:0; bottom:0; left:0; right:0; opacity:0; visibility:hidden; }
  594. #ghd-settings.in { opacity:1; visibility:visible; background:rgba(0,0,0,.5); }
  595. #ghd-settings-inner { position:fixed; left:50%; top:50%; transform:translate(-50%,-50%); width:25rem; box-shadow:0 .5rem 1rem #111; color:#c0c0c0 }
  596. #ghd-settings label { margin-left:.5rem; position:relative; top:-1px }
  597. #ghd-settings-close { height:1rem; width:1rem; fill:#666; float:right; cursor:pointer }
  598. #ghd-settings-close:hover { fill:#ccc }
  599. #ghd-settings .ghd-right { float:right; padding:5px; }
  600. #ghd-settings p { line-height:22px; }
  601. #ghd-settings .form-select, #ghd-settings input[type="text"] { height:30px; min-height:30px; }
  602. #ghd-swatch { width:25px; height:22px; display:inline-block; margin:3px 10px; border-radius:4px; }
  603. #ghd-settings input, #ghd-settings select { border:#555 1px solid; }
  604. #ghd-settings .ghd-attach, #ghd-settings .ghd-diff-select { padding-right:25px; }
  605. #ghd-settings input[type="checkbox"] { margin-top:3px; width: 16px !important; height: 16px !important; border-radius: 3px !important; }
  606. #ghd-settings .boxed-group-inner { padding:0; }
  607. #ghd-settings .ghd-footer { padding:10px; border-top:#555 solid 1px; }
  608. #ghd-settings .ghd-settings-wrapper { max-height:60vh; overflow-y:auto; padding:4px 10px; }
  609. #ghd-settings .ghd-tab { width:6em; }
  610. #ghd-settings .octicon { vertical-align:text-bottom !important; }
  611. #ghd-settings .ghd-paste-area { position:absolute; bottom:50px; top:37px; left:2px; right:2px; width:396px !important; height:-moz-calc(100% - 85px);
  612. resize:none !important; border-style:solid; z-index:0; }
  613.  
  614. /* code wrap toggle: https://gist.github.com/silverwind/6c1701f56e62204cc42b
  615. icons next to a pre */
  616. .ghd-wrap-toggle { padding: 3px 5px; position:absolute; right:3px; top:3px; -moz-user-select:none; -webkit-user-select:none; cursor:pointer; z-index:20; }
  617. .ghd-code-wrapper:not(:hover) .ghd-wrap-toggle { border-color:transparent !important; background:transparent !important; }
  618. /* file & diff code tables */
  619. .ghd-wrap-table .blob-code-inner { white-space:pre-wrap !important; word-break:break-all !important; }
  620. .ghd-unwrap-table .blob-code-inner { white-space:pre !important; word-break:normal !important; }
  621. .ghd-wrap-toggle > *, .ghd-monospace > *, .ghd-file-toggle > * { pointer-events:none; vertical-align:middle !important; }
  622. /* icons for non-syntax highlighted code blocks; see https://github.com/gjtorikian/html-proofer/blob/master/README.md */
  623. .markdown-body:not(.comment-body) .ghd-wrap-toggle:not(:first-child) { right:3.4em; }
  624. .ghd-wrap-toggle svg { height:14px; width:14px; fill:rgba(110,110,110,.4); vertical-align:text-bottom; }
  625. /* wrap disabled (red) */
  626. .ghd-code-wrapper:hover .ghd-wrap-toggle.unwrap svg, .ghd-code-wrapper:hover .ghd-wrap-toggle svg { fill:#8b0000; }
  627. /* wrap enabled (green) */
  628. body:not(.nowrap) .ghd-code-wrapper:hover .ghd-wrap-toggle:not(.unwrap) svg, .ghd-code-wrapper:hover .ghd-wrap-toggle.wrapped svg { fill:#006400; }
  629. .markdown-body pre, .markdown-body .highlight, .ghd-code-wrapper { position:relative; }
  630. /* monospace font toggle */
  631. .ghd-monospace-font { font-family:"${data.font}", Menlo, Inconsolata, "Droid Mono", monospace !important; font-size:1em !important; }
  632. /* file collapsed icon */
  633. .Details--on .ghd-file-toggle svg { -webkit-transform:rotate(90deg); transform:rotate(90deg); }
  634. `);
  635.  
  636. let icon,
  637. opts = buildOptions("github"),
  638. optscm = buildOptions("codemirror"),
  639. optsjp = buildOptions("jupyter"),
  640. ver = getVersionTooltip();
  641.  
  642. // circle-question-mark icon
  643. icon = `
  644. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" height="16" width="14" viewBox="0 0 16 14">
  645. <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" />
  646. </svg>
  647. `;
  648.  
  649. // Settings panel markup
  650. make({
  651. el: "div",
  652. appendTo: "body",
  653. attr: { id: "ghd-settings" },
  654. html: `
  655. <div id="ghd-settings-inner" class="boxed-group">
  656. <h3>GitHub-Dark Settings
  657. <a href="https://github.com/StylishThemes/GitHub-Dark-Script/wiki" class="tooltipped tooltipped-e" aria-label="See documentation">${icon}</a>
  658. <svg id="ghd-settings-close" xmlns="http://www.w3.org/2000/svg" width="768" height="768" viewBox="160 160 608 608"><path d="M686.2 286.8L507.7 465.3l178.5 178.5-45 45-178.5-178.5-178.5 178.5-45-45 178.5-178.5-178.5-178.5 45-45 178.5 178.5 178.5-178.5z"/></svg>
  659. </h3>
  660. <div class="boxed-group-inner">
  661. <form>
  662. <div class="ghd-settings-wrapper">
  663. <p class="ghd-checkbox">
  664. <label>Enable GitHub-Dark<input class="ghd-enable ghd-right" type="checkbox"></label>
  665. </p>
  666. <p>
  667. <label>Color:</label>
  668. <input class="ghd-color ghd-right" type="text" value="#4183C4">
  669. <span id="ghd-swatch" class="ghd-right"></span>
  670. </p>
  671. <h4>Background</h4>
  672. <p>
  673. <label>Image:</label>
  674. <input class="ghd-image ghd-right" type="text">
  675. <a href="https://github.com/StylishThemes/GitHub-Dark/wiki/Image" class="tooltipped tooltipped-e" aria-label="Click to learn about GitHub's Content Security&#10;Policy and how to add a custom image">${icon}</a>
  676. </p>
  677. <p>
  678. <label>Image type:</label>
  679. <select class="ghd-type ghd-right form-select">
  680. <option value="tiled">Tiled</option>
  681. <option value="fit">Fit window</option>
  682. </select>
  683. </p>
  684. <p>
  685. <label>Image attachment:</label>
  686. <select class="ghd-attach ghd-right form-select">
  687. <option value="scroll">Scroll</option>
  688. <option value="fixed">Fixed</option>
  689. </select>
  690. </p>
  691. <h4>Code</h4>
  692. <p><label>GitHub Theme:</label> <select class="ghd-theme ghd-right form-select">${opts}</select></p>
  693. <p><label>CodeMirror Theme:</label> <select class="ghd-themecm ghd-right form-select">${optscm}</select></p>
  694. <p><label>Jupyter Theme:</label> <select class="ghd-themejp ghd-right form-select">${optsjp}</select></p>
  695. <p>
  696. <label>Font Name:</label> <input class="ghd-font ghd-right" type="text">
  697. <a href="http://www.cssfontstack.com/" class="tooltipped tooltipped-e" aria-label="Add a system installed (monospaced) font name;&#10;this script will not load external fonts!">${icon}</a>
  698. </p>
  699. <p>
  700. <label>Tab Size:</label>
  701. <select class="ghd-tab ghd-right form-select">
  702. <option value="0">disable</option>
  703. <option value="1">1</option>
  704. <option value="2">2</option>
  705. <option value="3">3</option>
  706. <option value="4">4</option>
  707. <option value="5">5</option>
  708. <option value="6">6</option>
  709. <option value="7">7</option>
  710. <option value="8">8</option>
  711. </select>
  712. </p>
  713. <p class="ghd-checkbox">
  714. <label>Wrap<input class="ghd-wrap ghd-right" type="checkbox"></label>
  715. </p>
  716. <h4>Toggles</h4>
  717. <p class="ghd-checkbox">
  718. <label>Code Wrap<input class="ghd-codewrap-checkbox ghd-right" type="checkbox"></label>
  719. </p>
  720. <p class="ghd-checkbox">
  721. <label>Comment Monospace Font<input class="ghd-monospace-checkbox ghd-right" type="checkbox"></label>
  722. </p>
  723. <p class="ghd-range">
  724. <label>Diff File Collapse</label>
  725. <select class="ghd-diff-select ghd-right form-select">
  726. <option value="0">Disabled</option>
  727. <option value="1">Enabled</option>
  728. <option value="2">Accordion</option>
  729. </select>
  730. </p>
  731. </div>
  732. <div class="ghd-footer">
  733. <div class="BtnGroup">
  734. <a href="#" class="ghd-update btn btn-sm tooltipped tooltipped-n tooltipped-multiline" aria-label="Update style if the newest release is not loading; the page will reload!">Force Update Style</a>
  735. <a href="#" class="ghd-textarea-toggle btn btn-sm tooltipped tooltipped-n" aria-label="Paste CSS update">
  736. <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 16 16" fill="#eee">
  737. <path d="M15 11 1 11 8 3z"/>
  738. </svg>
  739. </a>
  740. <div class="ghd-paste-area-content" aria-hidden="true" style="display:none">
  741. <textarea class="ghd-paste-area" placeholder="Paste GitHub-Dark Style here!"></textarea>
  742. </div>
  743. </div>&nbsp;
  744. <a href="#" class="ghd-reset btn btn-sm btn-danger tooltipped tooltipped-n" aria-label="Reset to defaults;&#10;there is no undo!">Reset All Settings</a>
  745. <span class="ghd-versions ghd-right tooltipped tooltipped-n" aria-label="${ver}">
  746. <svg class="ghd-info" xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 24 24">
  747. <path fill="#444" d="M12,9c0.82,0,1.5-0.68,1.5-1.5S12.82,6,12,6s-1.5,0.68-1.5,1.5S11.18,9,12,9z M12,1.5 C6.211,1.5,1.5,6.211,1.5,12S6.211,22.5,12,22.5S22.5,17.789,22.5,12S17.789,1.5,12,1.5z M12,19.5c-4.148,0-7.5-3.352-7.5-7.5 S7.852,4.5,12,4.5s7.5,3.352,7.5,7.5S16.148,19.5,12,19.5z M13.5,12c0-0.75-0.75-1.5-1.5-1.5s-0.75,0-1.5,0S9,11.25,9,12h1.5 c0,0,0,3.75,0,4.5S11.25,18,12,18s0.75,0,1.5,0s1.5-0.75,1.5-1.5h-1.5C13.5,16.5,13.5,12.75,13.5,12z"/>
  748. </svg>
  749. </span>
  750. </div>
  751. </form>
  752. </div>
  753. </div>
  754. `
  755. });
  756. updateToggles();
  757. }
  758.  
  759. function addCodeWrapButton(button, target) {
  760. target.insertBefore(button.cloneNode(true), target.childNodes[0]);
  761. target.classList.add("ghd-code-wrapper");
  762. }
  763.  
  764. // Add code wrap toggle
  765. function buildCodeWrap() {
  766. // mutation events happen quick, so we still add an update flag
  767. isUpdating = true;
  768. let icon = make({
  769. el: "button",
  770. cl4ss: "ghd-wrap-toggle tooltipped tooltipped-sw btn btn-sm" +
  771. (data.wrap ? "" : " unwrap"),
  772. attr: { "aria-label": "Toggle code wrap" },
  773. html: wrapIcon
  774. });
  775. $$(".blob-wrapper").forEach(el => {
  776. if (el && !$(".ghd-wrap-toggle", el)) {
  777. addCodeWrapButton(icon, el);
  778. }
  779. });
  780. $$(`
  781. .markdown-body pre:not(.ghd-code-wrapper),
  782. .markdown-format pre:not(.ghd-code-wrapper)`
  783. ).forEach(pre => {
  784. const code = $("code", pre);
  785. const wrap = pre.parentNode;
  786. if (code) {
  787. addCodeWrapButton(icon, pre);
  788. } else if (wrap.classList.contains("highlight")) {
  789. addCodeWrapButton(icon, wrap);
  790. }
  791. });
  792. isUpdating = false;
  793. }
  794.  
  795. // Add monospace font toggle
  796. function addMonospaceToggle() {
  797. isUpdating = true;
  798. let button = make({
  799. el: "button",
  800. cl4ss: "ghd-monospace toolbar-item tooltipped tooltipped-n",
  801. attr: {
  802. "type": "button",
  803. "aria-label": "Toggle monospaced font",
  804. "tabindex": "-1"
  805. },
  806. html: monospaceIcon
  807. });
  808. $$(".toolbar-commenting").forEach(el => {
  809. if (el && !$(".ghd-monospace", el)) {
  810. // prepend
  811. el.insertBefore(button.cloneNode(true), el.childNodes[0]);
  812. }
  813. });
  814. isUpdating = false;
  815. }
  816.  
  817. // Add file diffs toggle
  818. function addFileToggle() {
  819. isUpdating = true;
  820. let firstButton,
  821. button = make({
  822. el: "button",
  823. cl4ss: "ghd-file-toggle btn btn-sm tooltipped tooltipped-n",
  824. attr: {
  825. "type": "button",
  826. "aria-label": "Click to Expand or Collapse file",
  827. "tabindex": "-1"
  828. },
  829. html: fileIcon
  830. });
  831. $$("#files .file-actions").forEach(el => {
  832. if (el && !$(".ghd-file-toggle", el)) {
  833. // hide GitHub toggle view button
  834. el.querySelector(".js-details-target").style.display = "none";
  835. el.appendChild(button.cloneNode(true));
  836. }
  837. });
  838. firstButton = $(".ghd-file-toggle");
  839. // accordion mode = start with all but first entry collapsed
  840. if (firstButton && data.modeDiffToggle === "2") {
  841. toggleFile({
  842. target: firstButton
  843. }, true);
  844. }
  845. isUpdating = false;
  846. }
  847.  
  848. // Add toggle buttons after page updates
  849. function updateToggles() {
  850. if (isUpdating) {
  851. return;
  852. }
  853. clearTimeout(timer);
  854. timer = setTimeout(() => {
  855. if (data.enableCodeWrap) {
  856. buildCodeWrap();
  857. } else {
  858. removeAll(".ghd-wrap-toggle");
  859. toggleClass($$(".Details--on"), "Details--on", false);
  860. }
  861. if (data.enableMonospace) {
  862. addMonospaceToggle();
  863. } else {
  864. removeAll(".ghd-monospace");
  865. toggleClass($$(".ghd-monospace-font"), "ghd-monospace-font", false);
  866. }
  867. if (data.modeDiffToggle !== "0") {
  868. addFileToggle();
  869. } else {
  870. removeAll(".ghd-file-toggle");
  871. toggleClass($$(".Details--on"), "Details--on", false);
  872. }
  873. }, 200);
  874. }
  875.  
  876. function makeRow(vals, str) {
  877. return make({
  878. el: "tr",
  879. cl4ss: "ghd-shortcut",
  880. html: `<td class="keys"><kbd>${vals[0]}</kbd> <kbd>${vals[1]}</kbd></td><td>${str}</td>`
  881. });
  882. }
  883.  
  884. // add keyboard shortcut to help menu (press "?")
  885. function buildShortcut() {
  886. let row,
  887. el = $(".keyboard-mappings tbody");
  888. if (el && !$(".ghd-shortcut")) {
  889. row = makeRow(keyboardOpen.split("+"), "GitHub-Dark: open settings");
  890. el.appendChild(row);
  891. row = makeRow(keyboardToggle.split("+"), "GitHub-Dark: toggle style");
  892. el.appendChild(row);
  893. }
  894. }
  895.  
  896. function findSibling(node, selector) {
  897. node = node.parentNode.firstElementChild;
  898. while ((node = node.nextElementSibling)) {
  899. if (node.matches(selector)) {
  900. return node;
  901. }
  902. }
  903. return null;
  904. }
  905.  
  906. function toggleCodeWrap(el) {
  907. let css,
  908. overallWrap = data.wrap,
  909. target = findSibling(el, ".highlight, .diff-table, code, pre");
  910. if (!target) {
  911. if (debug) {
  912. console.log("Code wrap icon associated code not found", el);
  913. }
  914. return;
  915. }
  916. // code with line numbers
  917. if (target.nodeName === "TABLE") {
  918. if (target.className.indexOf("wrap-table") < 0) {
  919. css = !overallWrap;
  920. } else {
  921. css = target.classList.contains("ghd-unwrap-table");
  922. }
  923. toggleClass(target, "ghd-wrap-table", css);
  924. toggleClass(target, "ghd-unwrap-table", !css);
  925. toggleClass(el, "wrapped", css);
  926. toggleClass(el, "unwrap", !css);
  927. } else {
  928. css = target.getAttribute("style") || "";
  929. if (css === "") {
  930. css = wrapCss[overallWrap ? "unwrap" : "wrapped"];
  931. } else {
  932. css = wrapCss[css === wrapCss.wrapped ? "unwrap" : "wrapped"];
  933. }
  934. target.setAttribute("style", css);
  935. toggleClass(el, "wrapped", css === wrapCss.wrapped);
  936. toggleClass(el, "unwrap", css === wrapCss.unwrap);
  937. }
  938. }
  939.  
  940. function toggleMonospace(el) {
  941. let tmp = el.closest(".previewable-comment-form"),
  942. // single comment
  943. textarea = $(".comment-form-textarea", tmp);
  944. if (textarea) {
  945. toggleClass(textarea, "ghd-monospace-font");
  946. textarea.focus();
  947. tmp = textarea.classList.contains("ghd-monospace-font");
  948. toggleClass(el, "ghd-icon-active", tmp);
  949. }
  950. }
  951.  
  952. function toggleSibs(target, state) {
  953. // oddly, when a "Details--on" class is applied, the content is hidden
  954. const isCollapsed = state || target.classList.contains("Details--on"),
  955. toggles = $$(".file");
  956. let el,
  957. indx = toggles.length;
  958. while (indx--) {
  959. el = toggles[indx];
  960. if (el !== target) {
  961. el.classList.toggle("Details--on", isCollapsed);
  962. }
  963. }
  964. }
  965.  
  966. function toggleFile(event, init) {
  967. isUpdating = true;
  968. let el = event.target.closest(".file");
  969. if (el && data.modeDiffToggle === "2") {
  970. if (!init) {
  971. el.classList.toggle("Details--on");
  972. }
  973. toggleSibs(el, true);
  974. } else if (el) {
  975. el.classList.toggle("Details--on");
  976. // shift+click toggle all files!
  977. if (event.shiftKey) {
  978. toggleSibs(el);
  979. }
  980. }
  981. isUpdating = false;
  982. document.activeElement.blur();
  983. // move current open panel to the top
  984. if (el && !el.classList.contains("Details--on")) {
  985. location.hash = el.id;
  986. }
  987. }
  988.  
  989. function bindEvents() {
  990. let el, menu, lastKey,
  991. panel = $("#ghd-settings-inner"),
  992. swatch = $("#ghd-swatch", panel);
  993.  
  994. // finish initialization
  995. $("#ghd-settings-inner .ghd-enable").checked = data.enable;
  996. toggleClass($("body"), "ghd-disabled", !data.enable);
  997.  
  998. // Create our menu entry
  999. menu = make({
  1000. el: "a",
  1001. cl4ss: "dropdown-item",
  1002. html: "GitHub Dark Settings",
  1003. attr: { id: "ghd-menu" }
  1004. });
  1005.  
  1006. // .header changed to .Header 22 Aug 2017
  1007. el = $$(`
  1008. .header .dropdown-item[href="/settings/profile"],
  1009. .header .dropdown-item[data-ga-click*="go to profile"],
  1010. .Header .dropdown-item[href="/settings/profile"],
  1011. .Header .dropdown-item[data-ga-click*="go to profile"]`
  1012. );
  1013. // get last found item - gists only have the "go to profile" item;
  1014. // GitHub has both
  1015. el = el[el.length - 1];
  1016. if (el) {
  1017. // insert after
  1018. el.parentNode.insertBefore(menu, el.nextSibling);
  1019. on($("#ghd-menu"), "click", () => {
  1020. openPanel();
  1021. });
  1022. }
  1023.  
  1024. on(document, "keypress keydown", event => {
  1025. clearTimeout(timer);
  1026. // use "g+o" to open up ghd options panel
  1027. let openKeys = keyboardOpen.split("+"),
  1028. toggleKeys = keyboardToggle.split("+"),
  1029. key = event.key.toLowerCase(),
  1030. panelVisible = $("#ghd-settings").classList.contains("in");
  1031.  
  1032. // press escape to close the panel
  1033. if (key === "escape" && panelVisible) {
  1034. closePanel();
  1035. return;
  1036. }
  1037. // use event.which from keypress for shortcuts
  1038. // prevent opening panel while typing "go" in comments
  1039. if (event.type === "keydown" || /(input|textarea)/i.test(document.activeElement.nodeName)) {
  1040. return;
  1041. }
  1042. if (lastKey === openKeys[0] && key === openKeys[1]) {
  1043. if (panelVisible) {
  1044. closePanel();
  1045. } else {
  1046. openPanel();
  1047. }
  1048. }
  1049. if (lastKey === toggleKeys[0] && key === toggleKeys[1]) {
  1050. toggleStyle();
  1051. }
  1052. lastKey = key;
  1053. timer = setTimeout(() => {
  1054. lastKey = null;
  1055. }, keyboardDelay);
  1056.  
  1057. // add shortcut to help menu
  1058. if (key === "?") {
  1059. // table doesn't exist until user presses "?"
  1060. setTimeout(() => {
  1061. buildShortcut();
  1062. }, 300);
  1063. }
  1064. });
  1065.  
  1066. // add ghd-settings panel bindings
  1067. on($$("#ghd-settings, #ghd-settings-close"), "click keyup", event => {
  1068. // press escape to close settings
  1069. if (event.type === "keyup" && event.which !== 27) {
  1070. return;
  1071. }
  1072. closePanel();
  1073. });
  1074.  
  1075. on(panel, "click", event => {
  1076. event.stopPropagation();
  1077. });
  1078.  
  1079. on($(".ghd-reset", panel), "click", async event => {
  1080. event.preventDefault();
  1081. isUpdating = true;
  1082. // pass true to reset values
  1083. await setStoredValues(true);
  1084. // add reset values back to data
  1085. await getStoredValues();
  1086. // add reset values to panel
  1087. updatePanel();
  1088. // update style
  1089. updateStyle();
  1090. });
  1091.  
  1092. on($$("input[type='text']", panel), "focus", function() {
  1093. // select all text when focused
  1094. this.select();
  1095. });
  1096.  
  1097. on($$("select, input", panel), "change", () => {
  1098. if (!isUpdating) {
  1099. updateStyle();
  1100. }
  1101. });
  1102.  
  1103. on($(".ghd-update", panel), "click", async event => {
  1104. event.preventDefault();
  1105. await forceUpdate();
  1106. });
  1107.  
  1108. on($(".ghd-textarea-toggle", panel), "click", function(event) {
  1109. event.preventDefault();
  1110. let hidden, el;
  1111. this.classList.remove("selected");
  1112. el = next(this, ".ghd-paste-area-content");
  1113. if (el) {
  1114. hidden = el.style.display === "none";
  1115. el.style.display = hidden ? "" : "none";
  1116. if (el.style.display !== "none") {
  1117. el.classList.add("selected");
  1118. el = $("textarea", el);
  1119. el.focus();
  1120. el.select();
  1121. }
  1122. }
  1123. return false;
  1124. });
  1125.  
  1126. on($(".ghd-paste-area-content", panel), "paste", async event => {
  1127. let toggle = $(".ghd-textarea-toggle", panel),
  1128. textarea = event.target;
  1129. setTimeout(async () => {
  1130. textarea.parentNode.style.display = "none";
  1131. toggle.classList.remove("selected");
  1132. testing = true;
  1133. await forceUpdate(textarea.value);
  1134. }, 200);
  1135. });
  1136.  
  1137. // Toggles
  1138. on($("body"), "click", event => {
  1139. let target = event.target;
  1140. if (data.enableCodeWrap && target.classList.contains("ghd-wrap-toggle")) {
  1141. // **** CODE WRAP TOGGLE ****
  1142. event.stopPropagation();
  1143. toggleCodeWrap(target);
  1144. } else if (data.enableMonospace && target.classList.contains("ghd-monospace")) {
  1145. // **** MONOSPACE FONT TOGGLE ****
  1146. event.stopPropagation();
  1147. toggleMonospace(target);
  1148. return false;
  1149. } else if (data.modeDiffToggle !== "0" && target.classList.contains("ghd-file-toggle")) {
  1150. // **** CODE DIFF COLLAPSE TOGGLE ****
  1151. event.stopPropagation();
  1152. toggleFile(event);
  1153. }
  1154. });
  1155.  
  1156. // style color picker
  1157. picker = new jscolor($(".ghd-color", panel));
  1158. picker.zIndex = 65536;
  1159. picker.hash = true;
  1160. picker.backgroundColor = "#333";
  1161. picker.padding = 0;
  1162. picker.borderWidth = 0;
  1163. picker.borderColor = "#444";
  1164. picker.onFineChange = () => {
  1165. swatch.style.backgroundColor = "#" + picker;
  1166. };
  1167. }
  1168.  
  1169. function openPanel() {
  1170. // Don't show options panel on page that's missing main styles (e.g. help)
  1171. if ($(".modal-backdrop")) {
  1172. $(".modal-backdrop").click();
  1173. }
  1174. updatePanel();
  1175. $("#ghd-settings").classList.add("in");
  1176. }
  1177.  
  1178. function closePanel(flag) {
  1179. $("#ghd-settings").classList.remove("in");
  1180. picker.hide();
  1181.  
  1182. if (flag === "forced") {
  1183. // forced update; partial re-initialization
  1184. init();
  1185. } else {
  1186. // apply changes when the panel is closed
  1187. updateStyle();
  1188. }
  1189. }
  1190.  
  1191. function toggleStyle() {
  1192. let isEnabled = !data.enable;
  1193. data.enable = isEnabled;
  1194. $("#ghd-settings-inner .ghd-enable").checked = isEnabled;
  1195. // add processedCss back into style (emptied when disabled)
  1196. if (isEnabled) {
  1197. // data.processedCss is empty when ghd is disabled on init
  1198. if (!data.processedCss) {
  1199. processStyle();
  1200. } else {
  1201. addSavedStyle();
  1202. }
  1203. }
  1204. $style.disabled = !isEnabled;
  1205. }
  1206.  
  1207. async function init() {
  1208. if (!document.head) {
  1209. return;
  1210. }
  1211.  
  1212. document.head.parentNode.insertBefore($style, document.head.nextSibling);
  1213. await getStoredValues(true);
  1214.  
  1215. $style.disabled = !data.enable;
  1216. data.lastgithub = data.themeGH;
  1217. data.lastcodemirror = data.themeCM;
  1218. data.lastjupyter = data.themeJP;
  1219. data.lastCW = data.enableCodeWrap;
  1220. data.lastMS = data.enableMonospace;
  1221. data.lastDT = data.modeDiffToggle;
  1222.  
  1223. if (!data.processedCss) {
  1224. fetchAndApplyStyle();
  1225. } else {
  1226. // only load package.json once a day, or after a forced update
  1227. if ((new Date().getTime() > data.date + delay) || data.version === 0) {
  1228. // get package.json from GitHub-Dark & compare versions
  1229. // load new script if a newer one is available
  1230. checkVersion();
  1231. } else {
  1232. addSavedStyle();
  1233. }
  1234. }
  1235. isInitialized = false;
  1236. }
  1237.  
  1238. // add style at document-start
  1239. await init();
  1240.  
  1241. async function buildOnLoad() {
  1242. if (isInitialized === "pending") {
  1243. // init after DOM loaded on .atom pages
  1244. await init();
  1245. }
  1246. // add panel even if you're not logged in - open panel using keyboard
  1247. // shortcut just not on githubusercontent pages (no settings panel needed)
  1248. if (window.location.host.indexOf("githubusercontent.com") < 0) {
  1249. buildSettings();
  1250. // add event binding on document ready
  1251. bindEvents();
  1252.  
  1253. on(document, "ghmo:container", updateToggles);
  1254. on(document, "ghmo:comments", updateToggles);
  1255. on(document, "ghmo:diff", updateToggles);
  1256. on(document, "ghmo:preview", updateToggles);
  1257. }
  1258.  
  1259. isInitialized = true;
  1260. }
  1261.  
  1262. if (document.readyState === "loading") {
  1263. on(document, "DOMContentLoaded", buildOnLoad);
  1264. } else {
  1265. buildOnLoad();
  1266. }
  1267.  
  1268. /* utility functions */
  1269. function isBool(name) {
  1270. let val = data[name];
  1271. return typeof val === "boolean" ? val : defaults[name];
  1272. }
  1273.  
  1274. function $(str, el) {
  1275. return (el || document).querySelector(str);
  1276. }
  1277.  
  1278. function $$(str, el) {
  1279. return [...(el || document).querySelectorAll(str)];
  1280. }
  1281.  
  1282. function next(el, selector) {
  1283. while ((el = el.nextElementSibling)) {
  1284. if (el && el.matches(selector)) {
  1285. return el;
  1286. }
  1287. }
  1288. return null;
  1289. }
  1290.  
  1291. function make(obj) {
  1292. let key,
  1293. el = document.createElement(obj.el);
  1294. if (obj.cl4ss) { el.className = obj.cl4ss; }
  1295. if (obj.html) { el.innerHTML = obj.html; }
  1296. if (obj.attr) {
  1297. for (key in obj.attr) {
  1298. if (obj.attr.hasOwnProperty(key)) {
  1299. el.setAttribute(key, obj.attr[key]);
  1300. }
  1301. }
  1302. }
  1303. if (obj.appendTo) {
  1304. $(obj.appendTo).appendChild(el);
  1305. }
  1306. return el;
  1307. }
  1308.  
  1309. function removeAll(selector) {
  1310. isUpdating = true;
  1311. $$(selector).forEach(el => {
  1312. el.parentNode.removeChild(el);
  1313. });
  1314. isUpdating = false;
  1315. }
  1316.  
  1317. function on(els, name, callback) {
  1318. els = Array.isArray(els) ? els : [els];
  1319. let events = name.split(/\s+/);
  1320. els.forEach(el => {
  1321. events.forEach(ev => {
  1322. el.addEventListener(ev, callback);
  1323. });
  1324. });
  1325. }
  1326.  
  1327. function toggleClass(els, cl4ss, flag) {
  1328. els = Array.isArray(els) ? els : [els];
  1329. els.forEach(el => {
  1330. if (el) {
  1331. if (typeof flag === "undefined") {
  1332. flag = !el.classList.contains(cl4ss);
  1333. }
  1334. el.classList.toggle(cl4ss, flag);
  1335. }
  1336. });
  1337. }
  1338.  
  1339. // Add GM options
  1340. // await GM.registerMenuCommand("GitHub Dark Script debug logging", async () => {
  1341. // let val = prompt(
  1342. // "Toggle GitHub Dark Script debug log (true/false):",
  1343. // "" + debug
  1344. // );
  1345. // if (val) {
  1346. // debug = /^t/.test(val);
  1347. // await GM.setValue("debug", debug);
  1348. // }
  1349. // });
  1350.  
  1351. })();