GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2017-05-16 提交的版本,查看 最新版本

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