Greasy Fork 支持简体中文。

GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

目前為 2016-01-30 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name GitHub Dark Script
  3. // @version 1.0.3-beta
  4. // @description GitHub Dark in userscript form, with a settings panel
  5. // @namespace https://github.com/StylishThemes
  6. // @include /https?://((gist|guides|help|raw|status|developer)\.)?github\.com((?!generated_pages\/preview).)*$/
  7. // @include /render\.githubusercontent\.com/
  8. // @include /raw\.githubusercontent\.com/
  9. // @grant GM_addStyle
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @grant GM_xmlhttpRequest
  13. // @run-at document-start
  14. // @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js
  15. // @require https://greasyfork.org/scripts/15563-jscolor/code/jscolor.js?version=97027
  16. // ==/UserScript==
  17. /* global jQuery, GM_addStyle, GM_getValue, GM_setValue, GM_xmlhttpRequest, jscolor */
  18. /* eslint-disable indent, quotes */
  19. (function($) {
  20. 'use strict';
  21.  
  22. var ghd = {
  23.  
  24. version : '1.0.2-beta',
  25.  
  26. // delay until package.json allowed to load
  27. delay : 8.64e7, // 24 hours in milliseconds
  28.  
  29. // Keyboard shortcut to open ghd panel (only a two key combo coded)
  30. keyboardOpen : 'g+0',
  31. keyboardToggle : 'g+-',
  32. // keyboard shortcut delay from first to second letter
  33. keyboardDelay : 1000,
  34.  
  35. // base urls to fetch style and package.json
  36. root : 'https://raw.githubusercontent.com/StylishThemes/GitHub-Dark/master/',
  37.  
  38. defaults : {
  39. attach : 'scroll',
  40. color : '#4183C4',
  41. enable : true,
  42. font : 'Menlo',
  43. image : 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkAgMAAAANjH3HAAAACVBMVEUaGhohISElJSUh9lebAAAB20lEQVRIx4XWuZXDMAwE0C0SAQtggIIYoAAEU+aKOHhYojTrYP2+QfOW/5QIJOih/q8HwF/pb3EX+UPIveYcQGgEHiu9hI+ihEc5Jz5KBIlRRRaJ1JtoSAl5Hw96hLB1/up1tnIXOck5jZQy+3iU2hAOKSH1JvwxHsp+5TLF5MOl1/MQXsVs1miXc+KDbYydyMeUgpPQreZ7fWidbNhkXNJSeAhc6qHmHD8AYovunYyEACWEbyIhNeB9fRrH3hFi0bGPLuEW7xCNaohw1vAlS805nfsrTspclB/hVdoqusg53eH7FWot+wjYpOViX8KbFFKTwlnzvj65P9H/vD0/hibYBGhPwlPO8TmxRsaxsNnrUmUXpNhirlJMPr6Hqq9k5Xn/8iYQHYIuQsWFC6Z87IOxLxHphSY4SpuiU87xJnJr5axfeRd+lnMExXpEWPpuZ1v7qZdNBOjiHzDREHX5fs5Zz9p6X0vVKbKKchlSl5rv+3p//FJ/PYvoKryI8vs+2G9lzRmnEKkh+BU8yDk515jDj/HAswu7CCz6U/Mxb/PnC9N41ndpU4hUU7JGk/C9PmP/M2xZYdvBW2PObyf1IUiIzoHmHW9yTncliYs9A9tVNppdShfgQaTLMf+j3X723tLeHgAAAABJRU5ErkJggg==")',
  44. tab : 4,
  45. theme : 'Twilight',
  46. type : 'tiled',
  47. wrap : false
  48. },
  49.  
  50. // url gets replaced by css when loaded
  51. themes : {
  52. 'Ambiance' : 'themes/ambiance.min.css',
  53. 'Chaos' : 'themes/chaos.min.css',
  54. 'Clouds Midnight' : 'themes/clouds-midnight.min.css',
  55. 'Cobalt' : 'themes/cobalt.min.css',
  56. 'Idle Fingers' : 'themes/idle-fingers.min.css',
  57. 'Kr Theme' : 'themes/kr-theme.min.css',
  58. 'Merbivore' : 'themes/merbivore.min.css',
  59. 'Merbivore Soft' : 'themes/merbivore-soft.min.css',
  60. 'Mono Industrial' : 'themes/mono-industrial.min.css',
  61. 'Mono Industrial Clear' : 'themes/mono-industrial-clear.min.css',
  62. 'Monokai' : 'themes/monokai.min.css',
  63. 'Pastel on Dark' : 'themes/pastel-on-dark.min.css',
  64. 'Solarized Dark' : 'themes/solarized-dark.min.css',
  65. 'Terminal' : 'themes/terminal.min.css',
  66. 'Tomorrow Night' : 'themes/tomorrow-night.min.css',
  67. 'Tomorrow Night Blue' : 'themes/tomorrow-night-blue.min.css',
  68. 'Tomorrow Night Bright' : 'themes/tomorrow-night-bright.min.css',
  69. 'Tomorrow Night Eigthies' : 'themes/tomorrow-night-eighties.min.css',
  70. 'Twilight' : 'themes/twilight.min.css',
  71. 'Vibrant Ink' : 'themes/vibrant-ink.min.css'
  72. },
  73.  
  74. type : {
  75. 'tiled' : 'background-repeat: repeat !important; background-size: auto !important; background-position: left top !important;',
  76. 'fit' : 'background-repeat: no-repeat !important; background-size: cover !important; background-position: center top !important;'
  77. },
  78.  
  79. wrapCss : {
  80. 'wrapped' : 'white-space: pre-wrap !important; word-break: break-all !important; display: block !important;',
  81. 'unwrap' : 'white-space: pre !important; word-break: normal !important; display: block !important;'
  82. },
  83.  
  84. wrapCodeCss : [
  85. '/* GitHub: Enable wrapping of long code lines */',
  86. ' .blob-code-inner,',
  87. ' .markdown-body pre > code,',
  88. ' .markdown-body .highlight > pre {',
  89. ' white-space: pre-wrap !important;',
  90. ' word-break: break-all !important;',
  91. ' display: block !important;',
  92. ' }',
  93. ' td.blob-code-inner {',
  94. ' display: table-cell !important;',
  95. ' }'
  96. ].join('\n'),
  97.  
  98. wrapIcon : '<div class="ghd-wrap-toggle tooltipped tooltipped-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. return (data.rawCss || '')
  309. // remove moz-document wrapper
  310. .replace(/@-moz-document regexp\((.*)\) \{(\n|\r)+/, '')
  311. // replace background image; if no 'url' at start, then use 'none'
  312. .replace(/\/\*\[\[bg-choice\]\]\*\/ url\(.*\)/, url)
  313. // Add tiled or fit window size css
  314. .replace('/*[[bg-options]]*/', this.type[data.type || 'tiled'])
  315. // set scroll or fixed background image
  316. .replace('/*[[bg-attachment]]*/ fixed', data.attach || 'scroll')
  317. // replace base-color
  318. .replace(/\/\*\[\[base-color\]\]\*\/ #\w{3,6}/g, data.color || '#4183C4')
  319. // add font choice
  320. .replace('/*[[font-choice]]*/', data.font || 'Menlo')
  321. // add tab size
  322. .replace(/\/\*\[\[tab-size\]\]\*\/ \d+/g, data.tab || 4)
  323. // code wrap css
  324. .replace('/*[[code-wrap]]*/', data.wrap ? ghd.wrapCodeCss : '')
  325. // remove default syntax
  326. .replace(/\s+\/\* grunt build - remove to end of file(.*(\n|\r))+\}$/m, '')
  327. // reset checkboxes - see https://github.com/StylishThemes/GitHub-Dark/issues/275
  328. .replace(/select, input, textarea/, 'select, input:not([type="checkbox"]), textarea');
  329. },
  330.  
  331. // this.data.themeCss should be populated with user selected theme
  332. // called asynchronously from processStyle()
  333. processTheme : function() {
  334. debug('Adding syntax theme to css');
  335. var css = this.$style.text() || '';
  336. // look for /*[[syntax-theme]]*/ label, if it doesn't exist, reprocess raw css
  337. if (!/syntax-theme/.test(css)) {
  338. debug('Need to process raw style before applying theme');
  339. this.applyStyle(this.processStyle());
  340. css = this.$style.text() || '';
  341. }
  342. // add syntax highlighting theme
  343. css = css.replace('/*[[syntax-theme]]*/', this.data.themeCss || '');
  344.  
  345. debug('Applying "' + this.data.theme + '" theme', '"' +
  346. (this.data.themeCss || '').match(this.regex) + '"');
  347.  
  348. this.$style.text(css);
  349. this.setStoredValues();
  350. this.isUpdating = false;
  351. },
  352.  
  353. applyStyle : function(css) {
  354. debug('Applying style', '"' + (css || '').match(this.regex) + '"');
  355. // add to style
  356. this.$style.text(css || '');
  357. this.setStoredValues();
  358. },
  359.  
  360. updateStyle : function() {
  361. this.isUpdating = true;
  362. var $panel = $('#ghd-settings-inner'),
  363. data = this.data;
  364.  
  365. data.attach = $panel.find('.ghd-attach').val();
  366. data.color = $panel.find('.ghd-color').val();
  367. data.enable = $panel.find('.ghd-enable').is(':checked');
  368. data.font = $panel.find('.ghd-font').val();
  369. data.image = $panel.find('.ghd-image').val();
  370. data.tab = $panel.find('.ghd-tab').val();
  371. data.theme = $panel.find('.ghd-theme').val();
  372. data.type = $panel.find('.ghd-type').val();
  373. data.wrap = $panel.find('.ghd-wrap').is(':checked');
  374.  
  375. debug('Updating user settings', data);
  376.  
  377. this.$style.prop('disabled', !data.enable);
  378. $('body')
  379. .toggleClass('ghd-disabled', !data.enable)
  380. .toggleClass('nowrap', !data.wrap);
  381.  
  382. this.applyStyle(this.processStyle());
  383. this.getTheme();
  384. this.isUpdating = false;
  385. },
  386.  
  387. // user can force GitHub-dark update
  388. forceUpdate : function() {
  389. // clear saved date
  390. GM_setValue('version', 0);
  391. document.location.reload();
  392. },
  393.  
  394. buildSettings : function() {
  395. debug('Adding settings panel & GitHub Dark link to profile dropdown');
  396. // Script-specific CSS
  397. GM_addStyle([
  398. '#ghd-menu:hover { cursor:pointer }',
  399. '#ghd-settings { position:fixed; z-index: 65535; top:0; bottom:0; left:0; right:0; opacity:0; visibility:hidden; }',
  400. '#ghd-settings.in { opacity:1; visibility:visible; background:rgba(0,0,0,.5); }',
  401. '#ghd-settings-inner { position:fixed; left:50%; top:50%; transform:translate(-50%,-50%); width:25rem; box-shadow: 0 .5rem 1rem #111; color:#c0c0c0 }',
  402. '#ghd-settings label { margin-left:.5rem; position:relative; top:-1px }',
  403. '#ghd-settings-close { height: 1rem; width: 1rem; fill: #666; float:right; cursor:pointer }',
  404. '#ghd-settings-close:hover { fill: #ccc }',
  405. '#ghd-settings .ghd-right { float: right; }',
  406. '#ghd-settings p { line-height: 25px; }',
  407. '#ghd-swatch { width:25px; height:25px; display:inline-block; margin:3px 10px; border-radius:4px; }',
  408. '#ghd-settings .checkbox input { margin-top: .35em }',
  409. '#ghd-settings input[type="checkbox"] { width: 16px !important; height: 16px !important; border-radius: 3px !important; }',
  410. '#ghd-settings .boxed-group-inner { padding: 0; }',
  411. '#ghd-settings .ghd-footer { padding: 10px; border-top: #555 solid 1px; }',
  412. '#ghd-settings .ghd-settings-wrapper { max-height: 60vh; overflow-y:auto; padding: 1px 10px; }',
  413. '#ghd-settings .ghd-tab { width: 5em; }',
  414. '#ghd-settings .ghd-info { vertical-align: middle; }',
  415.  
  416. // code wrap toggle: https://gist.github.com/silverwind/6c1701f56e62204cc42b
  417. // icons next to a pre
  418. '.ghd-wrap-toggle { position:absolute; right:1.4em; margin-top:.2em; -moz-user-select:none; -webkit-user-select:none; cursor:pointer; z-index:20; }',
  419. // file & diff code tables
  420. '.ghd-wrap-table td.blob-code-inner { white-space: pre-wrap !important; word-break: break-all !important; }',
  421. '.ghd-unwrap-table td.blob-code-inner { white-space: pre !important; word-break: normal !important; }',
  422. // icons inside a wrapper immediatly around a pre
  423. '.highlight > .ghd-wrap-toggle { right:.5em; top:.5em; margin-top:0; }',
  424. // icons for non-syntax highlighted code blocks; see https://github.com/gjtorikian/html-proofer/blob/master/README.md
  425. '.markdown-body:not(.comment-body) .ghd-wrap-toggle:not(:first-child) { right: 3.4em; }',
  426. '.ghd-wrap-toggle svg { height:1.25em; width:1.25em; fill:rgba(110,110,110,.4); }',
  427. '.ghd-wrap-toggle.unwrap:hover svg, .ghd-wrap-toggle:hover svg { fill:#8b0000; }', // wrap disabled (red)
  428. 'body:not(.nowrap) .ghd-wrap-toggle:not(.unwrap):hover svg, .ghd-wrap-toggle.wrapped:hover svg { fill:#006400; }', // wrap enabled (green)
  429. '.blob-wrapper, .markdown-body pre, .markdown-body .highlight { position:relative; }',
  430. // hide wrap icon when style disabled
  431. 'body.ghd-disabled .ghd-wrap-toggle { display: none; }'
  432. ].join(''));
  433.  
  434. var version = [],
  435. themes = '<select class="ghd-theme ghd-right">';
  436. $.each(this.themes, function(opt) {
  437. themes += '<option value="' + opt + '">' + opt + '</option>';
  438. });
  439. $.each(this.data.version.match(/\d{3}/g), function(i, v) {
  440. version.push(parseInt(v, 10));
  441. });
  442.  
  443. // Settings panel markup
  444. $('body').append([
  445. '<div id="ghd-settings">',
  446. '<div id="ghd-settings-inner" class="boxed-group">',
  447. '<h3>GitHub-Dark Settings',
  448. '<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>',
  449. '</h3>',
  450. '<div class="boxed-group-inner">',
  451. '<form>',
  452. '<div class="ghd-settings-wrapper">',
  453. '<p class="checkbox">',
  454. '<label>Enable GitHub-Dark<input class="ghd-enable ghd-right" type="checkbox"></label>',
  455. '</p>',
  456. '<p>',
  457. '<label>Color:</label> <input class="ghd-color ghd-right" type="text" value="#4183C4">',
  458. '<span id="ghd-swatch" class="ghd-right"></span>',
  459. '</p>',
  460. '<h4>Background</h4>',
  461. '<p>',
  462. '<label>Image:</label> <input class="ghd-image ghd-right" type="text">',
  463. '<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>',
  464. '</p>',
  465. '<p>',
  466. '<label>Image type:</label>',
  467. '<select class="ghd-type ghd-right">',
  468. '<option value="tiled">Tiled</option>',
  469. '<option value="fit">Fit window</option>',
  470. '</select>',
  471. '</p>',
  472. '<p>',
  473. '<label>Image attachment:</label>',
  474. '<select class="ghd-attach ghd-right">',
  475. '<option value="scroll">Scroll</option>',
  476. '<option value="fixed">Fixed</option>',
  477. '</select>',
  478. '</p>',
  479. '<h4>Code</h4>',
  480. '<p><label>Theme:</label> ' + themes + '</select></p>',
  481. '<p>',
  482. '<label>Font Name:</label> <input class="ghd-font ghd-right" type="text">',
  483. '<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>',
  484. '</p>',
  485. '<p>',
  486. '<label>Tab Size:</label> <input class="ghd-tab ghd-right" type="text">',
  487. '</p>',
  488. '<p class="checkbox">',
  489. '<label>Wrap<input class="ghd-wrap ghd-right" type="checkbox"></label>',
  490. '</p>',
  491. '</div>',
  492. '<div class="ghd-footer">',
  493. '<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;',
  494. '<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>',
  495. '<span class="ghd-info ghd-right tooltipped tooltipped-n" aria-label="Script v' + this.version + '&#10;CSS v' + version.join('.') + '"><span class="octicon octicon-info"></span></span>',
  496. '</div>',
  497. '</form>',
  498. '</div>',
  499. '</div>',
  500. '</div>',
  501. ].join(''));
  502.  
  503. ghd.buildCodeWrap();
  504. },
  505.  
  506. buildCodeWrap : function() {
  507. // mutation events happen quick, so we still add an update flag
  508. this.isUpdating = true;
  509. // add wrap code icons
  510. $('.blob-wrapper').prepend(this.wrapIcon);
  511. $('.markdown-body pre').before(this.wrapIcon);
  512. this.isUpdating = false;
  513. },
  514.  
  515. // add keyboard shortcut to help menu (press "?")
  516. buildShortcut : function() {
  517. var openPanel = this.keyboardOpen.split('+'),
  518. toggleStyle = this.keyboardToggle.split('+');
  519. if (!$('.ghd-shortcut').length) {
  520. $('.keyboard-mappings:eq(0) tbody:eq(0)').append([
  521. '<tr class="ghd-shortcut">',
  522. '<td class="keys">',
  523. '<kbd>' + openPanel[0] + '</kbd> <kbd>' + openPanel[1] + '</kbd>',
  524. '</td>',
  525. '<td>GitHub-Dark: open settings</td>',
  526. '</tr>',
  527. '<tr class="ghd-shortcut">',
  528. '<td class="keys">',
  529. '<kbd>' + toggleStyle[0] + '</kbd> <kbd>' + toggleStyle[1] + '</kbd>',
  530. '</td>',
  531. '<td>GitHub-Dark: toggle style</td>',
  532. '</tr>'
  533. ].join(''));
  534. }
  535. },
  536.  
  537. bindEvents : function() {
  538. var menu, lastKey,
  539. $panel = $('#ghd-settings-inner'),
  540. $swatch = $panel.find('#ghd-swatch');
  541.  
  542. // finish initialization
  543. $('#ghd-settings-inner .ghd-enable')[0].checked = this.data.enable;
  544. $('body').toggleClass('ghd-disabled', !this.data.enable);
  545.  
  546. // Create our menu entry
  547. menu = $('<a id="ghd-menu" class="dropdown-item">GitHub Dark Settings</a>');
  548. $('.header .dropdown-item[href="/settings/profile"], .header .dropdown-item[data-ga-click*="go to profile"]')
  549. // gists only have the "go to profile" item; GitHub has both
  550. .filter(':last')
  551. .after(menu);
  552.  
  553. $('#ghd-menu').on('click', function() {
  554. ghd.openPanel();
  555. });
  556.  
  557. // not sure what GitHub uses, so rolling our own
  558. $(document).on('keypress keydown', function(e) {
  559. clearTimeout(ghd.timer);
  560. // use "g+o" to open up ghd options panel
  561. var openPanel = ghd.keyboardOpen.split('+'),
  562. toggleStyle = ghd.keyboardToggle.split('+'),
  563. key = String.fromCharCode(e.which).toLowerCase(),
  564. panelVisible = $('#ghd-settings').hasClass('in');
  565.  
  566. // press escape to close the panel
  567. if (e.which === 27 && panelVisible) {
  568. ghd.closePanel();
  569. return;
  570. }
  571. // use e.which from keypress for shortcuts
  572. // prevent opening panel while typing "go" in comments
  573. if (e.type === 'keydown' || /(input|textarea)/i.test(document.activeElement.nodeName)) {
  574. return;
  575. }
  576. if (lastKey === openPanel[0] && key === openPanel[1]) {
  577. if (panelVisible) {
  578. ghd.closePanel();
  579. } else {
  580. ghd.openPanel();
  581. }
  582. }
  583. if (lastKey === toggleStyle[0] && key === toggleStyle[1]) {
  584. ghd.toggleStyle();
  585. }
  586. lastKey = key;
  587. ghd.timer = setTimeout(function() {
  588. lastKey = null;
  589. }, ghd.keyboardDelay);
  590.  
  591. // add shortcut to help menu
  592. if (key === '?') {
  593. // table doesn't exist until user presses "?"
  594. setTimeout(function() {
  595. ghd.buildShortcut();
  596. }, 300);
  597. }
  598. });
  599.  
  600. // add bindings
  601. $('#ghd-settings, #ghd-settings-close').on('click keyup', function(e) {
  602. // press escape to close settings
  603. if (e.type === 'keyup' && e.which !== 27) {
  604. return;
  605. }
  606. ghd.closePanel();
  607. });
  608.  
  609. $panel.on('click', function(e) {
  610. e.stopPropagation();
  611. });
  612.  
  613. $panel.find('.ghd-reset').on('click', function() {
  614. ghd.isUpdating = true;
  615. // pass true to reset values
  616. ghd.setStoredValues(true);
  617. // add reset values back to this.data
  618. ghd.getStoredValues();
  619. // add reset values to panel
  620. ghd.updatePanel();
  621. // update style
  622. ghd.updateStyle();
  623. return false;
  624. });
  625.  
  626. $panel.find('input[type="text"]').on('focus', function() {
  627. // select all text when focused
  628. this.select();
  629. });
  630.  
  631. $panel.find('select, input').on('change', function() {
  632. if (!ghd.isUpdating) {
  633. ghd.updateStyle();
  634. }
  635. });
  636.  
  637. $panel.find('.ghd-update').on('click', function() {
  638. ghd.forceUpdate();
  639. return false;
  640. });
  641.  
  642. $('body').on('click', '.ghd-wrap-toggle', function() {
  643. var css,
  644. overallWrap = ghd.data.wrap,
  645. $this = $(this),
  646. $code = $this.next('code, pre, .highlight');
  647. if ($code.find('code').length) {
  648. $code = $code.find('code');
  649. }
  650. // code with line numbers
  651. if ($code[0].nodeName === 'TABLE') {
  652. if ($code[0].className.indexOf('ghd-') < 0) {
  653. css = !overallWrap;
  654. } else {
  655. css = $code.hasClass('ghd-unwrap-table');
  656. }
  657. $code
  658. .toggleClass('ghd-wrap-table', css)
  659. .toggleClass('ghd-unwrap-table', !css);
  660. $this
  661. .toggleClass('wrapped', css)
  662. .toggleClass('unwrap', !css);
  663. } else {
  664. css = $code.attr('style') || '';
  665. if (css === '') {
  666. css = ghd.wrapCss[overallWrap ? 'unwrap' : 'wrapped'];
  667. } else {
  668. css = ghd.wrapCss[css === ghd.wrapCss.wrapped ? 'unwrap' : 'wrapped'];
  669. }
  670. $code.attr('style', css);
  671. $this
  672. .toggleClass('wrapped', css === ghd.wrapCss.wrapped)
  673. .toggleClass('unwrap', css === ghd.wrapCss.unwrap);
  674. }
  675. });
  676.  
  677. this.picker = new jscolor($panel.find('.ghd-color')[0]);
  678. this.picker.zIndex = 65536;
  679. this.picker.hash = true;
  680. this.picker.backgroundColor = '#333';
  681. this.picker.padding = 0;
  682. this.picker.borderWidth = 0;
  683. this.picker.borderColor = '#444';
  684. this.picker.onFineChange = function() {
  685. $swatch[0].style.backgroundColor = '#' + ghd.picker;
  686. };
  687. },
  688.  
  689. openPanel : function() {
  690. $('.modal-backdrop').click();
  691. ghd.updatePanel();
  692. $('#ghd-settings').addClass('in');
  693. },
  694.  
  695. closePanel : function() {
  696. $('#ghd-settings').removeClass('in');
  697. ghd.picker.hide();
  698.  
  699. // apply changes when the panel is closed
  700. ghd.updateStyle();
  701. },
  702.  
  703. toggleStyle : function() {
  704. var isEnabled = !this.data.enable;
  705. this.data.enable = isEnabled;
  706. $('#ghd-settings-inner .ghd-enable').prop('checked', isEnabled);
  707. // add processedCss back into style (emptied when disabled)
  708. if (isEnabled) {
  709. this.addSavedStyle();
  710. }
  711. this.$style.prop('disabled', !isEnabled);
  712. },
  713.  
  714. init : function() {
  715. debug('GitHub-Dark Script initializing!');
  716.  
  717. // add style tag to head
  718. ghd.$style = $('<style class="ghd-style">').appendTo('head');
  719.  
  720. this.getStoredValues();
  721. // save stored theme stored themes
  722. if (this.data.themeCss) {
  723. this.themes[this.data.theme] = this.data.themeCss;
  724. }
  725.  
  726. this.$style.prop('disabled', !this.data.enable);
  727.  
  728. // only load package.json once a day, or after a forced update
  729. if ((new Date().getTime() > this.data.date + this.delay) || this.data.version === 0) {
  730. // get package.json from GitHub-Dark & compare versions
  731. // load new script if a newer one is available
  732. this.checkVersion();
  733. } else {
  734. this.addSavedStyle();
  735. }
  736. }
  737. };
  738.  
  739. // add style at document-start
  740. ghd.init();
  741.  
  742. $(function() {
  743. // add panel even if you're not logged in - open panel using keyboard shortcut
  744. ghd.buildSettings();
  745. // add event binding on document ready
  746. ghd.bindEvents();
  747.  
  748. var targets = document.querySelectorAll('#js-repo-pjax-container, #js-pjax-container, .js-contribution-activity');
  749.  
  750. Array.prototype.forEach.call(targets, function(target) {
  751. new MutationObserver(function(mutations) {
  752. mutations.forEach(function(mutation) {
  753. // preform checks before adding code wrap to minimize function calls
  754. if (!(ghd.isUpdating || document.querySelectorAll('.ghd-wrap-toggle').length) && mutation.target === target) {
  755. ghd.buildCodeWrap();
  756. }
  757. });
  758. }).observe(target, {
  759. childList: true,
  760. subtree: true
  761. });
  762. });
  763. });
  764.  
  765. // include a "?debug" anywhere in the browser URL to enable debugging
  766. function debug() {
  767. if (/\?debug/.test(window.location.href)) {
  768. console.log.apply(console, arguments);
  769. }
  770. }
  771. })(jQuery.noConflict(true));