diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d0af737..6af9227 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -109,7 +109,7 @@ jobs: uses: mnao305/chrome-extension-upload@v5.0.0 with: file-path: github-loc.zip - extension-id: clfbbldiigihjkignlkngblahkpalmhh + extension-id: bdjkkjhffigoaeinkkpipfhjdccimecc client-id: ${{ secrets.CLIENT_ID }} client-secret: ${{ secrets.CLIENT_SECRET }} refresh-token: ${{ secrets.REFRESH_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 1634cf7..beda0f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] +### Fixed + +- LOC stat not showing after GitHub's repository page redesign, or showing up in wrong places like PR contents. The stat is now anchored to the repository's forks stat and cloned from it, so it matches GitHub's current styling in both narrow and wide layouts + ## [1.0.8] - 2026-09-16 ### Fixed diff --git a/README.md b/README.md index 0543ef4..5545865 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ # GitHub LOC -Simple yet elegant Google Chrome extension that allows you to view Lines Of Code of both public and private GitHub repositories with an option to exclude selected languages. Clicking on the stat will take you to the [ghloc.vercel.app](https://ghloc.vercel.app/DervexDev/github-loc) page with even more LOC details. Get the extension from the Chrome Web Store [here](https://chromewebstore.google.com/detail/github-loc/clfbbldiigihjkignlkngblahkpalmhh). +Simple yet elegant Google Chrome extension that allows you to view Lines Of Code of both public and private GitHub repositories with an option to exclude selected languages. Clicking on the stat will take you to the [ghloc.vercel.app](https://ghloc.vercel.app/DervexDev/github-loc) page with even more LOC details. Get the extension from the Chrome Web Store [here](https://chromewebstore.google.com/detail/git-loc/bdjkkjhffigoaeinkkpipfhjdccimecc). ## Extension In Action diff --git a/public/store/demo1.png b/public/store/demo1.png new file mode 100644 index 0000000..774ba9c Binary files /dev/null and b/public/store/demo1.png differ diff --git a/public/store/demo2.png b/public/store/demo2.png new file mode 100644 index 0000000..183da2a Binary files /dev/null and b/public/store/demo2.png differ diff --git a/public/store/demo3.png b/public/store/demo3.png new file mode 100644 index 0000000..cb8f16b Binary files /dev/null and b/public/store/demo3.png differ diff --git a/src/stat/Stat.tsx b/src/stat/Stat.tsx deleted file mode 100644 index ead23dd..0000000 --- a/src/stat/Stat.tsx +++ /dev/null @@ -1,46 +0,0 @@ -interface Props { - org: string - repo: string - branch: string - isPrivate: boolean -} - -function publicHref(org: string, repo: string, branch: string) { - return `https://ghloc.vercel.app/${org}/${repo}${ - branch ? `?branch=${encodeURIComponent(branch)}` : "" - }` -} - -function privateHref(org: string, repo: string, branch: string) { - const url = new URL(chrome.runtime.getURL("src/details/index.html")) - url.searchParams.set("org", org) - url.searchParams.set("repo", repo) - if (branch) { - url.searchParams.set("branch", branch) - } - return url.toString() -} - -export default function Stat({ org, repo, branch, isPrivate }: Props) { - return ( - - - - - - {" "} - 0 lines of code - - ) -} diff --git a/src/stat/index.ts b/src/stat/index.ts index b4adf66..e8daef9 100644 --- a/src/stat/index.ts +++ b/src/stat/index.ts @@ -1,127 +1,166 @@ import "./stat.css" -import { locateRoot, injectStat, updateStat, updateLink, findAboutRoot, STAT_ID } from "./injector" +import { isPrivateRepository, removeStats, StatState, syncStats } from "./injector" import { filterTree } from "../details/tree" import { fetchLoc, LocData, loadLoc } from "./loader" -import { getTarget, getFilter, loadMatchFilter, now } from "./util" -import Stat from "./Stat" +import { getTarget, isRepoHomePath, loadMatchFilter, now } from "./util" const FETCH_RATE_LIMIT = 10 * 60 -const NAV_EVENTS = ["turbo:load", "turbo:render", "popstate"] as const +const NAV_EVENTS = ["turbo:load", "turbo:render", "popstate", "pageshow"] as const +const PLACEHOLDER = "…" + +interface Current { + key: string + org: string + repo: string + branch: string + isPrivate: boolean + filter: string + locData: LocData | null +} +let current: Current | null = null let runId = 0 -let lastTarget = "" -let debounceTimer: ReturnType | undefined -let missingTimer: ReturnType | undefined +let syncTimer: ReturnType | undefined +let pendingForce = false + +function publicHref(org: string, repo: string, branch: string, filter: string) { + const url = new URL(`https://ghloc.vercel.app/${org}/${repo}`) + if (branch) { + url.searchParams.set("branch", branch) + } + if (filter) { + url.searchParams.set("filter", filter) + } + return url.toString() +} -function targetKey(org: string, repo: string, branch: string) { - return `${org}/${repo}/${branch}` +function privateHref(org: string, repo: string, branch: string) { + const url = new URL(chrome.runtime.getURL("src/details/index.html")) + url.searchParams.set("org", org) + url.searchParams.set("repo", repo) + if (branch) { + url.searchParams.set("branch", branch) + } + return url.toString() } -async function showLoc(stat: Element, locData: LocData, id: number) { - const filter = await loadMatchFilter() +function stateOf(target: Current): StatState { + const { org, repo, branch, isPrivate, filter, locData } = target + + return { + href: isPrivate ? privateHref(org, repo, branch) : publicHref(org, repo, branch, filter), + isPrivate, + value: locData ? filterTree(locData, filter).loc.toLocaleString() : PLACEHOLDER, + } +} + +async function load(target: Current, id: number) { + const { org, repo, branch } = target + + target.filter = await loadMatchFilter() if (id !== runId) { return } - updateStat(stat, filterTree(locData, filter).loc) -} + const cached = await loadLoc(org, repo, branch) + if (id !== runId) { + return + } + + if (cached) { + target.locData = cached + render() -function main() { - locateRoot().then(([root, isPrivate]) => { - const [org, repo, branch] = getTarget() - if (!org || !repo) { + if (now() - cached.lastFetched < FETCH_RATE_LIMIT) { return } + } - const key = targetKey(org, repo, branch) - if (root.querySelector(`#${STAT_ID}`) && lastTarget === key) { - return + try { + const fresh = await fetchLoc(org, repo, branch) + if (id === runId) { + target.locData = fresh + render() } + } catch (err) { + console.log("Failed to fetch LOC:", err) + } +} + +function render() { + if (current) { + syncStats(current.org, current.repo, stateOf(current)) + } +} + +function sync(force = false) { + if (!isRepoHomePath(location.pathname)) { + current = null + runId++ + removeStats() + return + } + + const [org, repo, branch] = getTarget() + const key = `${org}/${repo}/${branch}` - lastTarget = key + if (force || !current || current.key !== key) { const id = ++runId - const statJSX = Stat({ + current = { + key, org, repo, branch, - isPrivate, - }) - - const stat = injectStat(root, statJSX) - - loadLoc(org, repo, branch).then((locData) => { - if (id !== runId) { - return - } - - if (!isPrivate) { - getFilter().then((filter) => { - if (id === runId) { - updateLink(stat, filter) - } - }) - } - - if (locData) { - showLoc(stat, locData, id) - - if (now() - locData.lastFetched < FETCH_RATE_LIMIT) { - return - } - } - - fetchLoc(org, repo, branch) - .then((locData) => { - if (id !== runId) { - return - } - - showLoc(stat, locData, id) - }) - .catch((err) => { - console.log("Failed to fetch LOC:", err) - }) - }) - }) + isPrivate: isPrivateRepository(), + filter: "", + locData: null, + } + + load(current, id) + } + + render() } -function requestUpdate() { - clearTimeout(debounceTimer) - debounceTimer = setTimeout(main, 50) +// Throttled rather than debounced, so a page that keeps mutating +// (e.g. live timestamps) cannot postpone the sync indefinitely. +function requestSync(force = false) { + pendingForce ||= force + if (syncTimer !== undefined) { + return + } + + syncTimer = setTimeout(() => { + const forced = pendingForce + syncTimer = undefined + pendingForce = false + sync(forced) + }, 50) } chrome.runtime.onMessage.addListener((message) => { if (message === "github-loc:update") { - lastTarget = "" - requestUpdate() + requestSync() } }) -for (const event of NAV_EVENTS) { - window.addEventListener(event, () => { - lastTarget = "" - requestUpdate() - }) -} - -window.addEventListener("pageshow", (event) => { - if (event.persisted) { - lastTarget = "" - requestUpdate() +chrome.storage.onChanged.addListener((changes, area) => { + if (area === "sync" && (changes.ignoredFiles || changes.accessToken)) { + requestSync(true) } }) -new MutationObserver(() => { - clearTimeout(missingTimer) - missingTimer = setTimeout(() => { - if (document.getElementById(STAT_ID) || !findAboutRoot()) { - return - } +for (const event of NAV_EVENTS) { + window.addEventListener(event, () => requestSync()) +} - lastTarget = "" - main() - }, 50) -}).observe(document.documentElement, { childList: true, subtree: true }) +// GitHub renders (and re-renders) the sidebar client-side, so watch the DOM +// and re-sync whenever the stat goes missing, gets duplicated or the URL +// changes. Syncing is idempotent, so our own DOM changes settle immediately. +new MutationObserver(() => requestSync()).observe(document.documentElement, { + childList: true, + subtree: true, +}) -main() +sync() diff --git a/src/stat/injector.ts b/src/stat/injector.ts index 6f71d6d..5793e14 100644 --- a/src/stat/injector.ts +++ b/src/stat/injector.ts @@ -1,9 +1,57 @@ -import { JSX, render } from "preact" - -export const STAT_ID = "github-loc" +/** + * Locates the repository's "forks" stat in the About sidebar and injects a + * "lines of code" stat right below it. + * + * Instead of depending on GitHub's (frequently changing, often hashed) class + * names or on the sidebar's exact structure, we: + * + * 1. find the link that points to this exact repository's `/forks` page and + * carries the `repo-forked` octicon - this is the forks stat in the sidebar, + * 2. skip anything inside user content (README, PR/issue bodies, comments), + * 3. deep-clone the forks stat and rewrite its icon, number and label. + * + * Cloning means our stat inherits whatever markup and classes GitHub currently + * uses, so it keeps looking like the other stats across redesigns. GitHub + * renders the About section twice (narrow and wide layouts), so every matching + * forks stat gets its own copy. + */ + +export const STAT_ATTR = "data-github-loc" +const VALUE_ATTR = "data-github-loc-value" +const SVG_NS = "http://www.w3.org/2000/svg" + +// Containers holding user-generated content (markdown, comments, PR bodies) +// or transient UI, where a "forks" link must never be treated as the stat. +const EXCLUDED_CONTAINERS = [ + ".markdown-body", + ".comment-body", + ".js-comment", + ".timeline-comment", + "[data-testid='markdown-body']", + "[data-testid='issue-body']", + "[data-testid='comment-body']", + "article", + "dialog", + "[role='dialog']", + "[role='menu']", + "[role='tooltip']", + "[popover]", +].join(",") + +const ICON_PATHS = [ + "M5.75,13.29L8.89,2.32L10.23,2.71L7.08,13.67Z", + "M2.06,8l2.27-2.27c.27-.27.27-.71,0-.98-.27-.27-.71-.27-.98,0L.59,7.5c-.14.14-.2.32-.2.5,0,.18.07.36.2.5l2.76,2.76c.27.27.71.27.98,0h0c.27-.27.27-.71,0-.98l-2.27-2.27Z", + "M13.94,8l-2.27-2.27c-.27-.27-.27-.71,0-.98.27-.27.71-.27.98,0l2.76,2.76c.14.14.2.32.2.5,0,.18-.07.36-.2.5l-2.76,2.76c-.27.27-.71.27-.98,0h0c-.27-.27-.27-.71,0-.98l2.27-2.27Z", +] const PRIVATE_VISIBILITY = new Set(["Private", "Internal"]) +export interface StatState { + href: string + isPrivate: boolean + value: string +} + export function isPrivateRepository() { const publicMeta = document .querySelector('meta[name="octolytics-dimension-repository_public"]') @@ -16,8 +64,10 @@ export function isPrivateRepository() { return false } - const header = document.getElementById("repository-container-header") - for (const label of header?.querySelectorAll(".Label") ?? []) { + const labels = document.querySelectorAll( + '[data-testid="repo-visibility-label"], #repository-container-header .Label, #repo-title-component .Label, #repo-title-component span', + ) + for (const label of labels) { const text = label.textContent?.trim() if (text && PRIVATE_VISIBILITY.has(text)) { return true @@ -27,88 +77,176 @@ export function isPrivateRepository() { } } - const legacyVisibility = document - .evaluate( - '//*[@id="repo-title-component"]/span[2]', - document, - null, - XPathResult.FIRST_ORDERED_NODE_TYPE, - null, - ) - .singleNodeValue?.textContent?.trim() - - return !!legacyVisibility && PRIVATE_VISIBILITY.has(legacyVisibility) + return false } -export function findAboutRoot(): HTMLElement | null { - return ( - (document.evaluate( - '//h2[normalize-space(.)="About" and not(@class="heading-element")]', - document, - null, - XPathResult.FIRST_ORDERED_NODE_TYPE, - null, - ).singleNodeValue?.parentElement as HTMLElement | null) ?? null - ) +function normalizePath(path: string) { + return path.replace(/\/+$/, "").toLowerCase() } -let locateObserver: MutationObserver | undefined -let locateGeneration = 0 +/** Returns the elements wrapping each forks stat of the given repository. */ +export function findForkItems(org: string, repo: string): HTMLElement[] { + const forksPath = normalizePath(`/${org}/${repo}/forks`) + const items: HTMLElement[] = [] -export function locateRoot(): Promise<[HTMLElement, boolean]> { - const generation = ++locateGeneration - locateObserver?.disconnect() - locateObserver = undefined + for (const link of document.querySelectorAll('a[href*="/forks"]')) { + if (link.host !== window.location.host || normalizePath(link.pathname) !== forksPath) { + continue + } + if (!link.querySelector("svg.octicon-repo-forked")) { + continue + } + if (link.closest(EXCLUDED_CONTAINERS) || link.closest(`[${STAT_ATTR}]`)) { + continue + } - return new Promise((resolve) => { - const tryLocate = () => { - if (generation !== locateGeneration) { - return true - } + // Stats are usually wrapped in their own row element (e.g. `div.mt-2`), + // clone that row so spacing matches. Fall back to the link itself. + const parent = link.parentElement + const item = parent && parent.childElementCount === 1 ? parent : link + items.push(item) + } - const root = findAboutRoot() - if (!root) { - return false - } + return items +} - locateObserver?.disconnect() - locateObserver = undefined - resolve([root, isPrivateRepository()]) - return true - } +function getLink(stat: HTMLElement) { + return stat instanceof HTMLAnchorElement ? stat : stat.querySelector("a") +} + +function textNodesOutside(root: Node, skip: Element[]) { + const nodes: Text[] = [] + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT) - if (!tryLocate()) { - locateObserver = new MutationObserver(tryLocate) - locateObserver.observe(document.documentElement, { childList: true, subtree: true }) + while (walker.nextNode()) { + const node = walker.currentNode as Text + if (!skip.some((el) => el.contains(node))) { + nodes.push(node) } - }) + } + + return nodes } -export function injectStat(root: Element, stat: JSX.Element) { - const existing = root.querySelector(`#${STAT_ID}`) - const div = existing ?? document.createElement("div") +function setIcon(svg: SVGElement) { + svg.classList.remove("octicon-repo-forked") + svg.classList.add("octicon-code") + svg.setAttribute("viewBox", "0 0 16 16") + svg.replaceChildren( + ...ICON_PATHS.map((d) => { + const path = document.createElementNS(SVG_NS, "path") + path.setAttribute("d", d) + return path + }), + ) +} - if (!existing) { - div.className = "mt-2" - div.id = STAT_ID +function createStat(forkItem: HTMLElement): HTMLElement | null { + const stat = forkItem.cloneNode(true) as HTMLElement + const link = getLink(stat) + if (!link) { + return null + } - if (root.lastElementChild?.firstElementChild?.textContent?.includes("Report")) { - root.insertBefore(div, root.lastElementChild) + stat.setAttribute(STAT_ATTR, "") + for (const el of [stat, ...stat.querySelectorAll("*")]) { + el.removeAttribute("id") + el.removeAttribute("data-discover") + el.removeAttribute("data-hovercard-url") + el.removeAttribute("data-pjax") + } + link.setAttribute("data-turbo", "false") + + let svg = link.querySelector("svg") + if (svg) { + setIcon(svg) + } + + let strong = link.querySelector("strong") + if (!strong) { + // Unknown structure - rebuild contents as: icon, number, label. + link.replaceChildren(...(svg ? [svg] : [])) + strong = document.createElement("strong") + link.append(strong, document.createTextNode(" lines of code")) + } else { + // Replace the "forks" label, keeping its wrapper elements and spacing. + const labels = textNodesOutside(link, [strong, ...(svg ? [svg] : [])]).filter((node) => + node.textContent?.trim(), + ) + + if (labels.length === 0) { + strong.after(document.createTextNode(" lines of code")) } else { - root.appendChild(div) + const [first, ...rest] = labels + const leading = /^\s/.test(first.textContent!) ? " " : "" + first.textContent = `${leading}lines of code` + rest.forEach((node) => (node.textContent = "")) } } - render(stat, div) + strong.setAttribute(VALUE_ATTR, "") - return div + return stat } -export function updateStat(stat: Element, value: number) { - stat.firstElementChild!.lastElementChild!.textContent = value.toLocaleString() +function applyState(stat: HTMLElement, state: StatState) { + const link = getLink(stat) + if (!link) { + return + } + + if (link.getAttribute("href") !== state.href) { + link.setAttribute("href", state.href) + } + + if (state.isPrivate) { + link.setAttribute("target", "_blank") + link.setAttribute("rel", "noopener") + } else { + link.removeAttribute("target") + link.removeAttribute("rel") + } + + const value = stat.querySelector(`[${VALUE_ATTR}]`) + if (value && value.textContent !== state.value) { + value.textContent = state.value + } } -export function updateLink(stat: Element, filter: string) { - const link = stat.firstElementChild!.getAttribute("href")! - stat.firstElementChild!.setAttribute("href", link + filter) +export function removeStats(keep: Set = new Set()) { + for (const stat of document.querySelectorAll(`[${STAT_ATTR}]`)) { + if (!keep.has(stat)) { + stat.remove() + } + } +} + +/** + * Makes sure there is exactly one stat right below every forks stat of the + * repository, all reflecting `state`. Removes stats anywhere else (e.g. left + * over after navigating away). Returns whether at least one stat is present. + */ +export function syncStats(org: string, repo: string, state: StatState): boolean { + const keep = new Set() + + for (const item of findForkItems(org, repo)) { + let stat = item.nextElementSibling as HTMLElement | null + + if (!stat?.hasAttribute(STAT_ATTR)) { + const created = createStat(item) + if (!created) { + continue + } + + stat = created + item.after(stat) + } + + applyState(stat, state) + keep.add(stat) + } + + removeStats(keep) + + return keep.size > 0 } diff --git a/src/stat/stat.css b/src/stat/stat.css index c399c06..6b08f16 100644 --- a/src/stat/stat.css +++ b/src/stat/stat.css @@ -1,5 +1,8 @@ -#github-loc a:focus, -#github-loc a:focus-visible, -#github-loc a:visited { +[data-github-loc] a:focus, +[data-github-loc] a:focus-visible, +[data-github-loc] a:visited, +a[data-github-loc]:focus, +a[data-github-loc]:focus-visible, +a[data-github-loc]:visited { text-decoration: none !important; } diff --git a/src/stat/util.ts b/src/stat/util.ts index f334e32..2d18ba6 100644 --- a/src/stat/util.ts +++ b/src/stat/util.ts @@ -36,18 +36,36 @@ export function getTarget() { return [path[1], path[2], branch] } -export function getFilter(): Promise { - return new Promise((resolve) => { - chrome.storage.sync.get("ignoredFiles").then((ignoredFiles) => { - if (Array.isArray(ignoredFiles.ignoredFiles)) { - let filter = "&filter=" - - ignoredFiles.ignoredFiles.forEach((ignored) => { - filter += "%21" + ignored + "%24%2C" // !md$, - }) - - resolve(filter.substring(0, filter.length - 3)) - } - }) - }) +// Reserved first path segments that are never a repository owner. +const NON_REPO_OWNERS = new Set([ + "orgs", + "settings", + "notifications", + "marketplace", + "topics", + "collections", + "explore", + "search", + "sponsors", + "login", + "logout", + "new", + "organizations", + "pulls", + "issues", + "codespaces", + "features", + "enterprise", + "about", + "pricing", +]) + +/** Whether the path is a repository's main page, the only one with the About sidebar. */ +export function isRepoHomePath(pathname: string) { + const path = pathname.split("/").filter(Boolean) + if (path.length < 2 || NON_REPO_OWNERS.has(path[0].toLowerCase())) { + return false + } + + return path.length === 2 || (path[2] === "tree" && path.length > 3) }