GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

Από την 26/12/2015. Δείτε την τελευταία έκδοση.

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