Skip to content

Instantly share code, notes, and snippets.

@kiliman
Last active September 25, 2023 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiliman/5d7a3826bc16f5967978336d026805a3 to your computer and use it in GitHub Desktop.
Save kiliman/5d7a3826bc16f5967978336d026805a3 to your computer and use it in GitHub Desktop.
TamperMonkey script to open the npm package by Ctrl/Cmd+click on import statement from GitHub code view
// ==UserScript==
// @name GitHub open npm from import
// @namespace http://tampermonkey.net/
// @version 0.1.1
// @description Opens the npm package by Ctrl/Cmd+click on import statement
// @author Kiliman
// @match https://github.com/*
// @icon https://www.google.com/s2/favicons?domain=github.com
// @grant none
// ==/UserScript==
(function () {
"use strict";
function handleClick(e) {
// only process ctrl/cmd clicks
if (!(e.ctrlKey || e.metaKey)) return
const { srcElement, offsetX, offsetY } = e
// get first line
const reactLine = document.querySelector('.react-code-line-contents')
const lineHeight = reactLine?.getBoundingClientRect().height ?? 21.594
const code = srcElement.value.split('\n')
const lineNumber = parseInt(offsetY / lineHeight)
const line = code[lineNumber]
//console.log({ offsetY, lineHeight, lineNumber, line })
const match = line.match(/from\s+["'](.+)["']/)
if (!match) return
const packageName = match[1]
if (packageName.startsWith('.')) {
// navigate to local module
const newPath = new URL(packageName, document.location)
const branch = newPath.pathname.match(/\/blob\/(\w+)\//)[1]
const branchPrefix = `/blob/${branch}/`
// get path relative to ../blob/branch/
const ghPath = newPath.pathname.substring(newPath.pathname.indexOf(branchPrefix) + branchPrefix.length)
// find github file tree li based on path (we use prefix ^= since we don't know the extension
const li = document.querySelector(`li.PRIVATE_TreeView-item[id^="${ghPath}"]`)
if (li) {
// get text span so we can "click" it to navigate
const span = li.querySelector('span.PRIVATE_TreeView-item-content-text>span')
span.click()
}
return
}
// only process imports from node_modules
// starts with @ or letter
if (!/^[@a-z]/.test(packageName)) return
window.open(`https://www.npmjs.com/package/${packageName}`, '_blank')
}
document.addEventListener('click', handleClick)
})();
@kiliman
Copy link
Author

kiliman commented Jul 20, 2023

Added support for local modules to navigate in the github code editor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment