GitHub Diff Links

A userscript that adds links to diff headers to jump back & forth between files

As of 2016-07-22. See the latest version.

  1. // ==UserScript==
  2. // @name GitHub Diff Links
  3. // @version 1.0.0
  4. // @description A userscript that adds links to diff headers to jump back & forth between files
  5. // @license https://creativecommons.org/licenses/by-sa/4.0/
  6. // @namespace http://github.com/Mottie
  7. // @include https://github.com/*
  8. // @run-at document-idle
  9. // @grant GM_addStyle
  10. // @author Rob Garrison
  11. // ==/UserScript==
  12. /* jshint esnext:true */
  13. (() => {
  14. "use strict";
  15.  
  16. // sometimes tooltips are too narrow...
  17. GM_addStyle(".gh-diff-links:after { min-width: 120px; }");
  18.  
  19. const button = document.createElement("a"),
  20. // button [ InnerHTML, tooltip ]
  21. nextBtn = ["Next", "Jump to next file\n("],
  22. prevBtn = ["Prev", "Jump to previous file\n(" ];
  23.  
  24. button.className = "btn btn-sm tooltipped tooltipped-s tooltipped-multiline gh-diff-links";
  25. button.setAttribute("rel", "nofollow");
  26.  
  27. function addButton(el, content, link) {
  28. var txt = (link.textContent || ""),
  29. btn = button.cloneNode();
  30. // only add file name to tooltip
  31. txt = txt.substring(txt.lastIndexOf("/") + 1, txt.length);
  32. btn.innerHTML = content[0];
  33. btn.setAttribute("aria-label", content[1] + txt + ")" );
  34. btn.href = link.href;
  35. // prepend button
  36. el.insertBefore(btn, el.childNodes[0]);
  37. }
  38.  
  39. function addLinks() {
  40. let last,
  41. diffLinks = $$(".gh-diff-links"),
  42. links = $$("#toc ol.content li > a");
  43. // add diff links if they don't already exist
  44. if (links.length !== diffLinks.length) {
  45. // remove old links (just in case)
  46. diffLinks.forEach(el => {
  47. el.parentNode.removeChild(el);
  48. });
  49. // links & file-actions "should" be the same length
  50. last = links.length - 1;
  51. $$(".file-actions").forEach((el, indx) => {
  52. if (indx === 0) {
  53. addButton(el, nextBtn, links[indx + 1]);
  54. } else if (indx === last) {
  55. addButton(el, prevBtn, links[indx - 1]);
  56. } else {
  57. addButton(el, nextBtn, links[indx + 1]);
  58. addButton(el, prevBtn, links[indx - 1]);
  59. }
  60. });
  61. }
  62. }
  63.  
  64. function init() {
  65. if ($("#files.diff-view")) {
  66. addLinks();
  67. }
  68. }
  69.  
  70. function $(selector, el) {
  71. return (el || document).querySelector(selector);
  72. }
  73. function $$(selector, el) {
  74. return Array.from((el || document).querySelectorAll(selector));
  75. }
  76.  
  77. document.addEventListener("pjax:end", init);
  78. init();
  79.  
  80. })();