GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2016-05-25 提交的版本,查看 最新版本

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