GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2016-07-11 提交的版本,查看 最新版本

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