GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

As of 2016-01-02. See the latest version.

  1. // ==UserScript==
  2. // @name GitHub Dark Script
  3. // @version 0.8.5
  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 /render\.githubusercontent\.com/
  8. // @include /raw\.githubusercontent\.com/
  9. // @grant GM_addStyle
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @grant GM_xmlhttpRequest
  13. // @run-at document-start
  14. // @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js
  15. // @require https://greatest.deepsurf.us/scripts/15563-jscolor/code/jscolor.js?version=97027
  16. // ==/UserScript==
  17. /* global jQuery, GM_addStyle, GM_getValue, GM_setValue, GM_xmlhttpRequest, jscolor, unsafeWindow */
  18. /* eslint-disable indent, quotes */
  19. (function(unsafeWindow, $) {
  20. 'use strict';
  21.  
  22. var ghd = {
  23.  
  24. // delay until package.json allowed to load
  25. delay : 8.64e7, // 24 hours in milliseconds
  26.  
  27. // Keyboard shortcut to open ghd panel (only a two key combo coded)
  28. keyboardShortcut : 'g+0',
  29. // keyboard shortcut delay from first to second letter
  30. keyboardDelay : 1000,
  31.  
  32. // base urls to fetch style and package.json
  33. root : 'https://raw.githubusercontent.com/StylishThemes/GitHub-Dark/master/',
  34.  
  35. defaults : {
  36. attach : 'scroll',
  37. color : '#4183C4',
  38. enable : true,
  39. font : 'Menlo',
  40. image : 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkAgMAAAANjH3HAAAACVBMVEUaGhohISElJSUh9lebAAAB20lEQVRIx4XWuZXDMAwE0C0SAQtggIIYoAAEU+aKOHhYojTrYP2+QfOW/5QIJOih/q8HwF/pb3EX+UPIveYcQGgEHiu9hI+ihEc5Jz5KBIlRRRaJ1JtoSAl5Hw96hLB1/up1tnIXOck5jZQy+3iU2hAOKSH1JvwxHsp+5TLF5MOl1/MQXsVs1miXc+KDbYydyMeUgpPQreZ7fWidbNhkXNJSeAhc6qHmHD8AYovunYyEACWEbyIhNeB9fRrH3hFi0bGPLuEW7xCNaohw1vAlS805nfsrTspclB/hVdoqusg53eH7FWot+wjYpOViX8KbFFKTwlnzvj65P9H/vD0/hibYBGhPwlPO8TmxRsaxsNnrUmUXpNhirlJMPr6Hqq9k5Xn/8iYQHYIuQsWFC6Z87IOxLxHphSY4SpuiU87xJnJr5axfeRd+lnMExXpEWPpuZ1v7qZdNBOjiHzDREHX5fs5Zz9p6X0vVKbKKchlSl5rv+3p//FJ/PYvoKryI8vs+2G9lzRmnEKkh+BU8yDk515jDj/HAswu7CCz6U/Mxb/PnC9N41ndpU4hUU7JGk/C9PmP/M2xZYdvBW2PObyf1IUiIzoHmHW9yTncliYs9A9tVNppdShfgQaTLMf+j3X723tLeHgAAAABJRU5ErkJggg==")',
  41. tab : 4,
  42. theme : 'Twilight',
  43. type : 'tiled',
  44. wrap : true
  45. },
  46.  
  47. // url gets replaced by css when loaded
  48. themes : {
  49. 'Ambiance' : 'themes/ambiance.min.css',
  50. 'Chaos' : 'themes/chaos.min.css',
  51. 'Clouds Midnight' : 'themes/clouds-midnight.min.css',
  52. 'Cobalt' : 'themes/cobalt.min.css',
  53. 'Idle Fingers' : 'themes/idle-fingers.min.css',
  54. 'Kr Theme' : 'themes/kr-theme.min.css',
  55. 'Merbivore' : 'themes/merbivore.min.css',
  56. 'Merbivore Soft' : 'themes/merbivore-soft.min.css',
  57. 'Mono Industrial' : 'themes/mono-industrial.min.css',
  58. 'Mono Industrial Clear' : 'themes/mono-industrial-clear.min.css',
  59. 'Monokai' : 'themes/monokai.min.css',
  60. 'Pastel on Dark' : 'themes/pastel-on-dark.min.css',
  61. 'Solarized Dark' : 'themes/solarized-dark.min.css',
  62. 'Terminal' : 'themes/terminal.min.css',
  63. 'Tomorrow Night' : 'themes/tomorrow-night.min.css',
  64. 'Tomorrow Night Blue' : 'themes/tomorrow-night-blue.min.css',
  65. 'Tomorrow Night Bright' : 'themes/tomorrow-night-bright.min.css',
  66. 'Tomorrow Night Eigthies' : 'themes/tomorrow-night-eighties.min.css',
  67. 'Twilight' : 'themes/twilight.min.css',
  68. 'Vibrant Ink' : 'themes/vibrant-ink.min.css'
  69. },
  70.  
  71. type : {
  72. 'tiled' : 'background-repeat: repeat !important; background-size: auto !important; background-position: left top !important;',
  73. 'fit' : 'background-repeat: no-repeat !important; background-size: cover !important; background-position: center top !important;'
  74. },
  75.  
  76. wrapCss : {
  77. 'wrapped' : 'white-space: pre-wrap !important; word-break: break-all !important; display: block !important;',
  78. 'unwrap' : 'white-space: pre !important; word-break: normal !important; display: block !important;'
  79. },
  80.  
  81. wrapCodeCss : [
  82. '/* GitHub Bug: Enable wrapping of long code lines */',
  83. ' .blob-code-inner,',
  84. ' .markdown-body pre > code,',
  85. ' .markdown-body .highlight > pre {',
  86. ' white-space: pre-wrap !important;',
  87. ' word-break: break-all !important;',
  88. ' display: block !important;',
  89. ' }',
  90. ' td.blob-code-inner {',
  91. ' display: table-cell !important;',
  92. ' }'
  93. ].join('\n'),
  94.  
  95. wrapIcon : '<div class="ghd-wrap-toggle tooltipped tooltipped-n" aria-label="Toggle code wrap"><svg xmlns="http://www.w3.org/2000/svg" width="768" height="768" viewBox="0 0 768 768"><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"/></svg></div>',
  96.  
  97. // extract style & theme name
  98. regex: /\/\*! [^\*]+ \*\//,
  99.  
  100. updatePanel : function() {
  101. // prevent multiple change events from processing
  102. this.isUpdating = true;
  103.  
  104. var color,
  105. data = this.data,
  106. defaults = this.defaults,
  107. $panel = $('#ghd-settings-inner');
  108.  
  109. $panel.find('.ghd-attach').val(data.attach || defaults.attach);
  110. $panel.find('.ghd-font').val(data.font || defaults.font);
  111. $panel.find('.ghd-image').val(data.image || defaults.image);
  112. $panel.find('.ghd-tab').val(data.tab || defaults.tab);
  113. $panel.find('.ghd-theme').val(data.theme || defaults.theme);
  114. $panel.find('.ghd-type').val(data.type || defaults.type);
  115.  
  116. $panel.find('.ghd-enable').prop('checked', typeof data.enable === 'boolean' ? data.enable : defaults.enable);
  117. $panel.find('.ghd-wrap').prop('checked', typeof data.wrap === 'boolean' ? data.wrap : defaults.wrap);
  118.  
  119. color = data.color || defaults.color;
  120. $panel.find('.ghd-color').val(color);
  121. // update swatch color & color picker value
  122. $panel.find('#ghd-swatch').css('background-color', color);
  123.  
  124. if (this.picker) {
  125. this.picker.fromString(color);
  126. }
  127. this.$style.prop('disabled', !data.enable);
  128. $('body')
  129. .toggleClass('ghd-disabled', !data.enable)
  130. .toggleClass('nowrap', !data.wrap);
  131.  
  132. this.isUpdating = false;
  133. },
  134.  
  135. /*
  136. this.data = {
  137. attach : 'scroll',
  138. color : '#4183C4',
  139. enable : true,
  140. font : 'Menlo',
  141. image : 'url()',
  142. tab : 4,
  143. theme : 'Tomorrow Night',
  144. type : 'tiled',
  145. wrap : true, // code: wrap long lines
  146.  
  147. date : 1450159200000, // last loaded package.json
  148. version : '001014032', // v1.14.32 = last stored GitHub-Dark version
  149.  
  150. rawCss : '@-moz-document regexp("^...', // github-dark.css (unprocessed css)
  151. themeCss : '/*! Tomorrow Night * /.ace_editor,.highlight{...', // theme/{name}.min.css
  152. processedCss : '' // css saved directly from this.$style
  153. }
  154. */
  155. getStoredValues : function() {
  156. var $panel = $('#ghd-settings-inner'),
  157. defaults = this.defaults,
  158.  
  159. data = this.data = {
  160. attach : GM_getValue('attach', defaults.attach),
  161. color : GM_getValue('color', defaults.color),
  162. enable : GM_getValue('enable', defaults.enable),
  163. font : GM_getValue('font', defaults.font),
  164. image : GM_getValue('image', defaults.image),
  165. tab : GM_getValue('tab', defaults.tab),
  166. theme : GM_getValue('theme', defaults.theme),
  167. type : GM_getValue('type', defaults.type),
  168. wrap : GM_getValue('wrap', defaults.wrap),
  169.  
  170. date : GM_getValue('date', 0),
  171. version : GM_getValue('version', 0),
  172.  
  173. rawCss : GM_getValue('rawCss', ''),
  174. themeCss : GM_getValue('themeCss', ''),
  175. processedCss : GM_getValue('processedCss', '')
  176. };
  177.  
  178. debug('Retrieved stored values', this.data);
  179.  
  180. },
  181.  
  182. setStoredValues : function(reset) {
  183. var data = this.data,
  184. defaults = this.defaults;
  185.  
  186. GM_setValue('attach', reset ? defaults.attach : data.attach);
  187. GM_setValue('color', reset ? defaults.color : data.color);
  188. GM_setValue('enable', reset ? defaults.enable : data.enable);
  189. GM_setValue('font', reset ? defaults.font : data.font);
  190. GM_setValue('image', reset ? defaults.image : data.image);
  191. GM_setValue('tab', reset ? defaults.tab : data.tab);
  192. GM_setValue('theme', reset ? defaults.theme : data.theme);
  193. GM_setValue('type', reset ? defaults.type : data.type);
  194. GM_setValue('wrap', reset ? defaults.wrap : data.wrap);
  195.  
  196. GM_setValue('date', reset ? 0 : data.date);
  197. GM_setValue('version', reset ? 0 : data.version);
  198.  
  199. GM_setValue('rawCss', data.rawCss);
  200. GM_setValue('themeCss', data.themeCss);
  201. GM_setValue('processedCss', ghd.$style.text());
  202.  
  203. debug((reset ? 'Resetting' : 'Saving') + ' current values', data);
  204. },
  205.  
  206. // convert version "1.2.3" into "001002003" for easier comparison
  207. convertVersion : function(val) {
  208. var index,
  209. parts = val ? val.split('.') : '',
  210. str = '',
  211. len = parts.length;
  212. for (index = 0; index < len; index++) {
  213. str += ('000' + parts[index]).slice(-3);
  214. }
  215. debug('Converted version "' + val + '" to "' + str + '" for easy comparison');
  216. return val ? str : val;
  217. },
  218.  
  219. checkVersion : function() {
  220. debug('Fetching package.json');
  221. GM_xmlhttpRequest({
  222. method : 'GET',
  223. url : ghd.root + 'package.json',
  224. onload : function(response) {
  225. // store package JSON (not accessed anywhere else, but just in case)
  226. ghd.data.package = $.parseJSON(response.responseText);
  227.  
  228. // save last loaded date, so package.json is only loaded once a day
  229. ghd.data.date = new Date().getTime();
  230. GM_setValue('date', ghd.data.date);
  231.  
  232. var version = ghd.convertVersion(ghd.data.package.version);
  233. // if new available, load it & parse
  234. if (version > ghd.data.version) {
  235. if (ghd.data.version !== 0) {
  236. debug('Updating from', ghd.data.version, 'to', version);
  237. }
  238. ghd.data.version = version;
  239. GM_setValue('version', ghd.data.version);
  240. ghd.fetchAndApplyStyle();
  241. } else {
  242. ghd.addSavedStyle();
  243. }
  244. }
  245. });
  246. },
  247.  
  248. fetchAndApplyStyle : function() {
  249. debug('Fetching github-dark.css');
  250. GM_xmlhttpRequest({
  251. method : 'GET',
  252. url : ghd.root + 'github-dark.css',
  253. onload : function(response) {
  254. ghd.data.rawCss = response.responseText;
  255. ghd.applyStyle(ghd.processStyle());
  256. ghd.getTheme();
  257. }
  258. });
  259. },
  260.  
  261. addSavedStyle : function() {
  262. debug('Adding previously saved style');
  263. // apply already processed css to prevent FOUC
  264. this.$style.text(this.data.processedCss);
  265. },
  266.  
  267. // load syntax highlighting theme, if necessary
  268. getTheme : function() {
  269. if (!this.data.enable) {
  270. debug('Disabled: stop theme processing');
  271. return;
  272. }
  273. var name = this.data.theme || 'Twilight';
  274. // test if this.themes contains the url (.min.css), or the actual css
  275. if (/\.min\.css$/.test(this.themes[name])) {
  276. var themeUrl = ghd.root + ghd.themes[name];
  277. debug('Loading "' + name + '" theme', themeUrl);
  278. GM_xmlhttpRequest({
  279. method : 'GET',
  280. url : themeUrl,
  281. onload : function(response) {
  282. var theme = response.responseText;
  283. if (theme) {
  284. ghd.themes[name] = theme;
  285. ghd.data.themeCss = theme;
  286. ghd.processTheme();
  287. } else {
  288. debug('Failed to load theme file', '"' + theme + '"');
  289. }
  290. }
  291. });
  292. } else {
  293. ghd.data.themeCss = ghd.themes[name];
  294. ghd.processTheme();
  295. }
  296. },
  297.  
  298. processStyle : function() {
  299. var data = this.data,
  300. url = /^url/.test(data.image || '') ? data.image :
  301. (data.image === 'none' ? 'none' : 'url("' + data.image + '")');
  302. if (!data.enable) {
  303. debug('Disabled: stop processing');
  304. return;
  305. }
  306. debug('Processing set styles');
  307. return (data.rawCss || '')
  308. // remove moz-document wrapper
  309. .replace(/@-moz-document regexp\((.*)\) \{(\n|\r)+/, '')
  310. // replace background image; if no 'url' at start, then use 'none'
  311. .replace(/\/\*\[\[bg-choice\]\]\*\/ url\(.*\)/, url)
  312. // Add tiled or fit window size css
  313. .replace('/*[[bg-options]]*/', this.type[data.type || 'tiled'])
  314. // set scroll or fixed background image
  315. .replace('/*[[bg-attachment]]*/ fixed', data.attach || 'scroll')
  316. // replace base-color
  317. .replace(/\/\*\[\[base-color\]\]\*\/ #\w{3,6}/g, data.color || '#4183C4')
  318. // add font choice
  319. .replace('/*[[font-choice]]*/', data.font || 'Menlo')
  320. // add tab size
  321. .replace(/\/\*\[\[tab-size\]\]\*\/ \d+/g, data.tab || 4)
  322. // code wrap css
  323. .replace(/\s+\/\* grunt-remove-block-below (.*(\n|\r))+\s+\/\* grunt-remove-block-above \*\//gm, '')
  324. .replace('/*[[code-wrap]]*/', data.wrap ? ghd.wrapCodeCss : '')
  325. // remove default syntax
  326. .replace(/\s+\/\* grunt build - remove to end of file(.*(\n|\r))+\}$/m, '');
  327. },
  328.  
  329. // this.data.themeCss should be populated with user selected theme
  330. // called asynchronously from processStyle()
  331. processTheme : function() {
  332. debug('Adding syntax theme to css');
  333. var css = this.$style.text() || '';
  334. // look for /*[[syntax-theme]]*/ label, if it doesn't exist, reprocess raw css
  335. if (!/syntax-theme/.test(css)) {
  336. debug('Need to process raw style before applying theme');
  337. this.applyStyle(this.processStyle());
  338. css = this.$style.text() || '';
  339. }
  340. // add syntax highlighting theme
  341. css = css.replace('/*[[syntax-theme]]*/', this.data.themeCss || '');
  342.  
  343. debug('Applying "' + this.data.theme + '" theme', '"' +
  344. (this.data.themeCss || '').match(this.regex) + '"');
  345.  
  346. this.$style.text(css);
  347. this.setStoredValues();
  348. this.isUpdating = false;
  349. },
  350.  
  351. applyStyle : function(css) {
  352. debug('Applying style', '"' + (css || '').match(this.regex) + '"');
  353. // add to style
  354. this.$style.text(css || '');
  355. this.setStoredValues();
  356. },
  357.  
  358. updateStyle : function(applyStyle) {
  359. this.isUpdating = true;
  360. var $panel = $('#ghd-settings-inner'),
  361. data = this.data;
  362.  
  363. data.attach = $panel.find('.ghd-attach').val();
  364. data.color = $panel.find('.ghd-color').val();
  365. data.enable = $panel.find('.ghd-enable').is(':checked');
  366. data.font = $panel.find('.ghd-font').val();
  367. data.image = $panel.find('.ghd-image').val();
  368. data.tab = $panel.find('.ghd-tab').val();
  369. data.theme = $panel.find('.ghd-theme').val();
  370. data.type = $panel.find('.ghd-type').val();
  371. data.wrap = $panel.find('.ghd-wrap').is(':checked');
  372.  
  373. debug('Updating user settings', data);
  374.  
  375. this.$style.prop('disabled', !data.enable);
  376. $('body')
  377. .toggleClass('ghd-disabled', !data.enable)
  378. .toggleClass('nowrap', !data.wrap);
  379.  
  380. if (applyStyle !== false) {
  381. this.applyStyle(this.processStyle());
  382. this.getTheme();
  383. }
  384. this.isUpdating = false;
  385. },
  386.  
  387. // user can force GitHub-dark update
  388. forceUpdate : function() {
  389. // clear saved date
  390. GM_setValue('version', 0);
  391. document.location.reload();
  392. },
  393.  
  394. buildSettings : function() {
  395. debug('Adding settings panel & GitHub Dark link to profile dropdown');
  396. // Script-specific CSS
  397. GM_addStyle([
  398. '#ghd-menu:hover { cursor:pointer }',
  399. '#ghd-settings { position:fixed; z-index: 65535; top:0; bottom:0; left:0; right:0; opacity:0; visibility:hidden; }',
  400. '#ghd-settings.in { opacity:1; visibility:visible; background:rgba(0,0,0,.5); }',
  401. '#ghd-settings-inner { position:fixed; left:50%; top:50%; transform:translate(-50%,-50%); width:25rem; box-shadow: 0 .5rem 1rem #111; color:#c0c0c0 }',
  402. '#ghd-settings label { margin-left:.5rem; position:relative; top:-1px }',
  403. '#ghd-settings-close { height: 1rem; width: 1rem; fill: #666; float:right; cursor:pointer }',
  404. '#ghd-settings-close:hover { fill: #ccc }',
  405. '#ghd-settings .ghd-right { float: right; }',
  406. '#ghd-settings p { line-height: 25px; }',
  407. '#ghd-swatch { width:25px; height:25px; display:inline-block; margin:3px 10px; border-radius:4px; }',
  408. '#ghd-settings .checkbox input { margin-top: .35em }',
  409. '#ghd-settings input[type="checkbox"] { width: 16px !important; height: 16px !important; border-radius: 3px !important; }',
  410. '#ghd-settings .boxed-group-inner { padding: 0; }',
  411. '#ghd-settings .ghd-footer { padding: 10px; border-top: #555 solid 1px; }',
  412. '#ghd-settings .ghd-settings-wrapper { max-height: 60vh; overflow-y:auto; padding: 1px 10px; }',
  413. '#ghd-settings .ghd-tab { width: 5em; }',
  414.  
  415. // code wrap toggle: https://gist.github.com/silverwind/6c1701f56e62204cc42b
  416. // icons next to a pre
  417. '.ghd-wrap-toggle { position:absolute; right:1.4em; margin-top:.2em; -moz-user-select:none; -webkit-user-select:none; cursor:pointer; z-index:1000; }',
  418. // file & diff code tables
  419. '.ghd-wrap-table td.blob-code-inner { white-space: pre-wrap !important; word-break: break-all !important; }',
  420. '.ghd-unwrap-table td.blob-code-inner { white-space: pre !important; word-break: normal !important; }',
  421. // icons inside a wrapper immediatly around a pre
  422. '.highlight > .ghd-wrap-toggle { right:.5em; top:.5em; margin-top:0; }',
  423. // icons for non-syntax highlighted code blocks; see https://github.com/gjtorikian/html-proofer/blob/master/README.md
  424. '.markdown-body:not(.comment-body) .ghd-wrap-toggle:not(:first-child) { right: 3.4em; }',
  425. '.ghd-wrap-toggle svg { height:1.25em; width:1.25em; fill:rgba(110,110,110,.4); }',
  426. '.ghd-wrap-toggle.unwrap:hover svg, .ghd-wrap-toggle:hover svg { fill:#8b0000; }', // wrap disabled (red)
  427. 'body:not(.nowrap) .ghd-wrap-toggle:not(.unwrap):hover svg, .ghd-wrap-toggle.wrapped:hover svg { fill:#006400; }', // wrap enabled (green)
  428. '.blob-wrapper, .markdown-body pre, .markdown-body .highlight { position:relative; }',
  429. // hide wrap icon when style disabled
  430. 'body.ghd-disabled .ghd-wrap-toggle { display: none; }'
  431. ].join(''));
  432.  
  433. var themes = '<select class="ghd-theme ghd-right">';
  434. $.each(this.themes, function(opt) {
  435. themes += '<option value="' + opt + '">' + opt + '</option>';
  436. });
  437.  
  438. // Settings panel markup
  439. $('body').append([
  440. '<div id="ghd-settings">',
  441. '<div id="ghd-settings-inner" class="boxed-group">',
  442. '<h3>GitHub-Dark Settings',
  443. '<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>',
  444. '</h3>',
  445. '<div class="boxed-group-inner">',
  446. '<form>',
  447. '<div class="ghd-settings-wrapper">',
  448. '<p class="checkbox">',
  449. '<label>Enable GitHub-Dark<input class="ghd-enable ghd-right ghd-ignoreChange" type="checkbox"></label>',
  450. '</p>',
  451. '<p>',
  452. '<label>Color:</label> <input class="ghd-color ghd-right" type="text" value="#4183C4">',
  453. '<span id="ghd-swatch" class="ghd-right"></span>',
  454. '</p>',
  455. '<h4>Background</h4>',
  456. '<p>',
  457. '<label>Image:</label> <input class="ghd-image ghd-right" type="text">',
  458. '<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"><sup>?</sup></a>',
  459. '</p>',
  460. '<p>',
  461. '<label>Image type:</label>',
  462. '<select class="ghd-type ghd-right">',
  463. '<option value="tiled">Tiled</option>',
  464. '<option value="fit">Fit window</option>',
  465. '</select>',
  466. '</p>',
  467. '<p>',
  468. '<label>Image attachment:</label>',
  469. '<select class="ghd-attach ghd-right">',
  470. '<option value="scroll">Scroll</option>',
  471. '<option value="fixed">Fixed</option>',
  472. '</select>',
  473. '</p>',
  474. '<h4>Code</h4>',
  475. '<p><label>Theme:</label> ' + themes + '</select></p>',
  476. '<p>',
  477. '<label>Font Name:</label> <input class="ghd-font ghd-right" type="text">',
  478. '<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!"><sup>?</sup></a>',
  479. '</p>',
  480. '<p>',
  481. '<label>Tab Size:</label> <input class="ghd-tab ghd-right" type="text">',
  482. '</p>',
  483. '<p class="checkbox">',
  484. '<label>Wrap<input class="ghd-wrap ghd-right" type="checkbox"></label>',
  485. '</p>',
  486. '</div>',
  487. '<div class="ghd-footer">',
  488. '<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>&nbsp;',
  489. '<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>',
  490. '</div>',
  491. '</form>',
  492. '</div>',
  493. '</div>',
  494. '</div>',
  495. ].join(''));
  496.  
  497. ghd.buildCodeWrap();
  498. },
  499.  
  500. buildCodeWrap : function() {
  501. // add wrap code icons
  502. $('.blob-wrapper').prepend(this.wrapIcon);
  503. $('.markdown-body pre').before(this.wrapIcon);
  504. },
  505.  
  506. // add keyboard shortcut to help menu (press "?")
  507. buildShortcut : function() {
  508. var parts = this.keyboardShortcut.split('+');
  509. if (!$('.ghd-shortcut').length) {
  510. $('.keyboard-mappings:eq(0) tbody:eq(0)').append([
  511. '<tr class="ghd-shortcut">',
  512. '<td class="keys">',
  513. '<kbd>' + parts[0] + '</kbd> <kbd>' + parts[1] + '</kbd>',
  514. '</td>',
  515. '<td>Go to GitHub-Dark settings</td>',
  516. '</tr>'
  517. ].join(''));
  518. }
  519. },
  520.  
  521. bindEvents : function() {
  522. var menu, lastKey,
  523. $panel = $('#ghd-settings-inner'),
  524. $swatch = $panel.find('#ghd-swatch');
  525.  
  526. // finish initialization
  527. $('#ghd-settings-inner .ghd-enable')[0].checked = this.data.enable;
  528. $('body').toggleClass('ghd-disabled', !this.data.enable);
  529.  
  530. // Create our menu entry
  531. menu = $('<a id="ghd-menu" class="dropdown-item">GitHub Dark Settings</a>');
  532. $('.header .dropdown-item[href="/settings/profile"], .header .dropdown-item[data-ga-click*="go to profile"]')
  533. // gists only have the "go to profile" item; GitHub has both
  534. .filter(':last')
  535. .after(menu);
  536.  
  537. $('#ghd-menu').on('click', function() {
  538. ghd.openPanel();
  539. });
  540.  
  541. // not sure what GitHub uses, so rolling our own
  542. $(document).on('keyup', function(e) {
  543. clearTimeout(ghd.timer);
  544. // use "g+o" to open up ghd options panel
  545. var parts = ghd.keyboardShortcut.split('+'),
  546. key = String.fromCharCode(e.which).toLowerCase(),
  547. panelVisible = $('#ghd-settings').hasClass('in');
  548.  
  549. // press escape to close the panel
  550. if (e.which === 27 && panelVisible) {
  551. ghd.closePanel();
  552. return;
  553. }
  554.  
  555. if (lastKey === parts[0] && key === parts[1] && !panelVisible &&
  556. // prevent opening panel while typing "go" in comments
  557. !/(input|textarea)/i.test(document.activeElement.nodeName)
  558. ) {
  559. ghd.openPanel();
  560. }
  561. lastKey = key;
  562. ghd.timer = setTimeout(function() {
  563. lastKey = null;
  564. }, ghd.keyboardDelay);
  565.  
  566. // add shortcut to help menu
  567. if (e.which === 191) {
  568. // table doesn't exist until user presses "?"
  569. setTimeout(function() {
  570. ghd.buildShortcut();
  571. }, 300);
  572. }
  573. });
  574.  
  575. // add bindings
  576. $('#ghd-settings, #ghd-settings-close').on('click keyup', function(e) {
  577. // press escape to close settings
  578. if (e.type === 'keyup' && e.which !== 27) {
  579. return;
  580. }
  581. ghd.closePanel();
  582. });
  583.  
  584. $panel.on('click', function(e) {
  585. e.stopPropagation();
  586. });
  587.  
  588. $panel.find('.ghd-reset').on('click', function() {
  589. ghd.isUpdating = true;
  590. // pass true to reset values
  591. ghd.setStoredValues(true);
  592. // add reset values back to this.data
  593. ghd.getStoredValues();
  594. // add reset values to panel
  595. ghd.updatePanel();
  596. // update style
  597. ghd.updateStyle();
  598. return false;
  599. });
  600.  
  601. $panel.find('input[type="text"]').on('focus', function() {
  602. // select all text when focused
  603. this.select();
  604. });
  605.  
  606. $panel.find('select, input').on('change', function() {
  607. if (!ghd.isUpdating) {
  608. // pass false for settings that don't need the style to be
  609. // modified (code wrap or enable/disable)
  610. ghd.updateStyle(!$(this).hasClass('ghd-ignoreChange'));
  611. }
  612. });
  613.  
  614. $panel.find('.ghd-update').on('click', function() {
  615. ghd.forceUpdate();
  616. return false;
  617. });
  618.  
  619. $('body').on('click', '.ghd-wrap-toggle', function() {
  620. var css,
  621. overallWrap = ghd.data.wrap,
  622. $this = $(this),
  623. $code = $this.next('code, pre, .highlight');
  624. if ($code.find('code').length) {
  625. $code = $code.find('code');
  626. }
  627. // code with line numbers
  628. if ($code[0].nodeName === 'TABLE') {
  629. if ($code[0].className.indexOf('ghd-') < 0) {
  630. css = !overallWrap;
  631. } else {
  632. css = $code.hasClass('ghd-unwrap-table');
  633. }
  634. $code
  635. .toggleClass('ghd-wrap-table', css)
  636. .toggleClass('ghd-unwrap-table', !css);
  637. $this
  638. .toggleClass('wrapped', css)
  639. .toggleClass('unwrap', !css);
  640. } else {
  641. css = $code.attr('style') || '';
  642. if (css === '') {
  643. css = ghd.wrapCss[overallWrap ? 'unwrap' : 'wrapped'];
  644. } else {
  645. css = ghd.wrapCss[css === ghd.wrapCss.wrapped ? 'unwrap' : 'wrapped'];
  646. }
  647. $code.attr('style', css);
  648. $this
  649. .toggleClass('wrapped', css === ghd.wrapCss.wrapped)
  650. .toggleClass('unwrap', css === ghd.wrapCss.unwrap);
  651. }
  652. });
  653.  
  654. this.picker = new jscolor($panel.find('.ghd-color')[0]);
  655. this.picker.zIndex = 65536;
  656. this.picker.hash = true;
  657. this.picker.backgroundColor = '#333';
  658. this.picker.padding = 0;
  659. this.picker.borderWidth = 0;
  660. this.picker.borderColor = '#444';
  661. this.picker.onFineChange = function() {
  662. $swatch[0].style.backgroundColor = '#' + ghd.picker;
  663. };
  664.  
  665. },
  666.  
  667. openPanel : function() {
  668. $('.modal-backdrop').click();
  669. ghd.updatePanel();
  670. $('#ghd-settings').addClass('in');
  671. },
  672.  
  673. closePanel : function() {
  674. $('#ghd-settings').removeClass('in');
  675. ghd.picker.hide();
  676.  
  677. // apply changes when the panel is closed
  678. ghd.updateStyle();
  679. },
  680.  
  681. init : function() {
  682. debug('GitHub-Dark Script initializing!');
  683.  
  684. // add style tag to head
  685. ghd.$style = $('<style class="ghd-style">').appendTo('head');
  686.  
  687. this.getStoredValues();
  688. // save stored theme stored themes
  689. this.themes[this.data.theme] = this.data.themeCss;
  690.  
  691. this.$style.prop('disabled', !this.data.enable);
  692.  
  693. // only load package.json once a day, or after a forced update
  694. if ((new Date().getTime() > this.data.date + this.delay) || this.data.version === 0) {
  695. // get package.json from GitHub-Dark & compare versions
  696. // load new script if a newer one is available
  697. this.checkVersion();
  698. } else {
  699. this.addSavedStyle();
  700. }
  701. }
  702. };
  703.  
  704. // add style at document-start
  705. ghd.init();
  706.  
  707. $(function() {
  708. // apply script if option dropdown exists
  709. if ($('.header .dropdown-item[href="/settings/profile"], .header .dropdown-item[data-ga-click*="go to profile"]').length) {
  710. ghd.buildSettings();
  711. // add event binding on document ready
  712. ghd.bindEvents();
  713. }
  714.  
  715. // easier to bind to these events than use mutation observer
  716. unsafeWindow.jQuery('#js-repo-pjax-container, #js-pjax-container, .js-contribution-activity')
  717. .on('pjax:complete', function() {
  718. ghd.buildCodeWrap();
  719. });
  720.  
  721. // save object to jQuery data in main window for easier debugging
  722. unsafeWindow.jQuery('#ghd-settings').data('ghd', ghd);
  723. });
  724.  
  725. // include a "?debug" anywhere in the browser URL to enable debugging
  726. function debug() {
  727. if (/\?debug/.test(window.location.href)) {
  728. console.log.apply(console, arguments);
  729. }
  730. }
  731. })(typeof unsafeWindow !== 'undefined' ? unsafeWindow : window, jQuery.noConflict(true));