Greasy Fork 还支持 简体中文。

GitHub Code Colors

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

目前為 2021-01-31 提交的版本,檢視 最新版本

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