Greasy Fork 还支持 简体中文。

GitHub Custom Hotkeys

A userscript that allows you to add custom GitHub keyboard hotkeys

目前為 2016-07-05 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name GitHub Custom Hotkeys
  3. // @version 0.2.3
  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 unused:true */
  17. (function() {
  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. var data = GM_getValue("github-hotkeys", {
  39. "f1": "#hotkey-settings"
  40. }),
  41.  
  42. openHash = "#hotkey-settings",
  43.  
  44. templates = {
  45. 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>",
  46. hotkey : "Hotkey: <input type='text' class='ghch-hotkey form-control'>&nbsp; URL: <input type='text' class='ghch-url form-control'>",
  47. scope : "<ul><li class='ghch-hotkey-add'>+ Click to add a new hotkey</li></ul>"
  48. },
  49.  
  50. // https://github.com/{nonUser}
  51. // see https://github.com/buunguyen/octotree/blob/master/src/adapters/github.js#L1-L10
  52. nonUser = new RegExp("(" + [
  53. "about",
  54. "account",
  55. "blog",
  56. "business",
  57. "contact",
  58. "dashboard",
  59. "developer",
  60. "explore",
  61. "features",
  62. "integrations",
  63. "issues",
  64. "join",
  65. "new",
  66. "notifications",
  67. "organizations",
  68. "open-source",
  69. "personal",
  70. "pricing",
  71. "pulls",
  72. "search",
  73. "security",
  74. "settings",
  75. "showcases",
  76. "site",
  77. "stars",
  78. "styleguide",
  79. "trending",
  80. "watching",
  81. ].join("|") + ")"),
  82.  
  83. getUrlParts = function() {
  84. var loc = window.location,
  85. root = "https://github.com",
  86. parts = {
  87. root : root,
  88. origin : loc.origin,
  89. page : ""
  90. },
  91. // pathname "should" always start with a "/"
  92. tmp = loc.pathname.split("/");
  93. // me
  94. parts.m = document.querySelector("meta[name='user-login']").getAttribute("content") || "";
  95. parts.me = parts.me ? parts.root + "/" + parts.m : "";
  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 = document.querySelector(".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. checkScope = function() {
  126. var key, url,
  127. parts = getUrlParts();
  128. removeElms(document.querySelector("body"), ".ghch-link");
  129. for (key in data) {
  130. if (data.hasOwnProperty(key)) {
  131. url = fixUrl(parts, key === "all" ? "{root}" : key);
  132. if (window.location.href.indexOf(url) > -1) {
  133. debug("Checking custom hotkeys for " + key);
  134. addHotkeys(parts, url, data[key]);
  135. }
  136. }
  137. }
  138. },
  139.  
  140. fixUrl = function(parts, url) {
  141. var valid = true; // use true in case a full URL is used
  142. url = url
  143. // allow {issues+#} to go inc or desc
  144. .replace(/\{issue([\-+]\d+)?\}/, function(s, n) {
  145. var val = n ? parseInt(parts.issue || "", 10) + parseInt(n, 10) : "";
  146. valid = val !== "" && val > 0;
  147. return valid ? parts.tab + "/" + val : "";
  148. })
  149. // allow {page+#} to change results page
  150. .replace(/\{page([\-+]\d+)?\}/, function(s, n) {
  151. var search,
  152. loc = window.location,
  153. val = n ? parseInt(parts.page || "", 10) + parseInt(n, 10) : "";
  154. valid = val !== "" && val > 0;
  155. if (valid) {
  156. search = loc.origin + loc.pathname;
  157. if (loc.search.match(/[&?]p?=\d+/)) {
  158. search += loc.search.replace(/([&?]p=)\d+/, function(s, n) {
  159. return n + val;
  160. });
  161. } else {
  162. // started on page 1 (no &p=1) available to replace
  163. search += loc.search + "&p=" + val;
  164. }
  165. }
  166. return valid ? search : "";
  167. })
  168. // replace placeholders
  169. .replace(/\{\w+\}/gi, function(matches) {
  170. var val = parts[matches.replace(/[{}]/g, "")] || "";
  171. valid = val !== "";
  172. return val;
  173. });
  174. return valid ? url : "";
  175. },
  176.  
  177. removeElms = function(src, selector) {
  178. var links = src.querySelectorAll(selector),
  179. len = links.length;
  180. while(len--) {
  181. src.removeChild(links[len]);
  182. }
  183. },
  184.  
  185. addHotkeys = function(parts, scope, hotkeys) {
  186. // Shhh, don't tell anyone, but GitHub checks the data-hotkey attribute
  187. // of any link on the page, so we only need to add dummy links :P
  188. var indx, url, key, link,
  189. len = hotkeys.length,
  190. body = document.querySelector("body");
  191. for (indx = 0; indx < len; indx++) {
  192. key = Object.keys(hotkeys[indx])[0];
  193. url = fixUrl(parts, hotkeys[indx][key]);
  194. if (url) {
  195. link = document.createElement("a");
  196. link.className = "ghch-link";
  197. link.href = url;
  198. link.setAttribute("data-hotkey", key);
  199. body.appendChild(link);
  200. debug("Adding '" + key + "' keyboard hotkey linked to: " + url);
  201. }
  202. }
  203. },
  204.  
  205. addHotkey = function(el) {
  206. var li = document.createElement("li");
  207. li.className = "ghch-hotkey-set";
  208. li.innerHTML = templates.hotkey + templates.remove;
  209. el.parentNode.insertBefore(li, el);
  210. return li;
  211. },
  212.  
  213. addScope = function(el) {
  214. var scope = document.createElement("fieldset");
  215. scope.className = "ghch-scope-custom";
  216. scope.innerHTML = "<legend><span class='simple-box' contenteditable>Enter Scope</span>&nbsp;" +
  217. templates.remove +
  218. "</legend>" +
  219. templates.scope;
  220. el.parentNode.insertBefore(scope, el);
  221. return scope;
  222. },
  223.  
  224. addMenu = function() {
  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.in { 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.in { 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. ].join(""));
  245.  
  246. // add menu
  247. var tmp,
  248. inner = [
  249. "<div id='ghch-settings-inner' class='boxed-group'>",
  250. "<h3>",
  251. "GitHub Custom Hotkey Settings",
  252. "<button type='button' class='btn btn-sm ghch-close tooltipped tooltipped-n' aria-label='Close';>" + templates.remove + "</button>",
  253. "<button type='button' class='ghch-code btn btn-sm tooltipped tooltipped-n' aria-label='Toggle JSON data view'>{ }</button>",
  254. "<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>",
  255. "</h3>",
  256. "<div class='ghch-menu-inner boxed-group-inner'>",
  257. "<fieldset class='ghch-scope-all'>",
  258. "<legend><span class='simple-box' data-scope='all'>All of GitHub &amp; subdomains</span></legend>",
  259. templates.scope,
  260. "</fieldset>",
  261. "<div class='ghch-scope-add'>+ Click to add a new scope</div>",
  262. "<textarea class='ghch-json-code'></textarea>",
  263. "</div>",
  264. "</div>"
  265. ].join(""),
  266.  
  267. menu = document.createElement("div");
  268. menu.id = "ghch-menu";
  269. menu.innerHTML = inner;
  270. document.querySelector("body").appendChild(menu);
  271. // Create our menu entry
  272. menu = document.createElement("a");
  273. menu.id = "ghch-open-menu";
  274. menu.className = "dropdown-item";
  275. menu.innerHTML = "GitHub Hotkey Settings";
  276.  
  277. tmp = document.querySelectorAll(".header .dropdown-item[href='/settings/profile'], .header .dropdown-item[data-ga-click*='go to profile']");
  278. if (tmp) {
  279. tmp[tmp.length - 1].parentNode.insertBefore(menu, tmp[tmp.length - 1].nextSibling);
  280. }
  281. addBindings();
  282. },
  283.  
  284. openPanel = function() {
  285. updateMenu();
  286. document.querySelector("#ghch-menu").classList.add("in");
  287. return false;
  288. },
  289.  
  290. closePanel = function() {
  291. var menu = document.querySelector("#ghch-menu");
  292. if (menu.classList.contains("in")) {
  293. // update data in case a "change" event didn't fire
  294. refreshData();
  295. checkScope();
  296. menu.classList.remove("in");
  297. menu.querySelector(".ghch-json-code").classList.remove("in");
  298. window.location.hash = "";
  299. return false;
  300. }
  301. },
  302.  
  303. addJSON = function() {
  304. var textarea = document.querySelector(".ghch-json-code");
  305. textarea.value = JSON
  306. .stringify(data, null, 2)
  307. // compress JSON a little
  308. .replace(/\n \}/g, " }")
  309. .replace(/\{\n /g, "{ ");
  310. },
  311.  
  312. processJSON = function() {
  313. var val,
  314. textarea = document.querySelector(".ghch-json-code"),
  315. txt = textarea.value;
  316. try {
  317. val = JSON.parse(txt);
  318. data = val;
  319. } catch (err) {}
  320. },
  321.  
  322. updateMenu = function() {
  323. var indx, len, hotkeys, key, scope, tmp, target, selector,
  324. menu = document.querySelector(".ghch-menu-inner");
  325. removeElms(menu, ".ghch-scope-custom");
  326. removeElms(menu.querySelector(".ghch-scope-all ul"), ".ghch-hotkey-set");
  327. // Add scopes
  328. for (key in data) {
  329. if (data.hasOwnProperty(key)) {
  330. if (key === "all") {
  331. selector = "all";
  332. scope = menu.querySelector(".ghch-scope-all .ghch-hotkey-add");
  333. } else if (key !== selector) {
  334. selector = key;
  335. scope = addScope(document.querySelector(".ghch-scope-add"));
  336. scope.querySelector("legend span").innerHTML = key;
  337. scope = scope.querySelector(".ghch-hotkey-add");
  338. }
  339. // add hotkey entries
  340. hotkeys = data[key];
  341. len = hotkeys.length;
  342. for (indx = 0; indx < len; indx++) {
  343. target = addHotkey(scope);
  344. tmp = Object.keys(hotkeys[indx])[0];
  345. target.querySelector(".ghch-hotkey").value = tmp;
  346. target.querySelector(".ghch-url").value = hotkeys[indx][tmp];
  347. }
  348. }
  349. }
  350. },
  351.  
  352. refreshData = function() {
  353. var tmp, scope, scopes, sIndx, sLen, hotkeys, scIndx, scLen, val,
  354. menu = document.querySelector(".ghch-menu-inner");
  355. data = {};
  356. scopes = menu.querySelectorAll("fieldset");
  357. sLen = scopes.length;
  358. for (sIndx = 0; sIndx < sLen; sIndx++) {
  359. tmp = scopes[sIndx].querySelector("legend span");
  360. if (tmp) {
  361. scope = tmp.getAttribute("data-scope") || tmp.textContent.trim();
  362. hotkeys = scopes[sIndx].querySelectorAll(".ghch-hotkey-set");
  363. scLen = hotkeys.length;
  364. data[scope] = [];
  365. for (scIndx = 0; scIndx < scLen; scIndx++) {
  366. tmp = hotkeys[scIndx].querySelectorAll("input");
  367. val = tmp[0] && tmp[0].value || "";
  368. if (val) {
  369. data[scope][scIndx] = {};
  370. data[scope][scIndx][val] = tmp[1].value || "";
  371. }
  372. }
  373. }
  374. }
  375. GM_setValue("github-hotkeys", data);
  376. debug("Data refreshed", data);
  377. },
  378.  
  379. lastHref = window.location.href,
  380. addBindings = function() {
  381. var tmp,
  382. menu = document.querySelector("#ghch-menu");
  383.  
  384. // open menu
  385. document.querySelector("#ghch-open-menu").addEventListener("click", openPanel);
  386. // close menu
  387. menu.addEventListener("click", closePanel);
  388. document.querySelector("body").addEventListener("keydown", function(event) {
  389. if (event.which === 27) {
  390. closePanel();
  391. }
  392. });
  393. // stop propagation
  394. menu.querySelector("#ghch-settings-inner").addEventListener("keydown", function(event) {
  395. event.stopPropagation();
  396. });
  397. menu.querySelector("#ghch-settings-inner").addEventListener("click", function(event) {
  398. event.stopPropagation();
  399. var target = event.target;
  400. // add hotkey
  401. if (target.classList.contains("ghch-hotkey-add")) {
  402. addHotkey(target);
  403. } else if (target.classList.contains("ghch-scope-add")) {
  404. addScope(target);
  405. }
  406. // svg & path nodeName may be lowercase
  407. tmp = target.nodeName.toLowerCase();
  408. if (tmp === "path") {
  409. target = target.parentNode;
  410. }
  411. // target should now point at svg
  412. if (target.classList.contains("ghch-remove")) {
  413. tmp = target.parentNode;
  414. // remove fieldset
  415. if (tmp.nodeName === "LEGEND") {
  416. tmp = tmp.parentNode;
  417. }
  418. // remove li; but not the button in the header
  419. if (tmp.nodeName !== "BUTTON") {
  420. tmp.parentNode.removeChild(tmp);
  421. refreshData();
  422. }
  423. }
  424. });
  425. menu.addEventListener("change", refreshData);
  426. // contenteditable scope title
  427. menu.addEventListener("input", function(event) {
  428. if (event.target.classList.contains("simple-box")) {
  429. refreshData();
  430. }
  431. });
  432. menu.querySelector("button.ghch-close").addEventListener("click", closePanel);
  433. // open JSON code textarea
  434. tmp = menu.querySelector(".ghch-code");
  435. tmp.addEventListener("click", function() {
  436. menu.querySelector(".ghch-json-code").classList.toggle("in");
  437. addJSON();
  438. });
  439. // close JSON code textarea
  440. tmp = menu.querySelector(".ghch-json-code");
  441. tmp.addEventListener("focus", function() {
  442. this.select();
  443. });
  444. tmp.addEventListener("paste", function() {
  445. setTimeout(function() {
  446. processJSON();
  447. updateMenu();
  448. document.querySelector(".ghch-json-code").classList.remove("in");
  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(function() {
  455. var 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. // include a "debug" anywhere in the browser URL (search parameter) to enable debugging
  468. debug = function() {
  469. if (/debug/.test(window.location.search)) {
  470. console.log.apply(console, arguments);
  471. }
  472. };
  473.  
  474. // initialize
  475. checkScope();
  476. addMenu();
  477.  
  478. })();