GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

目前为 2016-02-05 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name GitHub Dark Script
  3. // @version 1.0.0
  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.2.0/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.0',
  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,iVBORw0KGgoAAAANSUhEUgAAAEYAAABGCAYAAABxLuKEAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAAJcEhZcwAACxMAAAsTAQCanBgAAAiKSURBVHjarVzRTmsxDMt/IEAw8f+fyFUnBXm+tpMzeJhgWtbTpqnjuunq/f39++3t7f56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WYpQWi4DLYtWDhhdKapiulzS6g7XFLmUdb4TIGNjrpQ91dRNh2uTcjgVOk0S7XS34MExXOf7FxqtcrK75eKYKleCXmG0qniJD/4akLlflbbwvwXadJCXChHVIHB7Md2xZAlERY1i7+icUhiQDtLVwbyqlEo3VKdysUkScHeylW7tANlh1kMBdNJUVefcdbst81VAq4oIFaC6YkPHaLv4crpjwBysFC1Xy2u6RDrV2/5GcXN3GpDRptrilmYn/HzYKykAVWVgU3XCtlxsYrQI2mdA6ScMGkCdHbbbzpluCLej6y+Y6lbL5chyWQOz2RWgdXadlqeJw4ivLVOd7NKFKicdbAFUCfYOkHlJYeo+/UCblDDKSQdXdJbpIYnR4uD4vdNVJjvl5HRYpxJQpZ86SWy2ZyOVvjuBWpVkTD+JgGx2U8CEzBeF9S1vq7/QaN2WwG0AVYFSAlqciI0dar6ThuyuJtczGi1evEqp3v0aiLpGOP0oD18Rcu2xXdKZ0njrKtC66gS+put+moBlByUdsIPUb8+4nzrA5TOVwqa64XKHYeonBlSJBkfOBLSups8VEiaN1p1EcjZU+y4HDxJjNkx1upGaSkbxV4Yco8VOTmW0aDfdwmdpQ2EiLunomCvVCXw3Ml3kUmVq6abuM1qu05o31RPH9h8GNuBYdEQCqgAAAABJRU5ErkJggg==")',
  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-w" 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.themes[name] = theme;
  286. ghd.data.themeCss = theme;
  287. ghd.processTheme();
  288. } else {
  289. debug('Failed to load theme file', '"' + theme + '"');
  290. }
  291. }
  292. });
  293. } else {
  294. ghd.data.themeCss = ghd.themes[name];
  295. ghd.processTheme();
  296. }
  297. },
  298.  
  299. processStyle : function() {
  300. var data = this.data,
  301. url = /^url/.test(data.image || '') ? data.image :
  302. (data.image === 'none' ? 'none' : 'url("' + data.image + '")');
  303. if (!data.enable) {
  304. debug('Disabled: stop processing');
  305. return;
  306. }
  307. debug('Processing set styles');
  308.  
  309. var ret = (data.rawCss || '')
  310. // remove moz-document wrapper
  311. .replace(/@-moz-document regexp\((.*)\) \{(\n|\r)+/, '')
  312. // replace background image; if no 'url' at start, then use 'none'
  313. .replace(/\/\*\[\[bg-choice\]\]\*\/ url\(.*\)/, url)
  314. // Add tiled or fit window size css
  315. .replace('/*[[bg-options]]*/', this.type[data.type || 'tiled'])
  316. // set scroll or fixed background image
  317. .replace('/*[[bg-attachment]]*/ fixed', data.attach || 'scroll')
  318. // replace base-color
  319. .replace(/\/\*\[\[base-color\]\]\*\/ #\w{3,6}/g, data.color || '#4183C4')
  320. // add font choice
  321. .replace('/*[[font-choice]]*/', data.font || 'Menlo')
  322. // add tab size
  323. .replace(/\/\*\[\[tab-size\]\]\*\/ \d+/g, data.tab || 4)
  324. // code wrap css
  325. .replace('/*[[code-wrap]]*/', data.wrap ? ghd.wrapCodeCss : '')
  326. // remove default syntax
  327. .replace(/\s+\/\* grunt build - remove to end of file(.*(\n|\r))+\}$/m, '');
  328.  
  329. // see https://github.com/StylishThemes/GitHub-Dark/issues/275
  330. if (/firefox/i.test(navigator.userAgent)) {
  331. ret = ret
  332. .replace(/select, input, textarea/, 'select, input:not([type="checkbox"]), textarea')
  333. .replace(/input\[type=\"checkbox\"\][\s\S]+?}/gm, '');
  334. }
  335. return ret;
  336. },
  337.  
  338. // this.data.themeCss should be populated with user selected theme
  339. // called asynchronously from processStyle()
  340. processTheme : function() {
  341. debug('Adding syntax theme to css');
  342. var css = this.$style.text() || '';
  343. // look for /*[[syntax-theme]]*/ label, if it doesn't exist, reprocess raw css
  344. if (!/syntax-theme/.test(css)) {
  345. debug('Need to process raw style before applying theme');
  346. this.applyStyle(this.processStyle());
  347. css = this.$style.text() || '';
  348. }
  349. // add syntax highlighting theme
  350. css = css.replace('/*[[syntax-theme]]*/', this.data.themeCss || '');
  351.  
  352. debug('Applying "' + this.data.theme + '" theme', '"' +
  353. (this.data.themeCss || '').match(this.regex) + '"');
  354.  
  355. this.$style.text(css);
  356. this.setStoredValues();
  357. this.isUpdating = false;
  358. },
  359.  
  360. applyStyle : function(css) {
  361. debug('Applying style', '"' + (css || '').match(this.regex) + '"');
  362. // add to style
  363. this.$style.text(css || '');
  364. this.setStoredValues();
  365. },
  366.  
  367. updateStyle : function() {
  368. this.isUpdating = true;
  369. var $panel = $('#ghd-settings-inner'),
  370. data = this.data;
  371.  
  372. data.attach = $panel.find('.ghd-attach').val();
  373. // get hex value directly
  374. data.color = this.picker.toHEXString();
  375. data.enable = $panel.find('.ghd-enable').is(':checked');
  376. data.font = $panel.find('.ghd-font').val();
  377. data.image = $panel.find('.ghd-image').val();
  378. data.tab = $panel.find('.ghd-tab').val();
  379. data.theme = $panel.find('.ghd-theme').val();
  380. data.type = $panel.find('.ghd-type').val();
  381. data.wrap = $panel.find('.ghd-wrap').is(':checked');
  382.  
  383. debug('Updating user settings', data);
  384.  
  385. this.$style.prop('disabled', !data.enable);
  386. $('body')
  387. .toggleClass('ghd-disabled', !data.enable)
  388. .toggleClass('nowrap', !data.wrap);
  389.  
  390. this.applyStyle(this.processStyle());
  391. this.getTheme();
  392. this.isUpdating = false;
  393. },
  394.  
  395. // user can force GitHub-dark update
  396. forceUpdate : function() {
  397. var raw = $('#ghd-settings-inner').find('.dropdown-menu').val();
  398. if (raw === '') {
  399. // clear saved date
  400. GM_setValue('version', 0);
  401. document.location.reload();
  402. } else {
  403. // Add raw css directly for style testing
  404. ghd.data.rawCss = raw;
  405. ghd.applyStyle(ghd.processStyle());
  406. ghd.getTheme();
  407. }
  408. },
  409.  
  410. buildSettings : function() {
  411. debug('Adding settings panel & GitHub Dark link to profile dropdown');
  412. // Script-specific CSS
  413. GM_addStyle([
  414. '#ghd-menu:hover { cursor:pointer }',
  415. '#ghd-settings { position:fixed; z-index: 65535; top:0; bottom:0; left:0; right:0; opacity:0; visibility:hidden; }',
  416. '#ghd-settings.in { opacity:1; visibility:visible; background:rgba(0,0,0,.5); }',
  417. '#ghd-settings-inner { position:fixed; left:50%; top:50%; transform:translate(-50%,-50%); width:25rem; box-shadow: 0 .5rem 1rem #111; color:#c0c0c0 }',
  418. '#ghd-settings label { margin-left:.5rem; position:relative; top:-1px }',
  419. '#ghd-settings-close { height: 1rem; width: 1rem; fill: #666; float:right; cursor:pointer }',
  420. '#ghd-settings-close:hover { fill: #ccc }',
  421. '#ghd-settings .ghd-right { float: right; }',
  422. '#ghd-settings p { line-height: 25px; }',
  423. '#ghd-swatch { width:25px; height:25px; display:inline-block; margin:3px 10px; border-radius:4px; }',
  424. '#ghd-settings .checkbox input { margin-top: .35em }',
  425. '#ghd-settings input[type="checkbox"] { width: 16px !important; height: 16px !important; border-radius: 3px !important; }',
  426. '#ghd-settings .boxed-group-inner { padding: 0; }',
  427. '#ghd-settings .ghd-footer { padding: 10px; border-top: #555 solid 1px; }',
  428. '#ghd-settings .ghd-settings-wrapper { max-height: 60vh; overflow-y:auto; padding: 1px 10px; }',
  429. '#ghd-settings .ghd-tab { width: 5em; }',
  430. '#ghd-settings .ghd-info { vertical-align: middle; }',
  431. // flip arrow -> dropup menu
  432. '#ghd-settings .ghd-textarea-toggle:after { border-top-color:transparent !important; border-bottom-color:#eee !important; vertical-align:3px; }',
  433. '#ghd-settings .dropdown-menu { position:absolute; bottom:50px; top:37px; left:2px; right:2px; width:396px; z-index:0; }',
  434.  
  435. // code wrap toggle: https://gist.github.com/silverwind/6c1701f56e62204cc42b
  436. // icons next to a pre
  437. '.ghd-wrap-toggle { position:absolute; right:1.4em; margin-top:.2em; -moz-user-select:none; -webkit-user-select:none; cursor:pointer; z-index:20; }',
  438. // file & diff code tables
  439. '.ghd-wrap-table td.blob-code-inner { white-space: pre-wrap !important; word-break: break-all !important; }',
  440. '.ghd-unwrap-table td.blob-code-inner { white-space: pre !important; word-break: normal !important; }',
  441. // icons inside a wrapper immediatly around a pre
  442. '.highlight > .ghd-wrap-toggle { right:.5em; top:.5em; margin-top:0; }',
  443. // icons for non-syntax highlighted code blocks; see https://github.com/gjtorikian/html-proofer/blob/master/README.md
  444. '.markdown-body:not(.comment-body) .ghd-wrap-toggle:not(:first-child) { right: 3.4em; }',
  445. '.ghd-wrap-toggle svg { height:1.25em; width:1.25em; fill:rgba(110,110,110,.4); }',
  446. '.ghd-wrap-toggle.unwrap:hover svg, .ghd-wrap-toggle:hover svg { fill:#8b0000; }', // wrap disabled (red)
  447. 'body:not(.nowrap) .ghd-wrap-toggle:not(.unwrap):hover svg, .ghd-wrap-toggle.wrapped:hover svg { fill:#006400; }', // wrap enabled (green)
  448. '.blob-wrapper, .markdown-body pre, .markdown-body .highlight { position:relative; }',
  449. // hide wrap icon when style disabled
  450. 'body.ghd-disabled .ghd-wrap-toggle { display: none; }',
  451. // monospace font toggle
  452. '.ghd-monospace-font { font-family: Menlo, Inconsolata, "Droid Mono", monospace !important; font-size: 1em !important; }'
  453. ].join(''));
  454.  
  455. var version = [],
  456. themes = '<select class="ghd-theme ghd-right">',
  457. // convert stored css version from "001014049" into "1.14.49" for tooltip
  458. parts = String(this.data.version).match(/\d{3}/g);
  459. $.each(this.themes, function(opt) {
  460. themes += '<option value="' + opt + '">' + opt + '</option>';
  461. });
  462. if (parts && parts.length) {
  463. $.each(parts, function(_i, v) {
  464. version.push(parseInt(v));
  465. });
  466. }
  467.  
  468. // Settings panel markup
  469. $('body').append([
  470. '<div id="ghd-settings">',
  471. '<div id="ghd-settings-inner" class="boxed-group">',
  472. '<h3>GitHub-Dark Settings',
  473. '<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>',
  474. '</h3>',
  475. '<div class="boxed-group-inner">',
  476. '<form>',
  477. '<div class="ghd-settings-wrapper">',
  478. '<p class="checkbox">',
  479. '<label>Enable GitHub-Dark<input class="ghd-enable ghd-right" type="checkbox"></label>',
  480. '</p>',
  481. '<p>',
  482. '<label>Color:</label> <input class="ghd-color ghd-right" type="text" value="#4183C4">',
  483. '<span id="ghd-swatch" class="ghd-right"></span>',
  484. '</p>',
  485. '<h4>Background</h4>',
  486. '<p>',
  487. '<label>Image:</label> <input class="ghd-image ghd-right" type="text">',
  488. '<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>',
  489. '</p>',
  490. '<p>',
  491. '<label>Image type:</label>',
  492. '<select class="ghd-type ghd-right">',
  493. '<option value="tiled">Tiled</option>',
  494. '<option value="fit">Fit window</option>',
  495. '</select>',
  496. '</p>',
  497. '<p>',
  498. '<label>Image attachment:</label>',
  499. '<select class="ghd-attach ghd-right">',
  500. '<option value="scroll">Scroll</option>',
  501. '<option value="fixed">Fixed</option>',
  502. '</select>',
  503. '</p>',
  504. '<h4>Code</h4>',
  505. '<p><label>Theme:</label> ' + themes + '</select></p>',
  506. '<p>',
  507. '<label>Font Name:</label> <input class="ghd-font ghd-right" type="text">',
  508. '<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>',
  509. '</p>',
  510. '<p>',
  511. '<label>Tab Size:</label> <input class="ghd-tab ghd-right" type="text">',
  512. '</p>',
  513. '<p class="checkbox">',
  514. '<label>Wrap<input class="ghd-wrap ghd-right" type="checkbox"></label>',
  515. '</p>',
  516. '</div>',
  517. '<div class="ghd-footer">',
  518. '<div class="btn-group">',
  519. '<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>',
  520. '<a href="#" class="ghd-textarea-toggle btn btn-sm select-menu-button"></a>',
  521. '<div class="dropdown-menu-content" aria-hidden="true">',
  522. '<textarea class="dropdown-menu" placeholder="Enter a &quot;raw&quot; GitHub-Dark Style, then press &quot;Force Update Style&quot;"></textarea>',
  523. '</div>',
  524. '</div>&nbsp;',
  525. '<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>',
  526. '<span class="ghd-right tooltipped tooltipped-n" aria-label="Script v' + this.version + '&#10;CSS ' + (version.length ? 'v' + version.join('.') : 'unknown') + '">',
  527. '<svg class="ghd-info" xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 24 24">',
  528. '<path fill="#444" d="M12,9c0.82,0,1.5-0.68,1.5-1.5S12.82,6,12,6s-1.5,0.68-1.5,1.5S11.18,9,12,9z M12,1.5 C6.211,1.5,1.5,6.211,1.5,12S6.211,22.5,12,22.5S22.5,17.789,22.5,12S17.789,1.5,12,1.5z M12,19.5c-4.148,0-7.5-3.352-7.5-7.5 S7.852,4.5,12,4.5s7.5,3.352,7.5,7.5S16.148,19.5,12,19.5z M13.5,12c0-0.75-0.75-1.5-1.5-1.5s-0.75,0-1.5,0S9,11.25,9,12h1.5 c0,0,0,3.75,0,4.5S11.25,18,12,18s0.75,0,1.5,0s1.5-0.75,1.5-1.5h-1.5C13.5,16.5,13.5,12.75,13.5,12z"/>',
  529. '</svg>',
  530. '</span>',
  531. '</div>',
  532. '</form>',
  533. '</div>',
  534. '</div>',
  535. '</div>',
  536. ].join(''));
  537.  
  538. ghd.buildCodeWrap();
  539. ghd.addMonospaceToggle();
  540. },
  541.  
  542. buildCodeWrap : function() {
  543. // mutation events happen quick, so we still add an update flag
  544. this.isUpdating = true;
  545. // add wrap code icons
  546. $('.blob-wrapper').prepend(this.wrapIcon);
  547. $('.markdown-body pre').before(this.wrapIcon);
  548. this.isUpdating = false;
  549. },
  550.  
  551. addMonospaceToggle : function() {
  552. this.isUpdating = true;
  553. var indx, $el,
  554. $toolbars = $('.toolbar-commenting'),
  555. len = $toolbars.length;
  556. for (indx = 0; indx < len; indx++) {
  557. $el = $toolbars.eq(indx);
  558. if (!$el.find('.ghd-monospace').length) {
  559. $el.prepend([
  560. '<button type="button" class="ghd-monospace toolbar-item tooltipped tooltipped-n" aria-label="Toggle monospaced font" tabindex="-1">',
  561. '<svg class="octicon" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="18px" height="18px" viewBox="0 0 25 25" fill="#767676">',
  562. '<rect x="11.5" y="2.5" width="3" height="3"/><rect x="11.5" y="7.5" width="3" height="3"/>',
  563. '<rect x="11.5" y="11.5" width="3" height="3"/><rect x="11.5" y="15.5" width="3" height="3"/>',
  564. '<rect x="11.5" y="19.5" width="3" height="3"/><rect x="15.5" y="19.5" width="3" height="3"/>',
  565. '<rect x="7.5" y="19.5" width="3" height="3"/><rect x="7.5" y="7.5" width="3" height="3"/>',
  566. '</svg>',
  567. '</button>'
  568. ].join(''));
  569. }
  570. }
  571. this.isUpdating = false;
  572. },
  573.  
  574. // add keyboard shortcut to help menu (press "?")
  575. buildShortcut : function() {
  576. var openPanel = this.keyboardOpen.split('+'),
  577. toggleStyle = this.keyboardToggle.split('+');
  578. if (!$('.ghd-shortcut').length) {
  579. $('.keyboard-mappings:eq(0) tbody:eq(0)').append([
  580. '<tr class="ghd-shortcut">',
  581. '<td class="keys">',
  582. '<kbd>' + openPanel[0] + '</kbd> <kbd>' + openPanel[1] + '</kbd>',
  583. '</td>',
  584. '<td>GitHub-Dark: open settings</td>',
  585. '</tr>',
  586. '<tr class="ghd-shortcut">',
  587. '<td class="keys">',
  588. '<kbd>' + toggleStyle[0] + '</kbd> <kbd>' + toggleStyle[1] + '</kbd>',
  589. '</td>',
  590. '<td>GitHub-Dark: toggle style</td>',
  591. '</tr>'
  592. ].join(''));
  593. }
  594. },
  595.  
  596. bindEvents : function() {
  597. var menu, lastKey,
  598. $panel = $('#ghd-settings-inner'),
  599. $swatch = $panel.find('#ghd-swatch');
  600.  
  601. // finish initialization
  602. $('#ghd-settings-inner .ghd-enable')[0].checked = this.data.enable;
  603. $('body').toggleClass('ghd-disabled', !this.data.enable);
  604.  
  605. // Create our menu entry
  606. menu = $('<a id="ghd-menu" class="dropdown-item">GitHub Dark Settings</a>');
  607. $('.header .dropdown-item[href="/settings/profile"], .header .dropdown-item[data-ga-click*="go to profile"]')
  608. // gists only have the "go to profile" item; GitHub has both
  609. .filter(':last')
  610. .after(menu);
  611.  
  612. $('#ghd-menu').on('click', function() {
  613. ghd.openPanel();
  614. });
  615.  
  616. // not sure what GitHub uses, so rolling our own
  617. $(document).on('keypress keydown', function(e) {
  618. clearTimeout(ghd.timer);
  619. // use "g+o" to open up ghd options panel
  620. var openPanel = ghd.keyboardOpen.split('+'),
  621. toggleStyle = ghd.keyboardToggle.split('+'),
  622. key = String.fromCharCode(e.which).toLowerCase(),
  623. panelVisible = $('#ghd-settings').hasClass('in');
  624.  
  625. // press escape to close the panel
  626. if (e.which === 27 && panelVisible) {
  627. ghd.closePanel();
  628. return;
  629. }
  630. // use e.which from keypress for shortcuts
  631. // prevent opening panel while typing "go" in comments
  632. if (e.type === 'keydown' || /(input|textarea)/i.test(document.activeElement.nodeName)) {
  633. return;
  634. }
  635. if (lastKey === openPanel[0] && key === openPanel[1]) {
  636. if (panelVisible) {
  637. ghd.closePanel();
  638. } else {
  639. ghd.openPanel();
  640. }
  641. }
  642. if (lastKey === toggleStyle[0] && key === toggleStyle[1]) {
  643. ghd.toggleStyle();
  644. }
  645. lastKey = key;
  646. ghd.timer = setTimeout(function() {
  647. lastKey = null;
  648. }, ghd.keyboardDelay);
  649.  
  650. // add shortcut to help menu
  651. if (key === '?') {
  652. // table doesn't exist until user presses "?"
  653. setTimeout(function() {
  654. ghd.buildShortcut();
  655. }, 300);
  656. }
  657. });
  658.  
  659. // add bindings
  660. $('#ghd-settings, #ghd-settings-close').on('click keyup', function(e) {
  661. // press escape to close settings
  662. if (e.type === 'keyup' && e.which !== 27) {
  663. return;
  664. }
  665. ghd.closePanel();
  666. });
  667.  
  668. $panel.on('click', function(e) {
  669. e.stopPropagation();
  670. });
  671.  
  672. $panel.find('.ghd-reset').on('click', function() {
  673. ghd.isUpdating = true;
  674. // pass true to reset values
  675. ghd.setStoredValues(true);
  676. // add reset values back to this.data
  677. ghd.getStoredValues();
  678. // add reset values to panel
  679. ghd.updatePanel();
  680. // update style
  681. ghd.updateStyle();
  682. return false;
  683. });
  684.  
  685. $panel.find('input[type="text"]').on('focus', function() {
  686. // select all text when focused
  687. this.select();
  688. });
  689.  
  690. $panel.find('select, input').on('change', function() {
  691. if (!ghd.isUpdating) {
  692. ghd.updateStyle();
  693. }
  694. });
  695.  
  696. $panel.find('.ghd-update').on('click', function() {
  697. ghd.forceUpdate();
  698. return false;
  699. });
  700.  
  701. $panel.find('.ghd-textarea-toggle').on('click', function() {
  702. var $this = $(this),
  703. $dropdown = $this
  704. .removeClass('selected')
  705. .next('.dropdown-menu-content')
  706. .toggle();
  707. if ($dropdown.is(':visible')) {
  708. $this.addClass('selected');
  709. $dropdown.find('textarea').focus();
  710. }
  711. });
  712.  
  713. // code wrap toggle
  714. $('body').on('click', '.ghd-wrap-toggle', function() {
  715. var css,
  716. overallWrap = ghd.data.wrap,
  717. $this = $(this),
  718. $code = $this.next('code, pre, .highlight');
  719. if ($code.find('code').length) {
  720. $code = $code.find('code');
  721. }
  722. // code with line numbers
  723. if ($code[0].nodeName === 'TABLE') {
  724. if ($code[0].className.indexOf('ghd-') < 0) {
  725. css = !overallWrap;
  726. } else {
  727. css = $code.hasClass('ghd-unwrap-table');
  728. }
  729. $code
  730. .toggleClass('ghd-wrap-table', css)
  731. .toggleClass('ghd-unwrap-table', !css);
  732. $this
  733. .toggleClass('wrapped', css)
  734. .toggleClass('unwrap', !css);
  735. } else {
  736. css = $code.attr('style') || '';
  737. if (css === '') {
  738. css = ghd.wrapCss[overallWrap ? 'unwrap' : 'wrapped'];
  739. } else {
  740. css = ghd.wrapCss[css === ghd.wrapCss.wrapped ? 'unwrap' : 'wrapped'];
  741. }
  742. $code.attr('style', css);
  743. $this
  744. .toggleClass('wrapped', css === ghd.wrapCss.wrapped)
  745. .toggleClass('unwrap', css === ghd.wrapCss.unwrap);
  746. }
  747. });
  748.  
  749. // monospace font toggle
  750. $('body').on('click', '.ghd-monospace', function(e) {
  751. e.stopPropagation();
  752. var $this = $(this),
  753. $textarea = $this
  754. // each comment
  755. .closest('.timeline-comment')
  756. .find('.comment-form-textarea')
  757. .toggleClass('ghd-monospace-font')
  758. .focus();
  759. $this.toggleClass('ghd-icon-active', $textarea.hasClass('ghd-monospace-font'));
  760. return false;
  761. });
  762.  
  763. this.picker = new jscolor($panel.find('.ghd-color')[0]);
  764. this.picker.zIndex = 65536;
  765. this.picker.hash = true;
  766. this.picker.backgroundColor = '#333';
  767. this.picker.padding = 0;
  768. this.picker.borderWidth = 0;
  769. this.picker.borderColor = '#444';
  770. this.picker.onFineChange = function() {
  771. $swatch[0].style.backgroundColor = '#' + ghd.picker;
  772. };
  773. },
  774.  
  775. openPanel : function() {
  776. $('.modal-backdrop').click();
  777. ghd.updatePanel();
  778. $('#ghd-settings').addClass('in');
  779. },
  780.  
  781. closePanel : function() {
  782. $('#ghd-settings').removeClass('in');
  783. ghd.picker.hide();
  784.  
  785. // apply changes when the panel is closed
  786. ghd.updateStyle();
  787. },
  788.  
  789. toggleStyle : function() {
  790. var isEnabled = !this.data.enable;
  791. this.data.enable = isEnabled;
  792. $('#ghd-settings-inner .ghd-enable').prop('checked', isEnabled);
  793. // add processedCss back into style (emptied when disabled)
  794. if (isEnabled) {
  795. this.addSavedStyle();
  796. }
  797. this.$style.prop('disabled', !isEnabled);
  798. },
  799.  
  800. init : function() {
  801. debug('GitHub-Dark Script initializing!');
  802.  
  803. // add style tag to head
  804. ghd.$style = $('<style class="ghd-style">').appendTo('head');
  805.  
  806. this.getStoredValues();
  807. // save stored theme stored themes
  808. if (this.data.themeCss) {
  809. this.themes[this.data.theme] = this.data.themeCss;
  810. }
  811.  
  812. this.$style.prop('disabled', !this.data.enable);
  813.  
  814. // only load package.json once a day, or after a forced update
  815. if ((new Date().getTime() > this.data.date + this.delay) || this.data.version === 0) {
  816. // get package.json from GitHub-Dark & compare versions
  817. // load new script if a newer one is available
  818. this.checkVersion();
  819. } else {
  820. this.addSavedStyle();
  821. }
  822. }
  823. };
  824.  
  825. // add style at document-start
  826. ghd.init();
  827.  
  828. $(function() {
  829. // add panel even if you're not logged in - open panel using keyboard shortcut
  830. ghd.buildSettings();
  831. // add event binding on document ready
  832. ghd.bindEvents();
  833.  
  834. var targets = document.querySelectorAll('#js-repo-pjax-container, #js-pjax-container, .js-contribution-activity');
  835.  
  836. Array.prototype.forEach.call(targets, function(target) {
  837. new MutationObserver(function(mutations) {
  838. mutations.forEach(function(mutation) {
  839. // preform checks before adding code wrap to minimize function calls
  840. if (!(ghd.isUpdating || document.querySelectorAll('.ghd-wrap-toggle').length) && mutation.target === target) {
  841. ghd.buildCodeWrap();
  842. ghd.addMonospaceToggle();
  843. }
  844. });
  845. }).observe(target, {
  846. childList: true,
  847. subtree: true
  848. });
  849. });
  850. });
  851.  
  852. // include a "?debug" anywhere in the browser URL to enable debugging
  853. function debug() {
  854. if (/\?debug/.test(window.location.href)) {
  855. console.log.apply(console, arguments);
  856. }
  857. }
  858. })(jQuery.noConflict(true));