GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2018-01-24 提交的版本,查看 最新版本

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