GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2017-03-25 提交的版本,查看 最新版本

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