GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

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

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