GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2020-09-08 提交的版本,查看 最新版本

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