GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

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

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