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