// ==UserScript== // @name GitHub Useful Forks // @namespace Violentmonkey Scripts // @version 1.1 // @author bethro // @license MIT // @icon https://useful-forks.github.io/assets/useful-forks-logo.png // @description Adds a button to GitHub repositories to see useful forks of the repo. // @homepage https://github.com/bethropolis/useful-forks // @homepageURL https://github.com/bethropolis/useful-forks // @supportURL https://github.com/bethropolis/useful-forks/issues // @match https://github.com/*/* // @grant none // @downloadURL https://update.greasyfork.icu/scripts/496406/GitHub%20Useful%20Forks.user.js // @updateURL https://update.greasyfork.icu/scripts/496406/GitHub%20Useful%20Forks.meta.js // ==/UserScript== (function() { 'use strict'; const UF_LI_ID = "useful_forks_li"; const UF_BTN_ID = "useful_forks_btn"; const UF_TIP_ID = "useful_forks_tooltip"; function getRepoUrl() { const pathComponents = window.location.pathname.split("/"); const user = pathComponents[1], repo = pathComponents[2]; return `https://useful-forks.github.io/?repo=${user}/${repo}`; } function setBtnUrl() { const button = document.getElementById(UF_BTN_ID); button.addEventListener("click", () => { window.open(getRepoUrl(), "_blank"); }); } function createUsefulBtn() { const li = document.createElement("li"); const content = `
Search for useful forks in a new tab
`; li.innerHTML = content; li.id = UF_LI_ID; return li; } function init() { // This is required for some cases like on Back/Forward navigation const oldLi = document.getElementById(UF_LI_ID); if (oldLi) { oldLi.remove(); } const forkBtn = document.getElementById("repo-network-counter"); if (forkBtn) { // sufficient to know the user is looking at a repository const forksAmount = forkBtn.textContent; if (forksAmount < 1) { return; } const parentLi = forkBtn.closest("li"); const newLi = createUsefulBtn(); parentLi.parentNode.insertBefore(newLi, parentLi); setBtnUrl(); // this needs to happen after the btn is inserted in the DOM } } init(); // entry point of the script /* Without a timeout, the Back/Forward browser navigation ends up messing up the JavaScript onClick event assigned to the button. The trade-off here is that the button appears a bit after the page loads. Moreover, it's worth pointing out that a MutationObserver is required here because GitHub does some optimizations that do not require reloading an entire page. PJax is one of those tricks used, but it does not seem to be exclusive, hence why `document.addEventListener("pjax:end", init);` is not sufficient. */ let timeout; const observer = new MutationObserver(() => { clearTimeout(timeout); timeout = setTimeout(init, 10); }); /* `subtree: false` is used to reduce the amount of callbacks triggered. `document.body` may be of narrower scope, but I couldn't figure it out. */ observer.observe(document.body, { childList: true, subtree: false }); })();