GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

当前为 2016-01-26 提交的版本,查看 最新版本

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