GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

目前為 2020-08-09 提交的版本,檢視 最新版本

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