GitHub Code Colors

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

目前為 2019-07-24 提交的版本,檢視 最新版本

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