GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2018-04-02 提交的版本,查看 最新版本

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