Skip to content

Instantly share code, notes, and snippets.

@fregante
Forked from kiliman/github-open-npm.js
Created August 10, 2024 15:53
Show Gist options
  • Save fregante/9ec6aedd28c307b4bb9eaed54bf21690 to your computer and use it in GitHub Desktop.
Save fregante/9ec6aedd28c307b4bb9eaed54bf21690 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)
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment