GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2016-06-23 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name GitHub Custom Hotkeys
  3. // @version 0.2.2
  4. // @description A userscript that allows you to add custom GitHub keyboard hotkeys
  5. // @license https://creativecommons.org/licenses/by-sa/4.0/
  6. // @namespace http://github.com/Mottie
  7. // @include https://github.com/*
  8. // @include https://*.github.com/*
  9. // @grant GM_addStyle
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @run-at document-idle
  13. // @author Rob Garrison
  14. // ==/UserScript==
  15. /* global GM_addStyle, GM_getValue, GM_setValue */
  16. /*jshint unused:true */
  17. (function() {
  18. "use strict";
  19. /* "g p" here overrides the GitHub default "g p" which takes you to the Pull Requests page
  20. {
  21. "all": [
  22. { "f1" : "#hotkey-settings" },
  23. { "g g": "{repo}/graphs" },
  24. { "g p": "{repo}/pulse" },
  25. { "g u": "{user}" },
  26. { "g s": "{upstream}" }
  27. ],
  28. "{repo}/issues": [
  29. { "g right": "{issue+1}" },
  30. { "g left" : "{issue-1}" }
  31. ],
  32. "{root}/search": [
  33. { "g right": "{page+1}" },
  34. { "g left" : "{page-1}" }
  35. ]
  36. }
  37. */
  38. var data = GM_getValue("github-hotkeys", {
  39. "f1": "#hotkey-settings"
  40. }),
  41.  
  42. openHash = "#hotkey-settings",
  43.  
  44. templates = {
  45. remove : "<svg class='ghch-remove octicon' fill='currentColor' xmlns='http://www.w3.org/2000/svg' width='9' height='9' viewBox='0 0 9 9'><path d='M9 1L5.4 4.4 9 8 8 9 4.6 5.4 1 9 0 8l3.6-3.5L0 1l1-1 3.5 3.6L8 0l1 1z'/></svg>",
  46. hotkey : "Hotkey: <input type='text' class='ghch-hotkey form-control'>&nbsp; URL: <input type='text' class='ghch-url form-control'>",
  47. scope : "<ul><li class='ghch-hotkey-add'>+ Click to add a new hotkey</li></ul>"
  48. },
  49.  
  50. // https://github.com/{nonUser}
  51. nonUser = new RegExp("(" + [
  52. "about",
  53. "account",
  54. "blog",
  55. "business",
  56. "contact",
  57. "explore",
  58. "integrations",
  59. "issues",
  60. "join",
  61. "new",
  62. "notifications",
  63. "organizations",
  64. "open-source",
  65. "personal",
  66. "pricing",
  67. "pulls",
  68. "search",
  69. "security",
  70. "settings",
  71. "showcases",
  72. "site",
  73. "stars",
  74. "trending",
  75. "watching",
  76. ].join("|") + ")"),
  77.  
  78. getUrlParts = function() {
  79. var loc = window.location,
  80. root = "https://github.com",
  81. parts = {
  82. root : root,
  83. origin : loc.origin,
  84. page : ""
  85. },
  86. // pathname "should" always start with a "/"
  87. tmp = loc.pathname.split("/");
  88. // me
  89. parts.m = document.querySelector("meta[name='user-login']").getAttribute("content") || "";
  90. parts.me = parts.me ? parts.root + "/" + parts.m : "";
  91. // user name
  92. if (nonUser.test(tmp[1] || "")) {
  93. // invalid user! clear out the values
  94. tmp = [];
  95. }
  96. parts.u = tmp[1] || "";
  97. parts.user = tmp[1] ? root + "/" + tmp[1] : "";
  98. // repo name
  99. parts.r = tmp[2] || "";
  100. parts.repo = tmp[1] && tmp[2] ? parts.user + "/" + tmp[2] : "";
  101. // tab?
  102. parts.t = tmp[3] || "";
  103. parts.tab = tmp[3] ? parts.repo + "/" + tmp[3] : "";
  104. if (parts.t === "issues") {
  105. // issue number
  106. parts.issue = tmp[4] || "";
  107. }
  108. // forked from
  109. tmp = document.querySelector(".repohead .fork-flag a");
  110. parts.upstream = tmp ? tmp.getAttribute("href") : "";
  111. // current page
  112. if (loc.search.match(/[&?]q=/)) {
  113. tmp = loc.search.match(/[&?]p=(\d+)/);
  114. parts.page = tmp ? tmp[1] || "1" : "1";
  115. }
  116. return parts;
  117. },
  118.  
  119. // pass true to initialize; false to remove everything
  120. checkScope = function() {
  121. var key, url,
  122. parts = getUrlParts();
  123. removeElms(document.querySelector("body"), ".ghch-link");
  124. for (key in data) {
  125. if (data.hasOwnProperty(key)) {
  126. url = fixUrl(parts, key === "all" ? "{root}" : key);
  127. if (window.location.href.indexOf(url) > -1) {
  128. debug("Checking custom hotkeys for " + key);
  129. addHotkeys(parts, url, data[key]);
  130. }
  131. }
  132. }
  133. },
  134.  
  135. fixUrl = function(parts, url) {
  136. var valid = true; // use true in case a full URL is used
  137. url = url
  138. // allow {issues+#} to go inc or desc
  139. .replace(/\{issue([\-+]\d+)?\}/, function(s, n) {
  140. var val = n ? parseInt(parts.issue || "", 10) + parseInt(n, 10) : "";
  141. valid = val !== "" && val > 0;
  142. return valid ? parts.tab + "/" + val : "";
  143. })
  144. // allow {page+#} to change results page
  145. .replace(/\{page([\-+]\d+)?\}/, function(s, n) {
  146. var search,
  147. loc = window.location,
  148. val = n ? parseInt(parts.page || "", 10) + parseInt(n, 10) : "";
  149. valid = val !== "" && val > 0;
  150. if (valid) {
  151. search = loc.origin + loc.pathname;
  152. if (loc.search.match(/[&?]p?=\d+/)) {
  153. search += loc.search.replace(/([&?]p=)\d+/, function(s, n) {
  154. return n + val;
  155. });
  156. } else {
  157. // started on page 1 (no &p=1) available to replace
  158. search += loc.search + "&p=" + val;
  159. }
  160. }
  161. return valid ? search : "";
  162. })
  163. // replace placeholders
  164. .replace(/\{\w+\}/gi, function(matches) {
  165. var val = parts[matches.replace(/[{}]/g, "")] || "";
  166. valid = val !== "";
  167. return val;
  168. });
  169. return valid ? url : "";
  170. },
  171.  
  172. removeElms = function(src, selector) {
  173. var links = src.querySelectorAll(selector),
  174. len = links.length;
  175. while(len--) {
  176. src.removeChild(links[len]);
  177. }
  178. },
  179.  
  180. addHotkeys = function(parts, scope, hotkeys) {
  181. // Shhh, don't tell anyone, but GitHub checks the data-hotkey attribute
  182. // of any link on the page, so we only need to add dummy links :P
  183. var indx, url, key, link,
  184. len = hotkeys.length,
  185. body = document.querySelector("body");
  186. for (indx = 0; indx < len; indx++) {
  187. key = Object.keys(hotkeys[indx])[0];
  188. url = fixUrl(parts, hotkeys[indx][key]);
  189. if (url) {
  190. link = document.createElement("a");
  191. link.className = "ghch-link";
  192. link.href = url;
  193. link.setAttribute("data-hotkey", key);
  194. body.appendChild(link);
  195. debug("Adding '" + key + "' keyboard hotkey linked to: " + url);
  196. }
  197. }
  198. },
  199.  
  200. addHotkey = function(el) {
  201. var li = document.createElement("li");
  202. li.className = "ghch-hotkey-set";
  203. li.innerHTML = templates.hotkey + templates.remove;
  204. el.parentNode.insertBefore(li, el);
  205. return li;
  206. },
  207.  
  208. addScope = function(el) {
  209. var scope = document.createElement("fieldset");
  210. scope.className = "ghch-scope-custom";
  211. scope.innerHTML = "<legend><span class='simple-box' contenteditable>Enter Scope</span>&nbsp;" +
  212. templates.remove +
  213. "</legend>" +
  214. templates.scope;
  215. el.parentNode.insertBefore(scope, el);
  216. return scope;
  217. },
  218.  
  219. addMenu = function() {
  220. GM_addStyle([
  221. "#ghch-open-menu { cursor:pointer; }",
  222. "#ghch-menu { position:fixed; z-index: 65535; top:0; bottom:0; left:0; right:0; opacity:0; visibility:hidden; }",
  223. "#ghch-menu.in { opacity:1; visibility:visible; background:rgba(0,0,0,.5); }",
  224. "#ghch-settings-inner { position:fixed; left:50%; top:50%; transform:translate(-50%,-50%); width:25rem; box-shadow:0 .5rem 1rem #111; }",
  225. "#ghch-settings-inner h3 .btn { float:right; font-size:.8em; padding:0 6px 2px 6px; margin-left:3px; }",
  226. ".ghch-remove, .ghch-remove svg, #ghch-settings-inner .ghch-close svg { vertical-align:middle; cursor:pointer; }",
  227. ".ghch-menu-inner { max-height:60vh; overflow-y:auto; }",
  228. ".ghch-menu-inner ul { list-style:none; }",
  229. ".ghch-menu-inner li { margin-bottom:4px; }",
  230. ".ghch-scope-all, .ghch-scope-add, .ghch-scope-custom { width:100%; border:2px solid rgba(85,85,85,0.5); border-radius:4px; padding:10px; margin:0; }",
  231. ".ghch-scope-add, .ghch-hotkey-add { border:2px dashed #555; border-radius:4px; opacity:0.6; text-align:center; cursor:pointer; margin-top:10px; }",
  232. ".ghch-scope-add:hover, .ghch-hotkey-add:hover { opacity:1; }",
  233. ".ghch-menu-inner legend span { padding:0 6px; min-width:30px; border:0; }",
  234. ".ghch-hotkey { width:60px; }",
  235. ".ghch-menu-inner li .ghch-remove { margin-left:10px; }",
  236. ".ghch-menu-inner li .ghch-remove:hover, .ghch-menu-inner legend .ghch-remove:hover { color:#800; }",
  237. ".ghch-json-code { display:none; font-family:Menlo, Inconsolata, 'Droid Mono', monospace; font-size:1em; }",
  238. ".ghch-json-code.in { position:absolute; top:37px; bottom:0; left:2px; right:2px; z-index:0; width:396px; max-width:396px; max-height:calc(100% - 37px); display:block; }"
  239. ].join(""));
  240.  
  241. // add menu
  242. var tmp,
  243. inner = [
  244. "<div id='ghch-settings-inner' class='boxed-group'>",
  245. "<h3>",
  246. "GitHub Custom Hotkey Settings",
  247. "<button type='button' class='btn btn-sm ghch-close tooltipped tooltipped-n' aria-label='Close';>" + templates.remove + "</button>",
  248. "<button type='button' class='ghch-code btn btn-sm tooltipped tooltipped-n' aria-label='Toggle JSON data view'>{ }</button>",
  249. "<a href='https://github.com/Mottie/GitHub-userscripts/wiki/GitHub-custom-hotkeys' class='ghch-help btn btn-sm tooltipped tooltipped-n' aria-label='Get Help'>?</a>",
  250. "</h3>",
  251. "<div class='ghch-menu-inner boxed-group-inner'>",
  252. "<fieldset class='ghch-scope-all'>",
  253. "<legend><span class='simple-box' data-scope='all'>All of GitHub &amp; subdomains</span></legend>",
  254. templates.scope,
  255. "</fieldset>",
  256. "<div class='ghch-scope-add'>+ Click to add a new scope</div>",
  257. "<textarea class='ghch-json-code'></textarea>",
  258. "</div>",
  259. "</div>"
  260. ].join(""),
  261.  
  262. menu = document.createElement("div");
  263. menu.id = "ghch-menu";
  264. menu.innerHTML = inner;
  265. document.querySelector("body").appendChild(menu);
  266. // Create our menu entry
  267. menu = document.createElement("a");
  268. menu.id = "ghch-open-menu";
  269. menu.className = "dropdown-item";
  270. menu.innerHTML = "GitHub Hotkey Settings";
  271.  
  272. tmp = document.querySelectorAll(".header .dropdown-item[href='/settings/profile'], .header .dropdown-item[data-ga-click*='go to profile']");
  273. if (tmp) {
  274. tmp[tmp.length - 1].parentNode.insertBefore(menu, tmp[tmp.length - 1].nextSibling);
  275. }
  276. addBindings();
  277. },
  278.  
  279. openPanel = function() {
  280. updateMenu();
  281. document.querySelector("#ghch-menu").classList.add("in");
  282. return false;
  283. },
  284.  
  285. closePanel = function() {
  286. var menu = document.querySelector("#ghch-menu");
  287. if (menu.classList.contains("in")) {
  288. // update data in case a "change" event didn't fire
  289. refreshData();
  290. checkScope();
  291. menu.classList.remove("in");
  292. menu.querySelector(".ghch-json-code").classList.remove("in");
  293. window.location.hash = "";
  294. return false;
  295. }
  296. },
  297.  
  298. addJSON = function() {
  299. var textarea = document.querySelector(".ghch-json-code");
  300. textarea.value = JSON
  301. .stringify(data, null, 2)
  302. // compress JSON a little
  303. .replace(/\n \}/g, " }")
  304. .replace(/\{\n /g, "{ ");
  305. },
  306.  
  307. processJSON = function() {
  308. var val,
  309. textarea = document.querySelector(".ghch-json-code"),
  310. txt = textarea.value;
  311. try {
  312. val = JSON.parse(txt);
  313. data = val;
  314. } catch (err) {}
  315. },
  316.  
  317. updateMenu = function() {
  318. var indx, len, hotkeys, key, scope, tmp, target, selector,
  319. menu = document.querySelector(".ghch-menu-inner");
  320. removeElms(menu, ".ghch-scope-custom");
  321. removeElms(menu.querySelector(".ghch-scope-all ul"), ".ghch-hotkey-set");
  322. // Add scopes
  323. for (key in data) {
  324. if (data.hasOwnProperty(key)) {
  325. if (key === "all") {
  326. selector = "all";
  327. scope = menu.querySelector(".ghch-scope-all .ghch-hotkey-add");
  328. } else if (key !== selector) {
  329. selector = key;
  330. scope = addScope(document.querySelector(".ghch-scope-add"));
  331. scope.querySelector("legend span").innerHTML = key;
  332. scope = scope.querySelector(".ghch-hotkey-add");
  333. }
  334. // add hotkey entries
  335. hotkeys = data[key];
  336. len = hotkeys.length;
  337. for (indx = 0; indx < len; indx++) {
  338. target = addHotkey(scope);
  339. tmp = Object.keys(hotkeys[indx])[0];
  340. target.querySelector(".ghch-hotkey").value = tmp;
  341. target.querySelector(".ghch-url").value = hotkeys[indx][tmp];
  342. }
  343. }
  344. }
  345. },
  346.  
  347. refreshData = function() {
  348. var tmp, scope, scopes, sIndx, sLen, hotkeys, scIndx, scLen, val,
  349. menu = document.querySelector(".ghch-menu-inner");
  350. data = {};
  351. scopes = menu.querySelectorAll("fieldset");
  352. sLen = scopes.length;
  353. for (sIndx = 0; sIndx < sLen; sIndx++) {
  354. tmp = scopes[sIndx].querySelector("legend span");
  355. if (tmp) {
  356. scope = tmp.getAttribute("data-scope") || tmp.textContent.trim();
  357. hotkeys = scopes[sIndx].querySelectorAll(".ghch-hotkey-set");
  358. scLen = hotkeys.length;
  359. data[scope] = [];
  360. for (scIndx = 0; scIndx < scLen; scIndx++) {
  361. tmp = hotkeys[scIndx].querySelectorAll("input");
  362. val = tmp[0] && tmp[0].value || "";
  363. if (val) {
  364. data[scope][scIndx] = {};
  365. data[scope][scIndx][val] = tmp[1].value || "";
  366. }
  367. }
  368. }
  369. }
  370. GM_setValue("github-hotkeys", data);
  371. debug("Data refreshed", data);
  372. },
  373.  
  374. lastHref = window.location.href,
  375. addBindings = function() {
  376. var tmp,
  377. menu = document.querySelector("#ghch-menu");
  378.  
  379. // open menu
  380. document.querySelector("#ghch-open-menu").addEventListener("click", openPanel);
  381. // close menu
  382. menu.addEventListener("click", closePanel);
  383. document.querySelector("body").addEventListener("keydown", function(event) {
  384. if (event.which === 27) {
  385. closePanel();
  386. }
  387. });
  388. // stop propagation
  389. menu.querySelector("#ghch-settings-inner").addEventListener("keydown", function(event) {
  390. event.stopPropagation();
  391. });
  392. menu.querySelector("#ghch-settings-inner").addEventListener("click", function(event) {
  393. event.stopPropagation();
  394. var target = event.target;
  395. // add hotkey
  396. if (target.classList.contains("ghch-hotkey-add")) {
  397. addHotkey(target);
  398. } else if (target.classList.contains("ghch-scope-add")) {
  399. addScope(target);
  400. }
  401. // svg & path nodeName may be lowercase
  402. tmp = target.nodeName.toLowerCase();
  403. if (tmp === "path") {
  404. target = target.parentNode;
  405. }
  406. // target should now point at svg
  407. if (target.classList.contains("ghch-remove")) {
  408. tmp = target.parentNode;
  409. // remove fieldset
  410. if (tmp.nodeName === "LEGEND") {
  411. tmp = tmp.parentNode;
  412. }
  413. // remove li; but not the button in the header
  414. if (tmp.nodeName !== "BUTTON") {
  415. tmp.parentNode.removeChild(tmp);
  416. refreshData();
  417. }
  418. }
  419. });
  420. menu.addEventListener("change", refreshData);
  421. // contenteditable scope title
  422. menu.addEventListener("input", function(event) {
  423. if (event.target.classList.contains("simple-box")) {
  424. refreshData();
  425. }
  426. });
  427. menu.querySelector("button.ghch-close").addEventListener("click", closePanel);
  428. // open JSON code textarea
  429. tmp = menu.querySelector(".ghch-code");
  430. tmp.addEventListener("click", function() {
  431. menu.querySelector(".ghch-json-code").classList.toggle("in");
  432. addJSON();
  433. });
  434. // close JSON code textarea
  435. tmp = menu.querySelector(".ghch-json-code");
  436. tmp.addEventListener("focus", function() {
  437. this.select();
  438. });
  439. tmp.addEventListener("paste", function() {
  440. setTimeout(function() {
  441. processJSON();
  442. updateMenu();
  443. document.querySelector(".ghch-json-code").classList.remove("in");
  444. }, 200);
  445. });
  446.  
  447. // This is crazy! But window.location.search changes do not fire the
  448. // "popstate" or "hashchange" event, so we're stuck with a setInterval
  449. setInterval(function() {
  450. var loc = window.location;
  451. if (lastHref !== loc.href) {
  452. lastHref = loc.href;
  453. checkScope();
  454. // open panel via hash
  455. if (loc.hash === openHash) {
  456. openPanel();
  457. }
  458. }
  459. }, 1000);
  460. },
  461.  
  462. // include a "debug" anywhere in the browser URL (search parameter) to enable debugging
  463. debug = function() {
  464. if (/debug/.test(window.location.search)) {
  465. console.log.apply(console, arguments);
  466. }
  467. };
  468.  
  469. // initialize
  470. checkScope();
  471. addMenu();
  472.  
  473. })();