GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2018-09-19 提交的版本,查看 最新版本

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