GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

Pada tanggal 21 April 2017. Lihat %(latest_version_link).

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