GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

Version au 01/10/2017. Voir la dernière version.

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