GitHub Code Colors

A userscript that adds a color swatch next to the code color definition

  1. // ==UserScript==
  2. // @name GitHub Code Colors
  3. // @version 2.0.9
  4. // @description A userscript that adds a color swatch next to the code color definition
  5. // @license MIT
  6. // @author Rob Garrison
  7. // @namespace https://github.com/Mottie
  8. // @match https://github.com/*
  9. // @match https://gist.github.com/*
  10. // @run-at document-idle
  11. // @grant GM.addStyle
  12. // @grant GM_addStyle
  13. // @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js?updated=20180103
  14. // @require https://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=1108163
  15. // @require https://greasyfork.org/scripts/387811-color-bundle/code/color-bundle.js?version=719499
  16. // @icon https://github.githubassets.com/pinned-octocat.svg
  17. // @supportURL https://github.com/Mottie/GitHub-userscripts/issues
  18. // ==/UserScript==
  19.  
  20. /* global Color */
  21. (() => {
  22. "use strict";
  23.  
  24. // whitespace:initial => overrides code-wrap css in content
  25. GM.addStyle(`
  26. .ghcc-block { width:14px; height:14px; display:inline-block;
  27. vertical-align:middle; margin-right:4px; border-radius:4px;
  28. border:1px solid rgba(119, 119, 119, 0.5); position:relative;
  29. background-image:none; cursor:pointer; }
  30. .ghcc-popup { position:absolute; background:#222; color:#eee;
  31. min-width:350px; top:100%; left:0px; padding:10px; z-index:100;
  32. white-space:pre; cursor:text; text-align:left; -webkit-user-select:text;
  33. -moz-user-select:text; -ms-user-select:text; user-select:text; }
  34. .markdown-body .highlight pre, .markdown-body pre {
  35. overflow-y:visible !important; }
  36. .ghcc-copy { padding:2px 6px; margin-right:4px; background:transparent;
  37. border:0; }`);
  38.  
  39. const namedColors = Object.keys(Color.namedColors);
  40. const namedColorsList = namedColors.reduce((acc, name) => {
  41. acc[name] = `rgb(${Color.namedColors[name].join(", ")})`;
  42. return acc;
  43. }, {});
  44.  
  45. const copyButton = document.createElement("clipboard-copy");
  46. copyButton.className = "btn btn-sm btn-blue tooltipped tooltipped-w ghcc-copy";
  47. copyButton.setAttribute("aria-label", "Copy to clipboard");
  48. // This hint isn't working yet (GitHub needs to fix it)
  49. copyButton.setAttribute("data-copied-hint", "Copied!");
  50. copyButton.innerHTML = `
  51. <svg aria-hidden="true" class="octicon octicon-clippy" height="14" viewBox="0 0 14 16" width="14">
  52. <path fill-rule="evenodd" d="M2 13h4v1H2v-1zm5-6H2v1h5V7zm2 3V8l-3 3 3 3v-2h5v-2H9zM4.5 9H2v1h2.5V9zM2 12h2.5v-1H2v1zm9 1h1v2c-.02.28-.11.52-.3.7-.19.18-.42.28-.7.3H1c-.55 0-1-.45-1-1V4c0-.55.45-1 1-1h3c0-1.11.89-2 2-2 1.11 0 2 .89 2 2h3c.55 0 1 .45 1 1v5h-1V6H1v9h10v-2zM2 5h8c0-.55-.45-1-1-1H8c-.55 0-1-.45-1-1s-.45-1-1-1-1 .45-1 1-.45 1-1 1H3c-.55 0-1 .45-1 1z"></path>
  53. </svg>`;
  54.  
  55. // Misc regex
  56. const regex = {
  57. quotes: /['"]/g,
  58. unix: /^0x/,
  59. percent: /%%/g
  60. };
  61.  
  62. // Don't use a div, because GitHub-Dark adds a :hover background
  63. // color definition on divs
  64. const block = document.createElement("button");
  65. block.className = "ghcc-block";
  66. block.tabIndex = 0;
  67. // prevent submitting on click in comment preview
  68. block.type = "button";
  69. block.onclick = "event => event.stopPropagation()";
  70.  
  71. const br = document.createElement("br");
  72.  
  73. const popup = document.createElement("span");
  74. popup.className = "ghcc-popup";
  75.  
  76. const formats = {
  77. named: {
  78. regex: new RegExp("^(" + namedColors.join("|") + ")$", "i"),
  79. convert: color => {
  80. const rgb = color.rgb().toString();
  81. if (Object.values(namedColorsList).includes(rgb)) {
  82. // There may be more than one named color
  83. // e.g. "slategray" & "slategrey"
  84. return Object.keys(namedColorsList)
  85. .filter(n => namedColorsList[n] === rgb)
  86. .join("<br />");
  87. }
  88. return "";
  89. },
  90. },
  91. hex: {
  92. // Ex: #123, #123456 or 0x123456 (unix style colors, used by three.js)
  93. regex: /^(#|0x)([0-9A-F]{6,8}|[0-9A-F]{3,4})$/i,
  94. convert: color => `${color.hex().toString()}`,
  95. },
  96. rgb: {
  97. regex: /^rgba?(\([^\)]+\))?/i,
  98. regexAlpha: /rgba/i,
  99. find: (els, el, txt) => {
  100. // Color in a string contains everything
  101. if (el.classList.contains("pl-s")) {
  102. txt = txt.match(formats.rgb.regex)[0];
  103. } else {
  104. // Rgb(a) colors contained in multiple "pl-c1" spans
  105. let indx = formats.rgb.regexAlpha.test(txt) ? 4 : 3;
  106. const tmp = [];
  107. while (indx) {
  108. tmp.push(getTextContent(els.shift()));
  109. indx--;
  110. }
  111. txt += "(" + tmp.join(",") + ")";
  112. }
  113. addNode(el, txt);
  114. return els;
  115. },
  116. convert: color => {
  117. const rgb = color.rgb().alpha(1).toString();
  118. const rgba = color.rgb().toString();
  119. return `${rgb}${rgb === rgba ? "" : "; " + rgba}`;
  120. }
  121. },
  122. hsl: {
  123. // Ex: hsl(0,0%,0%) or hsla(0,0%,0%,0.2);
  124. regex: /^hsla?(\([^\)]+\))?/i,
  125. find: (els, el, txt) => {
  126. const tmp = /a$/i.test(txt);
  127. if (el.classList.contains("pl-s")) {
  128. // Color in a string contains everything
  129. txt = txt.match(formats.hsl.regex)[0];
  130. } else {
  131. // Traverse this HTML... & els only contains the pl-c1 nodes
  132. // <span class="pl-c1">hsl</span>(<span class="pl-c1">1</span>,
  133. // <span class="pl-c1">1</span><span class="pl-k">%</span>,
  134. // <span class="pl-c1">1</span><span class="pl-k">%</span>);
  135. // using getTextContent in case of invalid css
  136. txt = txt + "(" + getTextContent(els.shift()) + "," +
  137. getTextContent(els.shift()) + "%," +
  138. // Hsla needs one more parameter
  139. getTextContent(els.shift()) + "%" +
  140. (tmp ? "," + getTextContent(els.shift()) : "") + ")";
  141. }
  142. // Sometimes (previews only?) the .pl-k span is nested inside
  143. // the .pl-c1 span, so we end up with "%%"
  144. addNode(el, txt.replace(regex.percent, "%"));
  145. return els;
  146. },
  147. convert: color => {
  148. const hsl = color.hsl().alpha(1).round().toString();
  149. const hsla = color.hsl().round().toString();
  150. return `${hsl}${hsl === hsla ? "" : "; " + hsla}`;
  151. }
  152. },
  153. hwb: {
  154. convert: color => color.hwb().round().toString()
  155. },
  156. cymk: {
  157. convert: color => {
  158. const cmyk = color.cmyk().round().array(); // array of numbers
  159. return `device-cmyk(${cmyk.shift()}, ${cmyk.join("%, ")})`;
  160. }
  161. },
  162. };
  163.  
  164. function showPopup(el) {
  165. const popup = createPopup(el.style.backgroundColor);
  166. el.appendChild(popup);
  167. }
  168.  
  169. function hidePopup(el) {
  170. el.textContent = "";
  171. }
  172.  
  173. function checkPopup(event) {
  174. const el = event.target;
  175. if (el && el.classList.contains("ghcc-block")) {
  176. if (event.type === "click") {
  177. if (el.textContent) {
  178. hidePopup(el)
  179. } else {
  180. showPopup(el);
  181. }
  182. }
  183. }
  184. if (event.type === "keyup" && event.key === "Escape") {
  185. // hide all popups
  186. [...document.querySelectorAll(".ghcc-block")].forEach(el => {
  187. el.textContent = "";
  188. });
  189. }
  190. }
  191.  
  192. function createPopup(val) {
  193. const color = Color(val);
  194. const el = popup.cloneNode();
  195. const fragment = document.createDocumentFragment();
  196. Object.keys(formats).forEach(type => {
  197. if (typeof formats[type].convert === "function") {
  198. const val = formats[type].convert(color);
  199. if (val) {
  200. const button = copyButton.cloneNode(true);
  201. button.value = val;
  202. fragment.appendChild(button);
  203. fragment.appendChild(document.createTextNode(val));
  204. fragment.appendChild(br.cloneNode());
  205. }
  206. }
  207. });
  208. el.appendChild(fragment);
  209. return el;
  210. }
  211.  
  212. function addNode(el, val) {
  213. const node = block.cloneNode();
  214. node.style.backgroundColor = val;
  215. // Don't add node if color is invalid
  216. if (node.style.backgroundColor !== "") {
  217. el.insertBefore(node, el.childNodes[0]);
  218. }
  219. }
  220.  
  221. function getTextContent(el) {
  222. return el ? el.textContent : "";
  223. }
  224.  
  225. // Loop with delay to allow user interaction
  226. function* addBlock(els) {
  227. let last = "";
  228. while (els.length) {
  229. let el = els.shift();
  230. let txt = el.textContent;
  231. if (
  232. // No swatch for JavaScript Math.tan
  233. last === "Math" ||
  234. // Ignore nested pl-c1 (see https://git.io/fNF3N)
  235. el.parentNode && el.parentNode.classList.contains("pl-c1")
  236. ) {
  237. // noop
  238. } else if (!el.querySelector(".ghcc-block")) {
  239. if (el.classList.contains("pl-s")) {
  240. txt = txt.replace(regex.quotes, "");
  241. }
  242. if (formats.hex.regex.test(txt) || formats.named.regex.test(txt)) {
  243. addNode(el, txt.replace(regex.unix, "#"));
  244. } else if (formats.rgb.regex.test(txt)) {
  245. els = formats.rgb.find(els, el, txt);
  246. } else if (formats.hsl.regex.test(txt)) {
  247. els = formats.hsl.find(els, el, txt);
  248. }
  249. }
  250. last = txt;
  251. yield els;
  252. }
  253. }
  254.  
  255. function addColors() {
  256. if (document.querySelector(".highlight")) {
  257. let status;
  258. // .pl-c1 targets css hex colors, "rgb" and "hsl"
  259. const els = [...document.querySelectorAll(".pl-c1, .pl-s, .pl-en, .pl-pds")];
  260. const iter = addBlock(els);
  261. const loop = () => {
  262. for (let i = 0; i < 40; i++) {
  263. status = iter.next();
  264. }
  265. if (!status.done) {
  266. requestAnimationFrame(loop);
  267. }
  268. };
  269. loop();
  270. }
  271. }
  272.  
  273. document.addEventListener("ghmo:container", addColors);
  274. document.addEventListener("ghmo:preview", addColors);
  275. document.addEventListener("click", checkPopup);
  276. document.addEventListener("keyup", checkPopup);
  277. addColors();
  278.  
  279. })();