GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

As of 2017-12-31. See the latest version.

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