GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

当前为 2017-09-02 提交的版本,查看 最新版本

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