GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2016-09-13 提交的版本,查看 最新版本

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