GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

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

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