GitHub Image Preview

A userscript that adds clickable image thumbnails

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

  1. // ==UserScript==
  2. // @name GitHub Image Preview
  3. // @version 1.1.0
  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.  
  69. fullWidth = `
  70. <svg class="octicon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 16 16">
  71. <path d="M0 0h16v7H0zM0 9h16v7H0z"/>
  72. </svg>
  73. `,
  74.  
  75. imgTemplate = [
  76. // not using backticks here
  77. "<a href='${url}' class='exploregrid-item image js-navigation-open' rel='nofollow'>",
  78. "<span class='border-wrap'>${image}</span>",
  79. "</a>"
  80. ].join(""),
  81.  
  82. spanTemplate = [
  83. "<span class='exploregrid-item image'>",
  84. "<span class='border-wrap'>${image}</span>",
  85. "</span>"
  86. ].join("");
  87.  
  88. function addToggles() {
  89. if ($(".gh-img-preview")) {
  90. return;
  91. }
  92. busy = true;
  93. const div = document.createElement("div"),
  94. btn = `btn btn-sm tooltipped tooltipped-n" aria-label="Show`;
  95. div.className = "BtnGroup float-right gh-img-preview";
  96. div.innerHTML = `
  97. <div class="ghip-tiled ${btn} tiled files with image preview">${tiled}</div>
  98. <div class="ghip-fullw ${btn} full width files with image preview">${fullWidth}</div>
  99. `;
  100. $(".file-navigation").appendChild(div);
  101.  
  102. $(".ghip-tiled", div).addEventListener("click", () => {
  103. openView("tiled");
  104. });
  105. $(".ghip-fullw", div).addEventListener("click", () => {
  106. openView("fullw");
  107. });
  108. busy = false;
  109. }
  110.  
  111. function setInitState() {
  112. const view = GM_getValue("gh-image-preview");
  113. if (view) {
  114. openView(view);
  115. }
  116. }
  117.  
  118. function openView(name) {
  119. const el = $(".ghip-" + name);
  120. if (el) {
  121. el.classList.toggle("selected");
  122. if (el.classList.contains("selected")) {
  123. GM_setValue("gh-image-preview", name);
  124. showPreview(name);
  125. } else {
  126. GM_setValue("gh-image-preview", "");
  127. showList();
  128. }
  129. }
  130. }
  131.  
  132. function showPreview(size) {
  133. buildPreviews();
  134. const table = $("table.files"),
  135. btn1 = "ghip-" + size,
  136. btn2 = "ghip-" + (size === "fullw" ? "tiled" : "fullw");
  137. table.classList.add(...["ghip-show-previews", btn1]);
  138. $(".btn." + btn1).classList.add("selected");
  139. table.classList.remove(btn2);
  140. $(".btn." + btn2).classList.remove("selected");
  141. }
  142.  
  143. function showList() {
  144. $("table.files").classList.remove(...[
  145. "ghip-show-previews",
  146. "ghip-tiled",
  147. "ghip-fullw"
  148. ]);
  149. $(".btn.ghip-tiled").classList.remove("selected");
  150. $(".btn.ghip-fullw").classList.remove("selected");
  151. }
  152.  
  153. function buildPreviews() {
  154. busy = true;
  155. let template, url, temp, noExt,
  156. imgs = "<td colspan='4' class='ghip-content'>",
  157. indx = 0;
  158. const row = document.createElement("tr"),
  159. table = $("table.files tbody:last-child"),
  160. files = $$("tr.js-navigation-item"),
  161. len = files.length;
  162. row.className = "ghip-image-previews";
  163. if ($(".ghip-image-previews")) {
  164. temp = $(".ghip-image-previews");
  165. temp.parentNode.removeChild(temp);
  166. }
  167. if (table) {
  168. for (indx = 0; indx < len; indx++) {
  169. // not every submodule includes a link; reference examples from
  170. // see https://github.com/electron/electron/tree/v1.1.1/vendor
  171. temp = $("td.content a", files[indx]) ||
  172. $("td.content span span", files[indx]);
  173. // use innerHTML because some links include path - see "third_party/lss"
  174. template = temp ? temp.innerHTML.trim() + "</h4>" : "";
  175. // temp = temp && $("a", temp);
  176. url = temp && temp.nodeName === "A" ? temp.href : "";
  177. // add link color
  178. template = "<h4 class='ghip-file-name" + (url ? " text-blue" : "") +
  179. "'>" + template;
  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}" alt="${temp}" />`;
  192. imgs += updateTemplate(url, template);
  193. getSVG(url + "?raw=true");
  194. } else {
  195. // *** non-images (file/folder icons) ***
  196. temp = $("td.icon svg", files[indx]);
  197. if (temp) {
  198. // non-files svg class: "octicon-file-directory" or
  199. // "octicon-file-submodule"
  200. noExt = temp.classList.contains("octicon-file-directory") ||
  201. temp.classList.contains("octicon-file-submodule");
  202. // add xmlns otherwise the svg won't work inside an img
  203. // GitHub doesn't include this attribute on any svg octicons
  204. temp = temp.outerHTML
  205. .replace("<svg", "<svg xmlns='http://www.w3.org/2000/svg'");
  206. // include "leaflet-tile-container" to invert icon for GitHub-Dark
  207. template += "<span class='leaflet-tile-container'>" +
  208. "<img class='ghip-non-image' src='data:image/svg+xml;base64," +
  209. window.btoa(temp) + "'/>" +
  210. "</span>";
  211. // get file name + extension
  212. temp = url.substring(url.lastIndexOf("/") + 1, url.length);
  213. // don't include extension for folders, or files with no extension,
  214. // or files starting with a "." (e.g. ".gitignore")
  215. template += (!noExt && temp.indexOf(".") > 0) ?
  216. "<h4 class='ghip-file-type'>" +
  217. temp
  218. .substring(temp.lastIndexOf(".") + 1, temp.length)
  219. .toUpperCase() +
  220. "</h4>" : "";
  221. imgs += url ?
  222. updateTemplate(url, template) :
  223. // empty url; use non-link template
  224. // see "depot_tools @ 4fa73b8" at
  225. // https://github.com/electron/electron/tree/v1.1.1/vendor
  226. updateTemplate(url, template, spanTemplate);
  227. } else if (files[indx].classList.contains("up-tree")) {
  228. // Up tree link
  229. temp = $("td:nth-child(2) a", files[indx]);
  230. url = temp ? temp.href : "";
  231. imgs += url ?
  232. updateTemplate(
  233. url,
  234. "<h4 class='text-blue'>&middot;&middot;</h4>"
  235. ) : "";
  236. }
  237. }
  238. }
  239. row.innerHTML = imgs + "</td>";
  240. table.appendChild(row);
  241. }
  242. busy = false;
  243. }
  244.  
  245. function updateTemplate(url, img, tmpl) {
  246. return (tmpl || imgTemplate)
  247. .replace("${url}", url)
  248. .replace("${image}", img);
  249. }
  250.  
  251. function getSVG(url) {
  252. GM_xmlhttpRequest({
  253. method: "GET",
  254. url,
  255. onload: response => {
  256. busy = true;
  257. let encoded;
  258. const url = response.finalUrl,
  259. file = url.substring(url.lastIndexOf("/") + 1, url.length),
  260. target = $("[data-svg-holder='" + file + "']");
  261. if (target) {
  262. encoded = window.btoa(response.responseText);
  263. target.src = "data:image/svg+xml;base64," + encoded;
  264. }
  265. busy = false;
  266. }
  267. });
  268. }
  269.  
  270. function $(selector, el) {
  271. return (el || document).querySelector(selector);
  272. }
  273. function $$(selector, el) {
  274. return Array.from((el || document).querySelectorAll(selector));
  275. }
  276.  
  277. function init() {
  278. if ($("table.files")) {
  279. addToggles();
  280. setInitState();
  281. }
  282. }
  283.  
  284. // DOM targets - to detect GitHub dynamic ajax page loading
  285. $$(
  286. "#js-repo-pjax-container, .context-loader-container, [data-pjax-container]"
  287. ).forEach(target => {
  288. new MutationObserver(mutations => {
  289. mutations.forEach(mutation => {
  290. // preform checks before adding code wrap to minimize function calls
  291. if (!busy && mutation.target === target) {
  292. clearTimeout(timer);
  293. timer = setTimeout(init, 200);
  294. }
  295. });
  296. }).observe(target, {
  297. childList: true,
  298. subtree: true
  299. });
  300. });
  301.  
  302. init();
  303. })();