GitHub Dark Script

GitHub Dark in userscript form, with a settings panel

As of 2016-07-16. See the latest version.

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