GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

目前為 2016-09-13 提交的版本,檢視 最新版本

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