Created
April 30, 2024 05:36
-
-
Save foriequal0/1b4faa1e6c405c1bb2dac5031fba0a12 to your computer and use it in GitHub Desktop.
Scroll to current file for GitHub
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Scroll to current file for GitHub | |
// @match https://github.com/* | |
// @version 1.0 | |
// ==/UserScript== | |
function check(callback) { | |
const result = callback(); | |
if (!result) { | |
throw new Error("assertion Failed: "+ callback.toString()); | |
} | |
return result; | |
} | |
function getRefName() { | |
const embeddedData = check(() => document.querySelector('script[data-target="react-app.embeddedData"]')); | |
const obj = JSON.parse(embeddedData.text); | |
const refName = check(() => obj?.payload?.refInfo?.name); | |
return refName; | |
} | |
function trimPrefix(str, prefix) { | |
check(() => str.startsWith(prefix)); | |
return str.substring(prefix.length); | |
} | |
function scrollToCurrentFile() { | |
const pathname = location.pathname; | |
const [_empty, _owner, _repo, type, ...rest] = pathname.split("/"); | |
if (type != "blob" && type != "tree") { | |
return; | |
} | |
const restPath = rest.join("/"); | |
const refName = getRefName(); | |
const filePath = trimPrefix(restPath, refName); | |
if (!filePath) { | |
return; | |
} | |
const relativePath = trimPrefix(filePath, "/"); | |
const item = document.getElementById(`${relativePath}-item`); | |
item?.scrollIntoView({ block: "center", behavior: 'smooth' }); | |
} | |
// After page load | |
window.addEventListener("turbo:load", scrollToCurrentFile); | |
// File tree click | |
document.addEventListener("soft-nav:end", scrollToCurrentFile); | |
// Window resize | |
let handle = null; | |
window.addEventListener("resize", function () { | |
// debounced resize handle | |
if (handle != null) { | |
clearTimeout(handle); | |
} | |
handle = setTimeout(function() { | |
handle = null; | |
scrollToCurrentFile(); | |
}, 200); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment