GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

As of 2017-08-22. See the latest version.

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