GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2021-02-12 提交的版本,查看 最新版本

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