GitHub Image Preview

A userscript that adds clickable image thumbnails

当前为 2016-09-17 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name GitHub Image Preview
  3. // @version 1.1.1
  4. // @description A userscript that adds clickable image thumbnails
  5. // @license https://creativecommons.org/licenses/by-sa/4.0/
  6. // @namespace https://github.com/Mottie
  7. // @include https://github.com/*
  8. // @run-at document-idle
  9. // @grant GM_addStyle
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @grant GM_xmlhttpRequest
  13. // @connect github.com
  14. // @connect githubusercontent.com
  15. // @author Rob Garrison
  16. // ==/UserScript==
  17. /* global GM_addStyle, GM_getValue, GM_setValue, GM_xmlhttpRequest */
  18. /* jshint unused:true, esnext:true */
  19. (() => {
  20. "use strict";
  21.  
  22. GM_addStyle(`
  23. table.files tr.ghip-image-previews,
  24. table.files.ghip-show-previews tbody tr.js-navigation-item {
  25. display:none; }
  26. table.files.ghip-show-previews tr.ghip-image-previews { display:table-row; }
  27. table.files.ghip-show-previews .ghip-non-image {
  28. height:80px; margin-top:15px; opacity:.2; }
  29. table.files.ghip-show-previews .image { position:relative; overflow:hidden;
  30. text-align:center; }
  31. .ghip-image-previews .image { padding:10px; }
  32. table.files.ghip-tiled .image { width:21.9%; }
  33. table.files.ghip-tiled .image .border-wrap img,
  34. .ghip-image-previews .border-wrap svg { max-height:130px; }
  35. table.files.ghip-fullw .image { width:97%; height:auto; }
  36. /* zoom doesn't work in Firefox, but "-moz-transform:scale(3);"
  37. doesn't limit the size of the image, so it overflows */
  38. table.files.ghip-tiled .image:hover img:not(.ghip-non-image) { zoom:3; }
  39. .ghip-image-previews .border-wrap img,
  40. .ghip-image-previews .border-wrap svg { max-width:95%; }
  41. .ghip-image-previews .border-wrap h4 { white-space:nowrap;
  42. text-overflow:ellipsis; margin-bottom:5px; }
  43. .ghip-image-previews .border-wrap h4.ghip-file-name { overflow:hidden; }
  44. .btn.ghip-tiled > *, .btn.ghip-fullw > *, .ghip-image-previews iframe {
  45. pointer-events:none; vertical-align:baseline; }
  46. .image .ghip-file-type { font-size:30px; top:-1.8em; position:relative;
  47. z-index:2; }
  48. .ghip-content span.exploregrid-item .ghip-file-name { cursor:default; }
  49. /* override GitHub-Dark styles */
  50. table.files img[src*='octocat-spinner'], img[src='/images/spinner.gif'] {
  51. width:auto !important; height:auto !important; }
  52. table.files td .simplified-path { color:#888 !important; }
  53. `);
  54.  
  55. // timer needed for file list to update?
  56. let timer,
  57. busy = false;
  58.  
  59. // supported img types
  60. const imgExt = /(png|jpg|jpeg|gif|tif|tiff|bmp|webp)$/i,
  61. svgExt = /svg$/i,
  62.  
  63. tiled = `
  64. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 16 16">
  65. <path d="M0 0h7v7H0zM9 9h7v7H9zM9 0h7v7H9zM0 9h7v7H0z"/>
  66. </svg>
  67. `,
  68. fullWidth = `
  69. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 16 16">
  70. <path d="M0 0h16v7H0zM0 9h16v7H0z"/>
  71. </svg>
  72. `,
  73. imgTemplate = [
  74. // not using backticks here
  75. "<a href='${url}' class='exploregrid-item image js-navigation-open' rel='nofollow'>",
  76. "<span class='border-wrap'>${image}</span>",
  77. "</a>"
  78. ].join(""),
  79. spanTemplate = [
  80. "<span class='exploregrid-item image'>",
  81. "<span class='border-wrap'>${image}</span>",
  82. "</span>"
  83. ].join("");
  84.  
  85. function addToggles() {
  86. if ($(".gh-img-preview")) {
  87. return;
  88. }
  89. busy = true;
  90. const div = document.createElement("div"),
  91. btn = `btn btn-sm BtnGroup-item tooltipped tooltipped-n" aria-label="Show`;
  92. div.className = "BtnGroup float-right gh-img-preview";
  93. div.innerHTML = `
  94. <div class="ghip-tiled ${btn} tiled files with image preview">${tiled}</div>
  95. <div class="ghip-fullw ${btn} full width files with image preview">${fullWidth}</div>
  96. `;
  97. $(".file-navigation").appendChild(div);
  98.  
  99. $(".ghip-tiled", div).addEventListener("click", () => {
  100. openView("tiled");
  101. });
  102. $(".ghip-fullw", div).addEventListener("click", () => {
  103. openView("fullw");
  104. });
  105. busy = false;
  106. }
  107.  
  108. function setInitState() {
  109. const view = GM_getValue("gh-image-preview");
  110. if (view) {
  111. openView(view);
  112. }
  113. }
  114.  
  115. function openView(name) {
  116. const el = $(".ghip-" + name);
  117. if (el) {
  118. el.classList.toggle("selected");
  119. if (el.classList.contains("selected")) {
  120. GM_setValue("gh-image-preview", name);
  121. showPreview(name);
  122. } else {
  123. GM_setValue("gh-image-preview", "");
  124. showList();
  125. }
  126. }
  127. }
  128.  
  129. function showPreview(size) {
  130. buildPreviews();
  131. const table = $("table.files"),
  132. btn1 = "ghip-" + size,
  133. btn2 = "ghip-" + (size === "fullw" ? "tiled" : "fullw");
  134. table.classList.add(...["ghip-show-previews", btn1]);
  135. $(".btn." + btn1).classList.add("selected");
  136. table.classList.remove(btn2);
  137. $(".btn." + btn2).classList.remove("selected");
  138. }
  139.  
  140. function showList() {
  141. $("table.files").classList.remove(...[
  142. "ghip-show-previews",
  143. "ghip-tiled",
  144. "ghip-fullw"
  145. ]);
  146. $(".btn.ghip-tiled").classList.remove("selected");
  147. $(".btn.ghip-fullw").classList.remove("selected");
  148. }
  149.  
  150. function buildPreviews() {
  151. busy = true;
  152. let template, url, temp, noExt,
  153. imgs = "<td colspan='4' class='ghip-content'>",
  154. indx = 0;
  155. const row = document.createElement("tr"),
  156. table = $("table.files tbody:last-child"),
  157. files = $$("tr.js-navigation-item"),
  158. len = files.length;
  159. row.className = "ghip-image-previews";
  160. if ($(".ghip-image-previews")) {
  161. temp = $(".ghip-image-previews");
  162. temp.parentNode.removeChild(temp);
  163. }
  164. if (table) {
  165. for (indx = 0; indx < len; indx++) {
  166. // not every submodule includes a link; reference examples from
  167. // see https://github.com/electron/electron/tree/v1.1.1/vendor
  168. temp = $("td.content a", files[indx]) ||
  169. $("td.content span span", files[indx]);
  170. // use innerHTML because some links include path - see "third_party/lss"
  171. template = temp ? temp.innerHTML.trim() + "</h4>" : "";
  172. // temp = temp && $("a", temp);
  173. url = temp && temp.nodeName === "A" ? temp.href : "";
  174. // add link color
  175. template = "<h4 class='ghip-file-name" + (url ? " text-blue" : "") +
  176. "'>" + template;
  177. if (imgExt.test(url)) {
  178. // *** image preview ***
  179. template += "<img src='" + url + "?raw=true'/>";
  180. imgs += imgTemplate
  181. .replace("${url}", url)
  182. .replace("${image}", template);
  183. } else if (svgExt.test(url)) {
  184. // *** svg preview ***
  185. // loaded & encoded because GitHub sets content-type headers as
  186. // a string
  187. temp = url.substring(url.lastIndexOf("/") + 1, url.length);
  188. template += `<img data-svg-holder="${temp}" alt="${temp}" />`;
  189. imgs += updateTemplate(url, template);
  190. getSVG(url + "?raw=true");
  191. } else {
  192. // *** non-images (file/folder icons) ***
  193. temp = $("td.icon svg", files[indx]);
  194. if (temp) {
  195. // non-files svg class: "octicon-file-directory" or
  196. // "octicon-file-submodule"
  197. noExt = temp.classList.contains("octicon-file-directory") ||
  198. temp.classList.contains("octicon-file-submodule");
  199. // add xmlns otherwise the svg won't work inside an img
  200. // GitHub doesn't include this attribute on any svg octicons
  201. temp = temp.outerHTML
  202. .replace("<svg", "<svg xmlns='http://www.w3.org/2000/svg'");
  203. // include "leaflet-tile-container" to invert icon for GitHub-Dark
  204. template += "<span class='leaflet-tile-container'>" +
  205. "<img class='ghip-non-image' src='data:image/svg+xml;base64," +
  206. window.btoa(temp) + "'/>" +
  207. "</span>";
  208. // get file name + extension
  209. temp = url.substring(url.lastIndexOf("/") + 1, url.length);
  210. // don't include extension for folders, or files with no extension,
  211. // or files starting with a "." (e.g. ".gitignore")
  212. template += (!noExt && temp.indexOf(".") > 0) ?
  213. "<h4 class='ghip-file-type'>" +
  214. temp
  215. .substring(temp.lastIndexOf(".") + 1, temp.length)
  216. .toUpperCase() +
  217. "</h4>" : "";
  218. imgs += url ?
  219. updateTemplate(url, template) :
  220. // empty url; use non-link template
  221. // see "depot_tools @ 4fa73b8" at
  222. // https://github.com/electron/electron/tree/v1.1.1/vendor
  223. updateTemplate(url, template, spanTemplate);
  224. } else if (files[indx].classList.contains("up-tree")) {
  225. // Up tree link
  226. temp = $("td:nth-child(2) a", files[indx]);
  227. url = temp ? temp.href : "";
  228. imgs += url ?
  229. updateTemplate(
  230. url,
  231. "<h4 class='text-blue'>&middot;&middot;</h4>"
  232. ) : "";
  233. }
  234. }
  235. }
  236. row.innerHTML = imgs + "</td>";
  237. table.appendChild(row);
  238. }
  239. busy = false;
  240. }
  241.  
  242. function updateTemplate(url, img, tmpl) {
  243. return (tmpl || imgTemplate)
  244. .replace("${url}", url)
  245. .replace("${image}", img);
  246. }
  247.  
  248. function getSVG(url) {
  249. GM_xmlhttpRequest({
  250. method: "GET",
  251. url,
  252. onload: response => {
  253. busy = true;
  254. let encoded;
  255. const url = response.finalUrl,
  256. file = url.substring(url.lastIndexOf("/") + 1, url.length),
  257. target = $("[data-svg-holder='" + file + "']");
  258. if (target) {
  259. encoded = window.btoa(response.responseText);
  260. target.src = "data:image/svg+xml;base64," + encoded;
  261. }
  262. busy = false;
  263. }
  264. });
  265. }
  266.  
  267. function $(selector, el) {
  268. return (el || document).querySelector(selector);
  269. }
  270. function $$(selector, el) {
  271. return Array.from((el || document).querySelectorAll(selector));
  272. }
  273.  
  274. function init() {
  275. if ($("table.files")) {
  276. addToggles();
  277. setInitState();
  278. }
  279. }
  280.  
  281. // DOM targets - to detect GitHub dynamic ajax page loading
  282. $$(
  283. "#js-repo-pjax-container, .context-loader-container, [data-pjax-container]"
  284. ).forEach(target => {
  285. new MutationObserver(mutations => {
  286. mutations.forEach(mutation => {
  287. // preform checks before adding code wrap to minimize function calls
  288. if (!busy && mutation.target === target) {
  289. clearTimeout(timer);
  290. timer = setTimeout(init, 200);
  291. }
  292. });
  293. }).observe(target, {
  294. childList: true,
  295. subtree: true
  296. });
  297. });
  298.  
  299. init();
  300. })();