GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

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

  1. // ==UserScript==
  2. // @name GitHub Dark Script
  3. // @version 2.0.7
  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 https://*.githubusercontent.com/*
  8. // @grant GM_addStyle
  9. // @grant GM_getValue
  10. // @grant GM_setValue
  11. // @grant GM_info
  12. // @grant GM_xmlhttpRequest
  13. // @grant GM_registerMenuCommand
  14. // @connect githubusercontent.com
  15. // @connect raw.githubusercontent.com
  16. // @run-at document-start
  17. // @require https://greasyfork.org/scripts/15563-jscolor/code/jscolor.js?version=106439
  18. // ==/UserScript==
  19. /* global GM_addStyle, GM_getValue, GM_setValue, GM_info, GM_xmlhttpRequest, GM_registerMenuCommand, jscolor */
  20. /* jshint esnext:true */
  21. (() => {
  22. 'use strict';
  23.  
  24. const version = GM_info.script.version,
  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,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")',
  44. tab : 4,
  45. theme : 'Twilight',
  46. type : 'tiled',
  47. wrap : false,
  48.  
  49. // toggle buttons
  50. enableCodeWrap : true,
  51. enableMonospace : true,
  52. // diff toggle + accordion mode
  53. modeDiffToggle : '1',
  54.  
  55. // internal variables
  56. date : 0,
  57. version : 0,
  58. rawCss : '',
  59. themeCss : '',
  60. processedCss : '',
  61. last : {}
  62. },
  63.  
  64. // extract style & theme name
  65. regex = /\/\*! [^\*]+ \*\//,
  66. // "themes/" prefix not included here
  67. themes = {
  68. 'Ambiance' : 'ambiance.min.css',
  69. 'Chaos' : 'chaos.min.css',
  70. 'Clouds Midnight' : 'clouds-midnight.min.css',
  71. 'Cobalt' : 'cobalt.min.css',
  72. 'Idle Fingers' : 'idle-fingers.min.css',
  73. 'Kr Theme' : 'kr-theme.min.css',
  74. 'Merbivore' : 'merbivore.min.css',
  75. 'Merbivore Soft' : 'merbivore-soft.min.css',
  76. 'Mono Industrial' : 'mono-industrial.min.css',
  77. 'Mono Industrial Clear' : 'mono-industrial-clear.min.css',
  78. 'Monokai' : 'monokai.min.css',
  79. 'Obsidian' : 'obsidian.min.css',
  80. 'Pastel on Dark' : 'pastel-on-dark.min.css',
  81. 'Solarized Dark' : 'solarized-dark.min.css',
  82. 'Terminal' : 'terminal.min.css',
  83. 'Tomorrow Night' : 'tomorrow-night.min.css',
  84. 'Tomorrow Night Blue' : 'tomorrow-night-blue.min.css',
  85. 'Tomorrow Night Bright' : 'tomorrow-night-bright.min.css',
  86. 'Tomorrow Night Eigthies' : 'tomorrow-night-eighties.min.css',
  87. 'Twilight' : 'twilight.min.css',
  88. 'Vibrant Ink' : 'vibrant-ink.min.css'
  89. },
  90.  
  91. type = {
  92. tiled : `
  93. background-repeat: repeat !important;
  94. background-size: auto !important;
  95. background-position: left top !important;
  96. `,
  97. fit : `
  98. background-repeat: no-repeat !important;
  99. background-size: cover !important;
  100. background-position: center top !important;
  101. `
  102. },
  103.  
  104. wrapCss = {
  105. wrapped : `
  106. white-space: pre-wrap !important;
  107. word-break: break-all !important;
  108. overflow-wrap: break-word !important;
  109. display: block !important;
  110. `,
  111. unwrap : `
  112. white-space: pre !important;
  113. word-break: normal !important;
  114. display: block !important;
  115. `
  116. },
  117.  
  118. // https://github.com/StylishThemes/GitHub-code-wrap/blob/master/github-code-wrap.css
  119. wrapCodeCss = `
  120. /* GitHub: Enable wrapping of long code lines */
  121. .blob-code-inner,
  122. .markdown-body pre > code,
  123. .markdown-body .highlight > pre { ${wrapCss.wrapped} }
  124. td.blob-code-inner {
  125. display: table-cell !important;
  126. }
  127. `,
  128.  
  129. wrapIcon = `
  130. <svg xmlns="http://www.w3.org/2000/svg" width="768" height="768" viewBox="0 0 768 768">
  131. <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"/>
  132. </svg>
  133. `,
  134.  
  135. monospaceIcon = `
  136. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 32 32">
  137. <path d="M5.91 7.31v8.41c0 .66.05 1.09.14 1.31.09.21.23.37.41.48.18.11.52.16 1.02.16v.41H2.41v-.41c.5 0 .86-.05 1.03-.14.16-.11.3-.27.41-.5.11-.23.16-.66.16-1.3V11.7c0-1.14-.04-1.87-.11-2.2-.04-.26-.13-.42-.24-.53-.11-.1-.27-.14-.46-.14-.21 0-.48.05-.77.18l-.18-.41 3.14-1.28h.52v-.01zm-.95-5.46c.32 0 .59.11.82.34.23.23.34.5.34.82 0 .32-.11.59-.34.82-.23.22-.51.34-.82.34-.32 0-.59-.11-.82-.34s-.36-.5-.36-.82c0-.32.11-.59.34-.82.24-.23.51-.34.84-.34zm19.636 19.006h-3.39v-1.64h5.39v9.8h3.43v1.66h-9.18v-1.66h3.77v-8.16h-.02zm.7-6.44c.21 0 .43.04.63.13.18.09.36.2.5.34s.25.3.34.5c.07.18.13.39.13.61 0 .22-.04.41-.13.61s-.19.36-.34.5-.3.25-.5.32c-.2.09-.39.13-.62.13-.21 0-.43-.04-.61-.12-.19-.07-.35-.19-.5-.34-.14-.14-.25-.3-.34-.5-.07-.2-.13-.39-.13-.61s.04-.43.13-.61c.07-.18.2-.36.34-.5s.31-.25.5-.34c.17-.09.39-.12.6-.12zM2 30L27.82 2H30L4.14 30H2z"/>
  138. </svg>
  139. `,
  140.  
  141. fileIcon = `
  142. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="10" height="6.5" viewBox="0 0 10 6.5">
  143. <path d="M0 1.497L1.504 0l3.49 3.76L8.505.016 10 1.52 4.988 6.51 0 1.496z"/>
  144. </svg>
  145. `,
  146.  
  147. $style = make({
  148. el: 'style',
  149. cl4ss: 'ghd-style'
  150. });
  151.  
  152. let timer, picker, // jscolor picker
  153. isInitialized = 'pending',
  154. // prevent mutationObserver from going nuts
  155. isUpdating = false,
  156. // set when css code to test is pasted into the settings panel
  157. testing = false,
  158. //
  159. debug = GM_getValue('debug', false),
  160. data = {};
  161.  
  162. function updatePanel() {
  163. if (!isInitialized || !$('#ghd-settings-inner')) { return; }
  164. // prevent multiple change events from processing
  165. isUpdating = true;
  166.  
  167. let temp, el,
  168. body = $('body'),
  169. panel = $('#ghd-settings-inner');
  170.  
  171. $('.ghd-attach', panel).value = data.attach || defaults.attach;
  172. $('.ghd-font', panel).value = data.font || defaults.font;
  173. $('.ghd-image', panel).value = data.image || defaults.image;
  174. $('.ghd-tab', panel).value = data.tab || defaults.tab;
  175. $('.ghd-theme', panel).value = data.theme || defaults.theme;
  176. $('.ghd-type', panel).value = data.type || defaults.type;
  177.  
  178. $('.ghd-enable', panel).checked = isBool('enable');
  179. $('.ghd-wrap', panel).checked = isBool('wrap');
  180.  
  181. $('.ghd-codewrap-checkbox', panel).checked = isBool('enableCodeWrap');
  182. $('.ghd-monospace-checkbox', panel).checked = isBool('enableMonospace');
  183.  
  184. el = $('.ghd-diff-select', panel);
  185. temp = '' + (data.modeDiffToggle || defaults.modeDiffToggle);
  186. el.value = temp;
  187. toggleClass(el, 'enabled', temp !== '0');
  188.  
  189. // update version tooltip
  190. $('.ghd-versions', panel).setAttribute('aria-label', getVersionTooltip());
  191.  
  192. temp = data.color || defaults.color;
  193. $('.ghd-color').value = temp;
  194. // update swatch color & color picker value
  195. $('#ghd-swatch').style.backgroundColor = temp;
  196.  
  197. if (picker) {
  198. picker.fromString(temp);
  199. }
  200. $style.disabled = !data.enable;
  201.  
  202. toggleClass(body, 'ghd-disabled', !data.enable);
  203. toggleClass(body, 'nowrap', !data.wrap);
  204.  
  205. if (data.enableCodeWrap !== data.lastCW ||
  206. data.enableMonospace !== data.lastMS ||
  207. data.modeDiffToggle !== data.lastDT) {
  208.  
  209. data.lastCW = data.enableCodeWrap;
  210. data.lastMS = data.enableMonospace;
  211. data.lastDT = data.modeDiffToggle;
  212. updateToggles();
  213. }
  214.  
  215. isUpdating = false;
  216. }
  217.  
  218. function getStoredValues(init) {
  219. data = GM_getValue('data', defaults);
  220. if (debug) {
  221. if (init) {
  222. console.log('GitHub-Dark Script initializing!');
  223. }
  224. console.log('Retrieved stored values', data);
  225. }
  226. }
  227.  
  228. function setStoredValues(reset) {
  229. data.processedCss = $style.textContent;
  230. GM_setValue('data', reset ? defaults : data);
  231. updatePanel();
  232. if (debug) {
  233. console.log((reset ? 'Resetting' : 'Saving') + ' current values', data);
  234. }
  235. }
  236.  
  237. // modified from http://stackoverflow.com/a/5624139/145346
  238. function hexToRgb(hex) {
  239. let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  240. return result ? [
  241. parseInt(result[1], 16),
  242. parseInt(result[2], 16),
  243. parseInt(result[3], 16)
  244. ].join(", ") : "";
  245. }
  246.  
  247. // convert version "1.2.3" into "001002003" for easier comparison
  248. function convertVersion(val) {
  249. let index,
  250. parts = val ? val.split('.') : '',
  251. str = '',
  252. len = parts.length;
  253. for (index = 0; index < len; index++) {
  254. str += ('000' + parts[index]).slice(-3);
  255. }
  256. if (debug) {
  257. console.log(`Converted version "${val}" to "${str}" for easy comparison`);
  258. }
  259. return val ? str : val;
  260. }
  261.  
  262. function checkVersion() {
  263. if (debug) {
  264. console.log('Fetching package.json');
  265. }
  266. GM_xmlhttpRequest({
  267. method : 'GET',
  268. url : root + 'package.json',
  269. onload : response => {
  270. let pkg = JSON.parse(response.responseText);
  271.  
  272. // save last loaded date, so package.json is only loaded once a day
  273. data.date = new Date().getTime();
  274.  
  275. let ver = convertVersion(pkg.version);
  276. // if new available, load it & parse
  277. if (ver > data.version) {
  278. if (data.version !== 0 && debug) {
  279. console.log('Updating from ${data.version} to ${ver}');
  280. }
  281. data.version = ver;
  282. fetchAndApplyStyle();
  283. } else {
  284. addSavedStyle();
  285. }
  286. // save new date/version
  287. GM_setValue('data', data);
  288. }
  289. });
  290. }
  291.  
  292. function fetchAndApplyStyle() {
  293. if (debug) {
  294. console.log(`Fetching ${root}github-dark.css`);
  295. }
  296. GM_xmlhttpRequest({
  297. method : 'GET',
  298. url : root + 'github-dark.css',
  299. onload : response => {
  300. data.rawCss = response.responseText;
  301. processStyle();
  302. }
  303. });
  304. }
  305.  
  306. // load syntax highlighting theme
  307. function fetchAndApplyTheme() {
  308. if (!data.enable) {
  309. if (debug) {
  310. console.log('Disabled: stop theme processing');
  311. }
  312. return;
  313. }
  314. if (data.lastTheme === data.theme && data.themeCss !== '') {
  315. return applyTheme();
  316. }
  317. let name = data.theme || 'Twilight',
  318. themeUrl = root + 'themes/' + themes[name];
  319. if (debug) {
  320. console.log(`Fetching ${name} theme`, themeUrl);
  321. }
  322. GM_xmlhttpRequest({
  323. method : 'GET',
  324. url : themeUrl,
  325. onload : response => {
  326. let theme = response.responseText;
  327. if (response.status === 200 && theme) {
  328. data.themeCss = theme;
  329. data.lastTheme = name;
  330. applyTheme();
  331. } else {
  332. throw Error(`Failed to load theme file: "${theme}"`);
  333. }
  334. }
  335. });
  336. }
  337.  
  338. function applyTheme() {
  339. if (debug) {
  340. console.log('Adding syntax theme "' + (data.themeCss || '').match(regex) + '" to css');
  341. }
  342. let css = data.processedCss || '';
  343. css = css.replace('/*[[syntax-theme]]*/', data.themeCss || '');
  344. applyStyle(css);
  345. setStoredValues();
  346. isUpdating = false;
  347. }
  348.  
  349. function processStyle() {
  350. let url = /^url/.test(data.image || '') ? data.image :
  351. (data.image === 'none' ? 'none' : 'url("' + data.image + '")');
  352. if (!data.enable) {
  353. if (debug) {
  354. console.log('Disabled: stop processing');
  355. }
  356. return;
  357. }
  358. if (debug) {
  359. console.log('Processing set styles');
  360. }
  361.  
  362. let processed = (data.rawCss || '')
  363. // remove moz-document wrapper
  364. .replace(/@-moz-document regexp\((.*)\) \{(\n|\r)+/, '')
  365. // replace background image; if no 'url' at start, then use 'none'
  366. .replace(/\/\*\[\[bg-choice\]\]\*\/ url\(.*\)/, url)
  367. // Add tiled or fit window size css
  368. .replace('/*[[bg-options]]*/', type[data.type || 'tiled'])
  369. // set scroll or fixed background image
  370. .replace('/*[[bg-attachment]]*/ fixed', data.attach || 'scroll')
  371. // replace base-color
  372. .replace(/\/\*\[\[base-color\]\]\*\/ #\w{3,6}/g, data.color || '#4183C4')
  373. // replace base-color-rgb
  374. .replace(/\/\*\[\[base-color-rgb\]\]\*\//g, hexToRgb(data.color || '#4183c4'))
  375. // add font choice
  376. .replace('/*[[font-choice]]*/', data.font || 'Menlo')
  377. // add tab size
  378. .replace(/\/\*\[\[tab-size\]\]\*\/ \d+/g, data.tab || 4)
  379. // code wrap css
  380. .replace('/*[[code-wrap]]*/', data.wrap ? wrapCodeCss : '')
  381. // remove default syntax
  382. .replace(/\s+\/\* grunt build - remove to end of file(.*(\n|\r))+\}$/m, '');
  383.  
  384. // see https://github.com/StylishThemes/GitHub-Dark/issues/275
  385. if (/firefox/i.test(navigator.userAgent)) {
  386. processed = processed
  387. // line in github-dark.css = "select, input:not(.btn-link), textarea"
  388. .replace('select, input:not(.btn-link)', 'input { color:#eee !important; } select')
  389. .replace(/input\[type=\"checkbox\"\][\s\S]+?}/gm, '');
  390. }
  391. data.processedCss = processed;
  392. fetchAndApplyTheme();
  393. }
  394.  
  395. function applyStyle(css) {
  396. if (debug) {
  397. console.log('Applying style', '"' + (css || '').match(regex) + '"');
  398. }
  399. $style.textContent = css || '';
  400. }
  401.  
  402. function addSavedStyle() {
  403. if (debug) {
  404. console.log('Adding previously saved style');
  405. }
  406. // apply already processed css to prevent FOUC
  407. $style.textContent = data.processedCss;
  408. }
  409.  
  410. function updateStyle() {
  411. isUpdating = true;
  412.  
  413. if (debug) {
  414. console.log('Updating user settings');
  415. }
  416.  
  417. let body = $('body'),
  418. panel = $('#ghd-settings-inner');
  419.  
  420. data.attach = $('.ghd-attach', panel).value;
  421. // get hex value directly
  422. data.color = picker.toHEXString();
  423. data.enable = $('.ghd-enable', panel).checked;
  424. data.font = $('.ghd-font', panel).value;
  425. data.image = $('.ghd-image', panel).value;
  426. data.tab = $('.ghd-tab', panel).value;
  427. data.theme = $('.ghd-theme', panel).value;
  428. data.type = $('.ghd-type', panel).value;
  429. data.wrap = $('.ghd-wrap', panel).checked;
  430.  
  431. data.enableCodeWrap = $('.ghd-codewrap-checkbox', panel).checked;
  432. data.enableMonospace = $('.ghd-monospace-checkbox', panel).checked;
  433.  
  434. data.modeDiffToggle = $('.ghd-diff-select', panel).value;
  435.  
  436. $style.disabled = !data.enable;
  437.  
  438. toggleClass(body, 'ghd-disabled', !data.enable);
  439. toggleClass(body, 'nowrap', !data.wrap);
  440.  
  441. if (testing) {
  442. processStyle();
  443. testing = false;
  444. } else {
  445. fetchAndApplyStyle();
  446. }
  447. isUpdating = false;
  448. }
  449.  
  450. // user can force GitHub-dark update
  451. function forceUpdate(css) {
  452. if (css) {
  453. // add raw css directly for style testing
  454. data.rawCss = css;
  455. processStyle();
  456. } else {
  457. // clear saved date
  458. data.version = 0;
  459. data.themeCss = '';
  460. GM_setValue('data', data);
  461. closePanel('forced');
  462. }
  463. }
  464.  
  465. function getVersionTooltip() {
  466. let indx,
  467. ver = [],
  468. // convert stored css version from "001014049" into "1.14.49" for tooltip
  469. parts = String(data.version).match(/\d{3}/g),
  470. len = parts && parts.length || 0;
  471. for (indx = 0; indx < len; indx++) {
  472. ver.push(parseInt(parts[indx], 10));
  473. }
  474. return `Script v${version}\nCSS ${(ver.length ? 'v' + ver.join('.') : 'unknown')}`;
  475. }
  476.  
  477. function buildSettings() {
  478. if (debug) {
  479. console.log('Adding settings panel & GitHub Dark link to profile dropdown');
  480. }
  481. // Script-specific CSS
  482. GM_addStyle(`
  483. #ghd-menu:hover { cursor:pointer }
  484. #ghd-settings { position:fixed; z-index:65535; top:0; bottom:0; left:0; right:0; opacity:0; visibility:hidden; }
  485. #ghd-settings.in { opacity:1; visibility:visible; background:rgba(0,0,0,.5); }
  486. #ghd-settings-inner { position:fixed; left:50%; top:50%; transform:translate(-50%,-50%); width:25rem; box-shadow:0 .5rem 1rem #111; color:#c0c0c0 }
  487. #ghd-settings label { margin-left:.5rem; position:relative; top:-1px }
  488. #ghd-settings-close { height:1rem; width:1rem; fill:#666; float:right; cursor:pointer }
  489. #ghd-settings-close:hover { fill:#ccc }
  490. #ghd-settings .ghd-right { float:right; padding:5px; }
  491. #ghd-settings p { line-height:22px; }
  492. #ghd-settings .form-select, #ghd-settings input[type="text"] { height:30px; min-height:30px; }
  493. #ghd-swatch { width:25px; height:22px; display:inline-block; margin:3px 10px; border-radius:4px; }
  494. #ghd-settings input, #ghd-settings select { border:#555 1px solid; }
  495. #ghd-settings .ghd-attach, #ghd-settings .ghd-diff-select { padding-right:25px; }
  496. #ghd-settings input[type="checkbox"] { margin-top:3px; width: 16px !important; height: 16px !important; border-radius: 3px !important; }
  497. #ghd-settings .boxed-group-inner { padding:0; }
  498. #ghd-settings .ghd-footer { padding:10px; border-top:#555 solid 1px; }
  499. #ghd-settings .ghd-settings-wrapper { max-height:60vh; overflow-y:auto; padding:4px 10px; }
  500. #ghd-settings .ghd-tab { width:5em; }
  501. #ghd-settings .octicon { vertical-align:text-bottom !important; }
  502. #ghd-settings .ghd-paste-area { position:absolute; bottom:50px; top:37px; left:2px; right:2px; width:396px !important; height:-moz-calc(100% - 85px);
  503. resize:none !important; border-style:solid; z-index:0; }
  504.  
  505. /* code wrap toggle: https://gist.github.com/silverwind/6c1701f56e62204cc42b
  506. icons next to a pre */
  507. .ghd-wrap-toggle { position:absolute; right:1.4em; margin-top:.2em; -moz-user-select:none; -webkit-user-select:none; cursor:pointer; z-index:20; }
  508. /* file & diff code tables */
  509. .ghd-wrap-table .blob-code-inner { white-space:pre-wrap !important; word-break:break-all !important; }
  510. .ghd-unwrap-table .blob-code-inner { white-space:pre !important; word-break:normal !important; }
  511. .ghd-wrap-toggle > *, .ghd-monospace > *, .ghd-file-toggle > * { pointer-events:none; vertical-align:middle !important; }
  512. /* icons inside a wrapper immediatly around a pre */
  513. .highlight > .ghd-wrap-toggle { right:.5em; top:.5em; margin-top:0; }
  514. /* icons for non-syntax highlighted code blocks; see https://github.com/gjtorikian/html-proofer/blob/master/README.md */
  515. .markdown-body:not(.comment-body) .ghd-wrap-toggle:not(:first-child) { right:3.4em; }
  516. .ghd-wrap-toggle svg { height:1.25em; width:1.25em; fill:rgba(110,110,110,.4); }
  517. /* wrap disabled (red) */
  518. .ghd-wrap-toggle.unwrap:hover svg, .ghd-wrap-toggle:hover svg { fill:#8b0000; }
  519. /* wrap enabled (green) */
  520. body:not(.nowrap) .ghd-wrap-toggle:not(.unwrap):hover svg, .ghd-wrap-toggle.wrapped:hover svg { fill:#006400; }
  521. .blob-wrapper, .markdown-body pre, .markdown-body .highlight { position:relative; }
  522. /* monospace font toggle */
  523. .ghd-monospace-font { font-family:"${data.font}", Menlo, Inconsolata, "Droid Mono", monospace !important; font-size:1em !important; }
  524. /* file collapsed icon */
  525. .ghd-file-collapsed > :not(.file-header) { display:none !important; }
  526. .ghd-file-collapsed .ghd-file-toggle svg { -webkit-transform:rotate(90deg); transform:rotate(90deg); }
  527. `);
  528.  
  529. let indx, theme, icon,
  530. opts = '',
  531. ver = getVersionTooltip(),
  532. names = Object.keys(themes),
  533. len = names.length;
  534. for (indx = 0; indx < len; indx++) {
  535. theme = names[indx];
  536. opts += `<option value="${theme}">${theme}</option>`;
  537. }
  538.  
  539. // circle-question-mark icon
  540. icon = `
  541. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" height="16" width="14" viewBox="0 0 16 14">
  542. <path d="M6 10h2v2H6V10z m4-3.5c0 2.14-2 2.5-2 2.5H6c0-0.55 0.45-1 1-1h0.5c0.28 0 0.5-0.22 0.5-0.5v-1c0-0.28-0.22-0.5-0.5-0.5h-1c-0.28 0-0.5 0.22-0.5 0.5v0.5H4c0-1.5 1.5-3 3-3s3 1 3 2.5zM7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z" />
  543. </svg>
  544. `;
  545.  
  546. // Settings panel markup
  547. make({
  548. el : 'div',
  549. appendTo: 'body',
  550. attr : { id: 'ghd-settings' },
  551. html : `
  552. <div id="ghd-settings-inner" class="boxed-group">
  553. <h3>GitHub-Dark Settings
  554. <a href="https://github.com/StylishThemes/GitHub-Dark-Script/wiki" class="tooltipped tooltipped-e" aria-label="See documentation">${icon}</a>
  555. <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>
  556. </h3>
  557. <div class="boxed-group-inner">
  558. <form>
  559. <div class="ghd-settings-wrapper">
  560. <p class="ghd-checkbox">
  561. <label>Enable GitHub-Dark<input class="ghd-enable ghd-right" type="checkbox"></label>
  562. </p>
  563. <p>
  564. <label>Color:</label>
  565. <input class="ghd-color ghd-right" type="text" value="#4183C4">
  566. <span id="ghd-swatch" class="ghd-right"></span>
  567. </p>
  568. <h4>Background</h4>
  569. <p>
  570. <label>Image:</label>
  571. <input class="ghd-image ghd-right" type="text">
  572. <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">${icon}</a>
  573. </p>
  574. <p>
  575. <label>Image type:</label>
  576. <select class="ghd-type ghd-right form-select">
  577. <option value="tiled">Tiled</option>
  578. <option value="fit">Fit window</option>
  579. </select>
  580. </p>
  581. <p>
  582. <label>Image attachment:</label>
  583. <select class="ghd-attach ghd-right form-select">
  584. <option value="scroll">Scroll</option>
  585. <option value="fixed">Fixed</option>
  586. </select>
  587. </p>
  588. <h4>Code</h4>
  589. <p><label>Theme:</label> <select class="ghd-theme ghd-right form-select">${opts}</select></p>
  590. <p>
  591. <label>Font Name:</label> <input class="ghd-font ghd-right" type="text">
  592. <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!">${icon}</a>
  593. </p>
  594. <p>
  595. <label>Tab Size:</label> <input class="ghd-tab ghd-right" type="text">
  596. </p>
  597. <p class="ghd-checkbox">
  598. <label>Wrap<input class="ghd-wrap ghd-right" type="checkbox"></label>
  599. </p>
  600. <h4>Toggles</h4>
  601. <p class="ghd-checkbox">
  602. <label>Code Wrap<input class="ghd-codewrap-checkbox ghd-right" type="checkbox"></label>
  603. </p>
  604. <p class="ghd-checkbox">
  605. <label>Comment Monospace Font<input class="ghd-monospace-checkbox ghd-right" type="checkbox"></label>
  606. </p>
  607. <p class="ghd-range">
  608. <label>Diff File Collapse</label>
  609. <select class="ghd-diff-select ghd-right form-select">
  610. <option value="0">Disabled</option>
  611. <option value="1">Enabled</option>
  612. <option value="2">Accordion</option>
  613. </select>
  614. </p>
  615. </div>
  616. <div class="ghd-footer">
  617. <div class="btn-group">
  618. <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>
  619. <a href="#" class="ghd-textarea-toggle btn btn-sm tooltipped tooltipped-n" aria-label="Paste CSS update">
  620. <svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 16 16" fill="#eee">
  621. <path d="M15 11 1 11 8 3z"/>
  622. </svg>
  623. </a>
  624. <div class="ghd-paste-area-content" aria-hidden="true" style="display:none">
  625. <textarea class="ghd-paste-area" placeholder="Paste GitHub-Dark Style here!"></textarea>
  626. </div>
  627. </div>&nbsp;
  628. <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>
  629. <span class="ghd-versions ghd-right tooltipped tooltipped-n" aria-label="${ver}">
  630. <svg class="ghd-info" xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 24 24">
  631. <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"/>
  632. </svg>
  633. </span>
  634. </div>
  635. </form>
  636. </div>
  637. </div>
  638. `
  639. });
  640.  
  641. updateToggles();
  642. }
  643.  
  644. // Add code wrap toggle
  645. function buildCodeWrap() {
  646. // mutation events happen quick, so we still add an update flag
  647. isUpdating = true;
  648. let icon = make({
  649. el : 'div',
  650. cl4ss : 'ghd-wrap-toggle tooltipped tooltipped-w',
  651. attr : { 'aria-label' : 'Toggle code wrap' },
  652. html : wrapIcon
  653. });
  654. $$('.blob-wrapper').forEach(el => {
  655. el.insertBefore(icon.cloneNode(true), el.childNodes[0]);
  656. });
  657. $$('.markdown-body pre').forEach(el => {
  658. el.parentNode.insertBefore(icon.cloneNode(true), el);
  659. });
  660. isUpdating = false;
  661. }
  662.  
  663. // Add monospace font toggle
  664. function addMonospaceToggle() {
  665. isUpdating = true;
  666. let button = make({
  667. el : 'button',
  668. cl4ss : 'ghd-monospace toolbar-item tooltipped tooltipped-n',
  669. attr : {
  670. 'type' : 'button',
  671. 'aria-label' : 'Toggle monospaced font',
  672. 'tabindex' : '-1'
  673. },
  674. html : monospaceIcon
  675. });
  676. $$('.toolbar-commenting').forEach(el => {
  677. if (!$('.ghd-monospace', el)) {
  678. // prepend
  679. el.insertBefore(button.cloneNode(true), el.childNodes[0]);
  680. }
  681. });
  682. isUpdating = false;
  683. }
  684.  
  685. // Add file diffs toggle
  686. function addFileToggle() {
  687. isUpdating = true;
  688. let firstButton,
  689. button = make({
  690. el : 'button',
  691. cl4ss : 'ghd-file-toggle btn btn-sm tooltipped tooltipped-n',
  692. attr : {
  693. 'type' : 'button',
  694. 'aria-label' : 'Click to Expand or Collapse file',
  695. 'tabindex' : '-1'
  696. },
  697. html : fileIcon
  698. });
  699. $$('#files .file-actions').forEach(el => {
  700. if (!$('.ghd-file-toggle', el)) {
  701. el.appendChild(button.cloneNode(true));
  702. }
  703. });
  704. firstButton = $('.ghd-file-toggle');
  705. // accordion mode = start with all but first entry collapsed
  706. if (firstButton && data.modeDiffToggle === '2') {
  707. toggleFile({
  708. target: firstButton
  709. }, true);
  710. }
  711. isUpdating = false;
  712. }
  713.  
  714. // Add toggle buttons after page updates
  715. function updateToggles() {
  716. if (data.enableCodeWrap) {
  717. buildCodeWrap();
  718. } else {
  719. removeAll('.ghd-wrap-toggle');
  720. toggleClass($$('.ghd-file-collapsed'), 'ghd-file-collapsed', false);
  721. }
  722. if (data.enableMonospace) {
  723. addMonospaceToggle();
  724. } else {
  725. removeAll('.ghd-monospace');
  726. toggleClass($$('.ghd-monospace-font'), 'ghd-monospace-font', false);
  727. }
  728. if (data.modeDiffToggle !== '0') {
  729. addFileToggle();
  730. } else {
  731. removeAll('.ghd-file-toggle');
  732. toggleClass($$('.ghd-file-collapsed'), 'ghd-file-collapsed', false);
  733. }
  734. }
  735.  
  736. function makeRow(vals, str) {
  737. return make({
  738. el : 'tr',
  739. cl4ss : 'ghd-shortcut',
  740. html : `<td class="keys"><kbd>${vals[0]}</kbd> <kbd>${vals[1]}</kbd></td><td>${str}</td>`
  741. });
  742. }
  743.  
  744. // add keyboard shortcut to help menu (press "?")
  745. function buildShortcut() {
  746. let row,
  747. el = $('.keyboard-mappings tbody');
  748. if (el && !$('.ghd-shortcut')) {
  749. row = makeRow(keyboardOpen.split('+'), 'GitHub-Dark: open settings');
  750. el.appendChild(row);
  751. row = makeRow(keyboardToggle.split('+'), 'GitHub-Dark: toggle style');
  752. el.appendChild(row);
  753. }
  754. }
  755.  
  756. function toggleCodeWrap(el) {
  757. let css,
  758. overallWrap = data.wrap,
  759. code = next(el, '.highlight, .diff-table, code, pre'),
  760. tmp = code ? $('code', code) : '';
  761. if (tmp) {
  762. // find code element
  763. code = tmp;
  764. }
  765. if (!code) {
  766. if (debug) {
  767. console.log('Code wrap icon associated code not found', el);
  768. }
  769. return;
  770. }
  771. // code with line numbers
  772. if (code.nodeName === 'TABLE') {
  773. if (code.className.indexOf('ghd-') < 0) {
  774. css = !overallWrap;
  775. } else {
  776. css = code.classList.contains('ghd-unwrap-table');
  777. }
  778. toggleClass(code, 'ghd-wrap-table', css);
  779. toggleClass(code, 'ghd-unwrap-table', !css);
  780. toggleClass(el, 'wrapped', css);
  781. toggleClass(el, 'unwrap', !css);
  782. } else {
  783. css = (code.getAttribute('style') || '').trim();
  784. if (css === '') {
  785. css = wrapCss[overallWrap ? 'unwrap' : 'wrapped'];
  786. } else {
  787. css = wrapCss[css === wrapCss.wrapped ? 'unwrap' : 'wrapped'];
  788. }
  789. code.setAttribute('style', css);
  790. toggleClass(el, 'wrapped', css === wrapCss.wrapped);
  791. toggleClass(el, 'unwrap', css === wrapCss.unwrap);
  792. }
  793. }
  794.  
  795. function toggleMonospace(el) {
  796. let tmp = closest(el, '.previewable-comment-form'),
  797. // single comment
  798. textarea = $('.comment-form-textarea', tmp);
  799. if (textarea) {
  800. toggleClass(textarea, 'ghd-monospace-font');
  801. textarea.focus();
  802. tmp = textarea.classList.contains('ghd-monospace-font');
  803. toggleClass(el, 'ghd-icon-active', tmp);
  804. }
  805. }
  806.  
  807. function toggleSibs(target, state) {
  808. let el,
  809. isCollapsed = state || target.classList.contains('ghd-file-collapsed'),
  810. toggles = document.querySelectorAll('.file'),
  811. indx = toggles.length;
  812. while (indx--) {
  813. el = toggles[indx];
  814. if (el !== target) {
  815. el.classList[isCollapsed ? 'add' : 'remove']('ghd-file-collapsed');
  816. }
  817. }
  818. }
  819.  
  820. function toggleFile(event, init) {
  821. isUpdating = true;
  822. let el = closest(event.target, '.file');
  823. if (data.modeDiffToggle === '2') {
  824. if (!init) {
  825. el.classList.toggle('ghd-file-collapsed');
  826. }
  827. toggleSibs(el, true);
  828. } else {
  829. el.classList.toggle('ghd-file-collapsed');
  830. // shift+click toggle all files!
  831. if (event.shiftKey) {
  832. toggleSibs(el);
  833. }
  834. }
  835. isUpdating = false;
  836. }
  837.  
  838. function bindEvents() {
  839. let el, menu, lastKey,
  840. panel = $('#ghd-settings-inner'),
  841. swatch = $('#ghd-swatch', panel);
  842.  
  843. // finish initialization
  844. $('#ghd-settings-inner .ghd-enable').checked = data.enable;
  845. toggleClass($('body'), 'ghd-disabled', !data.enable);
  846.  
  847. // Create our menu entry
  848. menu = make({
  849. el : 'a',
  850. cl4ss : 'dropdown-item',
  851. html : 'GitHub Dark Settings',
  852. attr : { id : 'ghd-menu' }
  853. });
  854.  
  855. el = $$('.header .dropdown-item[href="/settings/profile"], .header .dropdown-item[data-ga-click*="go to profile"]');
  856. // get last found item - gists only have the "go to profile" item; GitHub has both
  857. el = el[el.length - 1];
  858. if (el) {
  859. // insert after
  860. el.parentNode.insertBefore(menu, el.nextSibling);
  861. on($('#ghd-menu'), 'click', () => {
  862. openPanel();
  863. });
  864. }
  865.  
  866. on(document, 'keypress keydown', event => {
  867. clearTimeout(timer);
  868. // use "g+o" to open up ghd options panel
  869. let openKeys = keyboardOpen.split('+'),
  870. toggleKeys = keyboardToggle.split('+'),
  871. key = String.fromCharCode(event.which).toLowerCase(),
  872. panelVisible = $('#ghd-settings').classList.contains('in');
  873.  
  874. // press escape to close the panel
  875. if (event.which === 27 && panelVisible) {
  876. closePanel();
  877. return;
  878. }
  879. // use event.which from keypress for shortcuts
  880. // prevent opening panel while typing "go" in comments
  881. if (event.type === 'keydown' || /(input|textarea)/i.test(document.activeElement.nodeName)) {
  882. return;
  883. }
  884. if (lastKey === openKeys[0] && key === openKeys[1]) {
  885. if (panelVisible) {
  886. closePanel();
  887. } else {
  888. openPanel();
  889. }
  890. }
  891. if (lastKey === toggleKeys[0] && key === toggleKeys[1]) {
  892. toggleStyle();
  893. }
  894. lastKey = key;
  895. timer = setTimeout(() => {
  896. lastKey = null;
  897. }, keyboardDelay);
  898.  
  899. // add shortcut to help menu
  900. if (key === '?') {
  901. // table doesn't exist until user presses "?"
  902. setTimeout(() => {
  903. buildShortcut();
  904. }, 300);
  905. }
  906. });
  907.  
  908. // add ghd-settings panel bindings
  909. on($$('#ghd-settings, #ghd-settings-close'), 'click keyup', event => {
  910. // press escape to close settings
  911. if (event.type === 'keyup' && event.which !== 27) {
  912. return;
  913. }
  914. closePanel();
  915. });
  916.  
  917. on(panel, 'click', event => {
  918. event.stopPropagation();
  919. });
  920.  
  921. on($('.ghd-reset', panel), 'click', event => {
  922. event.preventDefault();
  923. isUpdating = true;
  924. // pass true to reset values
  925. setStoredValues(true);
  926. // add reset values back to data
  927. getStoredValues();
  928. // add reset values to panel
  929. updatePanel();
  930. // update style
  931. updateStyle();
  932. });
  933.  
  934. on($$('input[type="text"]', panel), 'focus', function() {
  935. // select all text when focused
  936. this.select();
  937. });
  938.  
  939. on($$('select, input', panel), 'change', () => {
  940. if (!isUpdating) {
  941. updateStyle();
  942. }
  943. });
  944.  
  945. on($('.ghd-update', panel), 'click', event => {
  946. event.preventDefault();
  947. forceUpdate();
  948. });
  949.  
  950. on($('.ghd-textarea-toggle', panel), 'click', function(event) {
  951. event.preventDefault();
  952. let hidden, el;
  953. this.classList.remove('selected');
  954. el = next(this, '.ghd-paste-area-content');
  955. if (el) {
  956. hidden = el.style.display === 'none';
  957. el.style.display = hidden ? '' : 'none';
  958. if (el.style.display !== 'none') {
  959. el.classList.add('selected');
  960. el = $('textarea', el);
  961. el.focus();
  962. el.select();
  963. }
  964. }
  965. return false;
  966. });
  967.  
  968. on($('.ghd-paste-area-content', panel), 'paste', event => {
  969. let toggle = $('.ghd-textarea-toggle', panel),
  970. textarea = event.target;
  971. setTimeout(() => {
  972. textarea.parentNode.style.display = 'none';
  973. toggle.classList.remove('selected');
  974. testing = true;
  975. forceUpdate(textarea.value);
  976. }, 200);
  977. });
  978.  
  979. // Toggles
  980. on($('body'), 'click', event => {
  981. let target = event.target;
  982. if (data.enableCodeWrap && target.classList.contains('ghd-wrap-toggle')) {
  983. // **** CODE WRAP TOGGLE ****
  984. event.stopPropagation();
  985. toggleCodeWrap(target);
  986. } else if (data.enableMonospace && target.classList.contains('ghd-monospace')) {
  987. // **** MONOSPACE FONT TOGGLE ****
  988. event.stopPropagation();
  989. toggleMonospace(target);
  990. return false;
  991. } else if (data.modeDiffToggle !== '0' && target.classList.contains('ghd-file-toggle')) {
  992. // **** CODE DIFF COLLAPSE TOGGLE ****
  993. event.stopPropagation();
  994. toggleFile(event);
  995. }
  996. });
  997.  
  998. // style color picker
  999. picker = new jscolor($('.ghd-color', panel));
  1000. picker.zIndex = 65536;
  1001. picker.hash = true;
  1002. picker.backgroundColor = '#333';
  1003. picker.padding = 0;
  1004. picker.borderWidth = 0;
  1005. picker.borderColor = '#444';
  1006. picker.onFineChange = () => {
  1007. swatch.style.backgroundColor = '#' + picker;
  1008. };
  1009. }
  1010.  
  1011. function openPanel() {
  1012. $('.modal-backdrop').click();
  1013. updatePanel();
  1014. $('#ghd-settings').classList.add('in');
  1015. }
  1016.  
  1017. function closePanel(flag) {
  1018. $('#ghd-settings').classList.remove('in');
  1019. picker.hide();
  1020.  
  1021. if (flag === 'forced') {
  1022. // forced update; partial re-initialization
  1023. init();
  1024. } else {
  1025. // apply changes when the panel is closed
  1026. updateStyle();
  1027. }
  1028. }
  1029.  
  1030. function toggleStyle() {
  1031. let isEnabled = !data.enable;
  1032. data.enable = isEnabled;
  1033. $('#ghd-settings-inner .ghd-enable').checked = isEnabled;
  1034. // add processedCss back into style (emptied when disabled)
  1035. if (isEnabled) {
  1036. // data.processedCss is empty when ghd is disabled on init
  1037. if (!data.processedCss) {
  1038. processStyle();
  1039. } else {
  1040. addSavedStyle();
  1041. }
  1042. }
  1043. $style.disabled = !isEnabled;
  1044. }
  1045.  
  1046. function init() {
  1047. if ($('body')) {
  1048. $('body').appendChild($style);
  1049. getStoredValues(true);
  1050.  
  1051. $style.disabled = !data.enable;
  1052. data.lastTheme = data.theme;
  1053. data.lastCW = data.enableCodeWrap;
  1054. data.lastMS = data.enableMonospace;
  1055. data.lastDT = data.modeDiffToggle;
  1056.  
  1057. // only load package.json once a day, or after a forced update
  1058. if ((new Date().getTime() > data.date + delay) || data.version === 0) {
  1059. // get package.json from GitHub-Dark & compare versions
  1060. // load new script if a newer one is available
  1061. checkVersion();
  1062. } else {
  1063. addSavedStyle();
  1064. }
  1065. isInitialized = false;
  1066. }
  1067. }
  1068.  
  1069. // add style at document-start
  1070. init();
  1071.  
  1072. on(document, 'DOMContentLoaded', () => {
  1073. if (isInitialized === 'pending') {
  1074. // init after DOM loaded on .atom pages
  1075. init();
  1076. }
  1077. // add panel even if you're not logged in - open panel using keyboard shortcut
  1078. // just not on githubusercontent pages (no settings panel needed)
  1079. if (window.location.host.indexOf('githubusercontent.com') < 0) {
  1080. buildSettings();
  1081. // add event binding on document ready
  1082. bindEvents();
  1083.  
  1084. $$('#js-repo-pjax-container, #js-pjax-container, .js-contribution-activity').forEach(target => {
  1085. new MutationObserver(mutations => {
  1086. mutations.forEach(mutation => {
  1087. // preform checks before adding code wrap to minimize function calls
  1088. if (!(isUpdating || $$('.ghd-wrap-toggle').length) &&
  1089. mutation.target === target) {
  1090. updateToggles();
  1091. }
  1092. });
  1093. }).observe(target, {
  1094. childList: true,
  1095. subtree: true
  1096. });
  1097. });
  1098. }
  1099.  
  1100. isInitialized = true;
  1101. });
  1102.  
  1103. /* utility functions */
  1104. function isBool(name) {
  1105. let val = data[name];
  1106. return typeof val === 'boolean' ? val : defaults[name];
  1107. }
  1108. function $(str, el) {
  1109. return (el || document).querySelector(str);
  1110. }
  1111. function $$(str, el) {
  1112. return Array.from((el || document).querySelectorAll(str));
  1113. }
  1114. function next(el, selector) {
  1115. while ((el = el.nextElementSibling)) {
  1116. if (el && el.matches(selector)) {
  1117. return el;
  1118. }
  1119. }
  1120. return null;
  1121. }
  1122. function closest(el, selector) {
  1123. while (el && el.nodeName !== 'BODY' && !el.matches(selector)) {
  1124. el = el.parentNode;
  1125. }
  1126. return el && el.matches(selector) ? el : [];
  1127. }
  1128. function make(obj) {
  1129. let key,
  1130. el = document.createElement(obj.el);
  1131. if (obj.cl4ss) { el.className = obj.cl4ss; }
  1132. if (obj.html) { el.innerHTML = obj.html; }
  1133. if (obj.attr) {
  1134. for (key in obj.attr) {
  1135. if (obj.attr.hasOwnProperty(key)) {
  1136. el.setAttribute(key, obj.attr[key]);
  1137. }
  1138. }
  1139. }
  1140. if (obj.appendTo) {
  1141. $(obj.appendTo).appendChild(el);
  1142. }
  1143. return el;
  1144. }
  1145. function removeAll(selector) {
  1146. $$(selector).forEach(el => {
  1147. el.parentNode.removeChild(el);
  1148. });
  1149. }
  1150. function on(els, name, callback) {
  1151. els = Array.isArray(els) ? els : [els];
  1152. let events = name.split(/\s+/);
  1153. els.forEach(el => {
  1154. events.forEach(ev => {
  1155. el.addEventListener(ev, callback);
  1156. });
  1157. });
  1158. }
  1159. function toggleClass(els, cl4ss, flag) {
  1160. els = Array.isArray(els) ? els : [els];
  1161. els.forEach(el => {
  1162. if (el) {
  1163. if (typeof flag === 'undefined') {
  1164. flag = !el.classList.contains(cl4ss);
  1165. }
  1166. if (flag) {
  1167. el.classList.add(cl4ss);
  1168. } else {
  1169. el.classList.remove(cl4ss);
  1170. }
  1171. }
  1172. });
  1173. }
  1174.  
  1175. // Add GM options
  1176. GM_registerMenuCommand("GitHub Dark Script debug logging", () => {
  1177. let val = prompt('Toggle GitHub Dark Script debug log (true/false):', !debug);
  1178. if (val) {
  1179. debug = /^t/.test(val);
  1180. GM_setValue('debug', debug);
  1181. }
  1182. });
  1183.  
  1184. })();