GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

Versione datata 13/03/2017. Vedi la nuova versione l'ultima versione.

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