GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2019-05-13 提交的版本,查看 最新版本

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