Greasy Fork 支持简体中文。

GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

目前為 2017-11-19 提交的版本,檢視 最新版本

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