GitHub Image Preview

A userscript that adds clickable image thumbnails

当前为 2019-01-29 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name GitHub Image Preview
  3. // @version 1.2.1
  4. // @description A userscript that adds clickable image thumbnails
  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_getValue
  12. // @grant GM_setValue
  13. // @grant GM_xmlhttpRequest
  14. // @connect github.com
  15. // @connect githubusercontent.com
  16. // @require https://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=666427
  17. // @icon https://assets-cdn.github.com/pinned-octocat.svg
  18. // ==/UserScript==
  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:22.5%; height:180px;
  33. margin:12px !important; /* GitHub uses !important flags now :( */ }
  34. table.files.ghip-tiled .image .border-wrap img,
  35. .ghip-image-previews .border-wrap svg { max-height:130px; }
  36. table.files.ghip-fullw .image { width:97%; height:auto; }
  37. /* zoom doesn't work in Firefox, but "-moz-transform:scale(3);"
  38. doesn't limit the size of the image, so it overflows */
  39. table.files.ghip-tiled .image:hover img:not(.ghip-non-image) { zoom:3; }
  40. .ghip-image-previews .border-wrap img,
  41. .ghip-image-previews .border-wrap svg { max-width:95%; }
  42. .ghip-image-previews .border-wrap img.error { border:5px solid red;
  43. border-radius:32px; }
  44. .ghip-image-previews .border-wrap h4 { white-space:nowrap;
  45. text-overflow:ellipsis; margin-bottom:5px; }
  46. .ghip-image-previews .border-wrap h4.ghip-file-name { overflow:hidden; }
  47. .btn.ghip-tiled > *, .btn.ghip-fullw > *, .ghip-image-previews iframe {
  48. pointer-events:none; vertical-align:baseline; }
  49. .image .ghip-file-type { font-size:30px; top:-1.8em; position:relative;
  50. z-index:2; }
  51. .ghip-content span.exploregrid-item .ghip-file-name { cursor:default; }
  52. /* override GitHub-Dark styles */
  53. table.files img[src*='octocat-spinner'], img[src='/images/spinner.gif'] {
  54. width:auto !important; height:auto !important; }
  55. table.files td .simplified-path { color:#888 !important; }
  56. `);
  57.  
  58. // supported img types
  59. const imgExt = /(png|jpg|jpeg|gif|tif|tiff|bmp|webp)$/i,
  60. svgExt = /svg$/i,
  61. spinner = "https://assets-cdn.github.com/images/spinners/octocat-spinner-32.gif",
  62.  
  63. folderIconClasses = `
  64. .octicon-file-directory,
  65. .octicon-file-symlink-directory,
  66. .octicon-file-submodule`,
  67.  
  68. tiled = `
  69. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 16 16">
  70. <path d="M0 0h7v7H0zM9 9h7v7H9zM9 0h7v7H9zM0 9h7v7H0z"/>
  71. </svg>
  72. `,
  73. fullWidth = `
  74. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 16 16">
  75. <path d="M0 0h16v7H0zM0 9h16v7H0z"/>
  76. </svg>
  77. `,
  78. imgTemplate = [
  79. // not using backticks here
  80. "<a href='${url}' class='exploregrid-item image m-3 float-left js-navigation-open' rel='nofollow'>",
  81. "<span class='border-wrap'>${image}</span>",
  82. "</a>"
  83. ].join(""),
  84. spanTemplate = [
  85. "<span class='exploregrid-item image m-3 float-left'>",
  86. "<span class='border-wrap'>${image}</span>",
  87. "</span>"
  88. ].join("");
  89.  
  90. function addToggles() {
  91. if ($(".gh-img-preview")) {
  92. return;
  93. }
  94. const div = document.createElement("div"),
  95. btn = `btn btn-sm BtnGroup-item tooltipped tooltipped-n" aria-label="Show`;
  96. div.className = "BtnGroup float-right gh-img-preview";
  97. div.innerHTML = `
  98. <button type="button" class="ghip-tiled ${btn} tiled files with image preview">${tiled}</button>
  99. <button type="button" class="ghip-fullw ${btn} full width files with image preview">${fullWidth}</button>
  100. `;
  101. $(".file-navigation").appendChild(div);
  102.  
  103. $(".ghip-tiled", div).addEventListener("click", event => {
  104. openView("tiled", event);
  105. });
  106. $(".ghip-fullw", div).addEventListener("click", event => {
  107. openView("fullw", event);
  108. });
  109. }
  110.  
  111. function setInitState() {
  112. const state = GM_getValue("gh-image-preview");
  113. if (state) {
  114. openView(state);
  115. }
  116. }
  117.  
  118. function openView(name, event) {
  119. const el = $(".ghip-" + name);
  120. if (el) {
  121. if (event) {
  122. el.classList.toggle("selected");
  123. if (!el.classList.contains("selected")) {
  124. return showList();
  125. }
  126. }
  127. showPreview(name);
  128. }
  129. }
  130.  
  131. function showPreview(name) {
  132. buildPreviews();
  133. const table = $("table.files"),
  134. selected = "ghip-" + name,
  135. notSelected = "ghip-" + (name === "fullw" ? "tiled" : "fullw");
  136. table.classList.add("ghip-show-previews", selected);
  137. $(".btn." + selected).classList.add("selected");
  138. table.classList.remove(notSelected);
  139. $(".btn." + notSelected).classList.remove("selected");
  140. GM_setValue("gh-image-preview", name);
  141. }
  142.  
  143. function showList() {
  144. $("table.files").classList.remove(
  145. "ghip-show-previews", "ghip-tiled", "ghip-fullw"
  146. );
  147. $(".btn.ghip-tiled").classList.remove("selected");
  148. $(".btn.ghip-fullw").classList.remove("selected");
  149. GM_setValue("gh-image-preview", "");
  150. }
  151.  
  152. function buildPreviews() {
  153. let template, url, temp, noExt, fileName,
  154. imgs = "<td colspan='4' class='ghip-content'>",
  155. indx = 0;
  156. const row = document.createElement("tr"),
  157. table = $("table.files tbody:last-child"),
  158. files = $$("tr.js-navigation-item"),
  159. len = files.length;
  160. row.className = "ghip-image-previews";
  161. if ($(".ghip-image-previews")) {
  162. temp = $(".ghip-image-previews");
  163. temp.parentNode.removeChild(temp);
  164. }
  165. if (table) {
  166. for (indx = 0; indx < len; indx++) {
  167. // not every submodule includes a link; reference examples from
  168. // see https://github.com/electron/electron/tree/v1.1.1/vendor
  169. temp = $("td.content a", files[indx]) ||
  170. $("td.content span span", files[indx]);
  171. // use innerHTML because some links include path - see "third_party/lss"
  172. fileName = temp ? temp.innerHTML.trim() : "";
  173. // temp = temp && $("a", temp);
  174. url = temp && temp.nodeName === "A" ? temp.href : "";
  175. // add link color
  176. template = `<h4 class="ghip-file-name ${
  177. (url ? " text-blue" : "")}" title="${fileName}">
  178. ${fileName}
  179. </h4>`;
  180. if (imgExt.test(url)) {
  181. // *** image preview ***
  182. template += "<img src='" + url + "?raw=true'/>";
  183. imgs += imgTemplate
  184. .replace("${url}", url)
  185. .replace("${image}", template);
  186. } else if (svgExt.test(url)) {
  187. // *** svg preview ***
  188. // loaded & encoded because GitHub sets content-type headers as
  189. // a string
  190. temp = url.substring(url.lastIndexOf("/") + 1, url.length);
  191. template += `<img data-svg-holder="${temp}" data-svg-url="${url}" alt="${temp}" src="${spinner}" />`;
  192. imgs += updateTemplate(url, template);
  193. } else {
  194. // *** non-images (file/folder icons) ***
  195. temp = $("td.icon svg", files[indx]);
  196. if (temp) {
  197. // non-files svg class: "directory", "submodule" or "symlink"
  198. // add "ghip-folder" class for file-filters userscript
  199. noExt = temp.matches(folderIconClasses) ? " ghip-folder" : "";
  200. // add xmlns otherwise the svg won't work inside an img
  201. // GitHub doesn't include this attribute on any svg octicons
  202. temp = temp.outerHTML
  203. .replace("<svg", "<svg xmlns='http://www.w3.org/2000/svg'");
  204. // include "leaflet-tile-container" to invert icon for GitHub-Dark
  205. template += `<span class="leaflet-tile-container${noExt}">` +
  206. `<img class="ghip-non-image" src="data:image/svg+xml;base64,` +
  207. window.btoa(temp) + `"/></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 ghip-up-tree'>&middot;&middot;</h4>"
  232. ) : "";
  233. }
  234. }
  235. }
  236. row.innerHTML = imgs + "</td>";
  237. table.appendChild(row);
  238. lazyLoadSVGs();
  239. }
  240. }
  241.  
  242. function updateTemplate(url, img, tmpl) {
  243. return (tmpl || imgTemplate)
  244. .replace("${url}", url)
  245. .replace("${image}", img);
  246. }
  247.  
  248. function lazyLoadSVGs() {
  249. const imgs = $$("[data-svg-holder]");
  250. if (imgs.length && "IntersectionObserver" in window) {
  251. let imgObserver = new IntersectionObserver(entries => {
  252. entries.forEach(entry => {
  253. if (entry.isIntersecting) {
  254. const img = entry.target;
  255. setTimeout(() => {
  256. const bounds = img.getBoundingClientRect();
  257. // Don't load all svgs when the user scrolls down the page really
  258. // fast
  259. if (bounds.top <= window.innerHeight && bounds.bottom >= 0) {
  260. getSVG(imgObserver, img);
  261. }
  262. }, 300);
  263. }
  264. });
  265. });
  266. imgs.forEach(function(img) {
  267. imgObserver.observe(img);
  268. });
  269. } else {
  270. console.error("IntersectionObserver is not supported");
  271. }
  272. }
  273.  
  274. function getSVG(observer, img) {
  275. GM_xmlhttpRequest({
  276. method: "GET",
  277. url: img.dataset.svgUrl + "?raw=true",
  278. onload: response => {
  279. const url = response.finalUrl,
  280. file = url.substring(url.lastIndexOf("/") + 1, url.length),
  281. target = $("[data-svg-holder='" + file + "']"),
  282. resp = response.responseText,
  283. // Loading too many images at once makes GitHub returns a "You have triggered
  284. // an abuse detection mechanism" message
  285. abuse = resp.includes("abuse detection");
  286. if (target && !abuse) {
  287. const encoded = window.btoa(response.responseText);
  288. target.src = "data:image/svg+xml;base64," + encoded;
  289. target.title = "";
  290. target.classList.remove("error");
  291. observer.unobserve(img);
  292. } else if (abuse) {
  293. img.title = "GitHub is reporting that too many images have been loaded at once, please wait";
  294. img.classList.add("error");
  295. }
  296. }
  297. });
  298. }
  299.  
  300. function $(selector, el) {
  301. return (el || document).querySelector(selector);
  302. }
  303. function $$(selector, el) {
  304. return [...(el || document).querySelectorAll(selector)];
  305. }
  306.  
  307. function init() {
  308. if ($("table.files")) {
  309. addToggles();
  310. setTimeout(setInitState, 0);
  311. }
  312. }
  313.  
  314. document.addEventListener("ghmo:container", init);
  315. init();
  316. })();