From 1b8a3684bddc379ece48c5dc8375789480ad6f83 Mon Sep 17 00:00:00 2001 From: shawn Date: Wed, 25 Nov 2026 10:20:56 +0800 Subject: [PATCH 1/2] feat: show diff stats in PR file trees --- src/_locales/en/messages.json | 4 + src/_locales/zh_CN/messages.json | 4 + src/_locales/zh_TW/messages.json | 4 + src/content.ts | 10 ++ src/features/pr-file-tree-diff-stats.ts | 173 ++++++++++++++++++++++++ src/options.test.ts | 1 + src/options.ts | 1 + src/styles/content.css | 21 +++ static/options.html | 15 ++ 9 files changed, 233 insertions(+) create mode 100644 src/features/pr-file-tree-diff-stats.ts diff --git a/src/_locales/en/messages.json b/src/_locales/en/messages.json index 6cb38b3..43234d6 100644 --- a/src/_locales/en/messages.json +++ b/src/_locales/en/messages.json @@ -113,6 +113,10 @@ "featPrApproveNowDesc": { "message": "Add an \"approve now\" shortcut to the Reviewers sidebar on PR detail pages. Requires a token." }, + "featPrFileTreeDiffStatsName": { "message": "File Tree Diff Stats" }, + "featPrFileTreeDiffStatsDesc": { + "message": "Show additions and deletions beside files in the PR file tree. Works with classic and preview pages. No token required." + }, "featPrCollapseExpandName": { "message": "Collapse/Expand All Files" }, "featPrCollapseExpandDesc": { "message": "Add a button to collapse or expand all file diffs on PR, commit, and compare pages." diff --git a/src/_locales/zh_CN/messages.json b/src/_locales/zh_CN/messages.json index b18e76d..793d34e 100644 --- a/src/_locales/zh_CN/messages.json +++ b/src/_locales/zh_CN/messages.json @@ -113,6 +113,10 @@ "featPrApproveNowDesc": { "message": "在 PR 详情页的 Reviewers 侧边栏添加「立即批准」快捷入口。需要令牌。" }, + "featPrFileTreeDiffStatsName": { "message": "文件树增删行数" }, + "featPrFileTreeDiffStatsDesc": { + "message": "在 PR 文件树的文件名旁显示新增和删除行数,支持经典版和预览版页面,无需 token。" + }, "featPrCollapseExpandName": { "message": "折叠/展开所有文件" }, "featPrCollapseExpandDesc": { "message": "在 PR、Commit 和对比页面添加一个折叠或展开所有文件差异的按钮。" diff --git a/src/_locales/zh_TW/messages.json b/src/_locales/zh_TW/messages.json index 096eac6..9d0d0a1 100644 --- a/src/_locales/zh_TW/messages.json +++ b/src/_locales/zh_TW/messages.json @@ -113,6 +113,10 @@ "featPrApproveNowDesc": { "message": "在 PR 詳情頁的 Reviewers 側邊欄新增「立即核准」快速入口。需要權杖。" }, + "featPrFileTreeDiffStatsName": { "message": "檔案樹增刪行數" }, + "featPrFileTreeDiffStatsDesc": { + "message": "在 PR 檔案樹的檔名旁顯示新增和刪除行數,支援經典版和預覽版頁面,無需 token。" + }, "featPrCollapseExpandName": { "message": "摺疊/展開所有檔案" }, "featPrCollapseExpandDesc": { "message": "在 PR、Commit 和比較頁面新增一個摺疊或展開所有檔案差異的按鈕。" diff --git a/src/content.ts b/src/content.ts index c965415..6f52ac1 100644 --- a/src/content.ts +++ b/src/content.ts @@ -8,6 +8,10 @@ import { } from "./features/pr-conflict-indicator"; import { injectPRReviewStatus } from "./features/pr-review-status"; import { injectPRDiffStats } from "./features/pr-diff-stats"; +import { + injectPRFileTreeDiffStats, + cleanupPRFileTreeDiffStats, +} from "./features/pr-file-tree-diff-stats"; import { injectReleasesTab } from "./features/release-tab"; import { cleanupReleaseAssetDownloads, @@ -34,6 +38,7 @@ const FEATURE_KEYS = [ "feature-pr-conflict-indicator", "feature-pr-review-status", "feature-pr-diff-stats", + "feature-pr-file-tree-diff-stats", "feature-release-tab", "feature-release-downloads-count", "feature-pr-label-position", @@ -51,6 +56,7 @@ type FeatureKey = (typeof FEATURE_KEYS)[number]; // CSS classes used by each feature's injected elements const FEATURE_CLASSES: Record = { + "feature-pr-file-tree-diff-stats": ["better-github-file-tree-diff-stats"], "feature-pr-branch-names": ["better-github-branch-badge", "bg-skeleton-pill--branch"], "feature-pr-conflict-indicator": ["better-github-conflict-indicator"], "feature-pr-review-status": ["better-github-review-status"], @@ -72,6 +78,7 @@ const FEATURE_CLASSES: Record = { // DOM run a cleanup hook on disable, before removeFeatureElements() strips their // elements by class. const FEATURE_CLEANUPS: Partial void>> = { + "feature-pr-file-tree-diff-stats": cleanupPRFileTreeDiffStats, "feature-pr-conflict-indicator": cleanupPRConflictIndicator, "feature-pr-label-position": cleanupPRLabelPosition, "feature-watch-fork-star-popup": cleanupWatchForkStarPopup, @@ -113,6 +120,9 @@ export function removeFeatureElements(key: FeatureKey): void { function injectFeature(key: FeatureKey): void { switch (key) { + case "feature-pr-file-tree-diff-stats": + injectPRFileTreeDiffStats(); + break; case "feature-pr-branch-names": injectPRBranchNames(); break; diff --git a/src/features/pr-file-tree-diff-stats.ts b/src/features/pr-file-tree-diff-stats.ts new file mode 100644 index 0000000..3e39616 --- /dev/null +++ b/src/features/pr-file-tree-diff-stats.ts @@ -0,0 +1,173 @@ +import { isPRFilesChangedPage } from "../lib/page-detect"; +import { buildDiffStatsBadge, type DiffStats } from "../lib/diff-stats-badge"; + +const BADGE_CLASS = "better-github-file-tree-diff-stats"; +const TREE_SELECTOR = '#pr-file-tree, [class*="PullRequestFileTree-module__sidebar"], file-tree'; +const HEADER_SELECTOR = '.js-file-header, [class*="diff-file-header"]'; +const DATA_SELECTOR = 'script[data-target="react-app.embeddedData"]'; +const RELEVANT_SELECTOR = `${TREE_SELECTOR}, ${HEADER_SELECTOR}, ${DATA_SELECTOR}`; + +let root: Element | null = null; +let observer: MutationObserver | null = null; +let frame: number | null = null; +let view = ""; +let source = ""; +let summariesValid = false; +const summaries = new Map(); +const renderedStats = new Map(); + +export function cleanupPRFileTreeDiffStats(): void { + observer?.disconnect(); + observer = null; + root = null; + if (frame !== null) cancelAnimationFrame(frame); + frame = null; + view = ""; + source = ""; + summariesValid = false; + summaries.clear(); + renderedStats.clear(); + document.querySelectorAll(`.${BADGE_CLASS}`).forEach((badge) => badge.remove()); +} + +function readSummaries(): void { + const script = document.querySelector(DATA_SELECTOR); + const text = script?.textContent ?? ""; + if (text === source) return; + source = text; + summaries.clear(); + summariesValid = false; + if (!text) return; + const initialPath = script?.closest("react-app")?.getAttribute("initial-path"); + if (initialPath !== view) return; + try { + const entries = JSON.parse(text).payload?.pullRequestsChangesRoute?.diffSummaries; + if (!Array.isArray(entries)) return; + for (const entry of entries) { + if ( + typeof entry.pathDigest !== "string" || + !Number.isInteger(entry.linesAdded) || + entry.linesAdded < 0 || + !Number.isInteger(entry.linesDeleted) || + entry.linesDeleted < 0 + ) + continue; + summaries.set(`#diff-${entry.pathDigest}`, { + additions: entry.linesAdded, + deletions: entry.linesDeleted, + changedFiles: null, + }); + } + summariesValid = true; + } catch { + // GitHub's embedded JSON is an external input; headers remain usable. + } +} + +function updateStats(): void { + if (!isPRFilesChangedPage()) { + cleanupPRFileTreeDiffStats(); + return; + } + const currentView = location.pathname + location.search; + if (view !== currentView) { + view = currentView; + summariesValid = false; + renderedStats.clear(); + } + readSummaries(); + + const headers = new Map(); + for (const header of document.querySelectorAll(HEADER_SELECTOR)) { + const anchor = header.getAttribute("data-anchor"); + const href = anchor + ? `#${anchor}` + : header.querySelector('a[href^="#diff-"]')?.getAttribute("href"); + if (!href) continue; + const match = [...header.querySelectorAll(".sr-only")] + .map((el) => el.textContent?.match(/([\d,]+) additions?\s*&\s*([\d,]+) deletions?/)) + .find(Boolean); + if (!match) continue; + const stats = { + additions: Number(match[1].replaceAll(",", "")), + deletions: Number(match[2].replaceAll(",", "")), + changedFiles: null, + }; + const initial = summaries.get(href); + if ( + summariesValid && + initial && + (initial.additions !== stats.additions || initial.deletions !== stats.deletions) + ) { + summariesValid = false; + renderedStats.clear(); + } + headers.set(href, stats); + } + for (const [href, stats] of headers) renderedStats.set(href, stats); + + for (const tree of document.querySelectorAll(TREE_SELECTOR)) { + for (const link of tree.querySelectorAll('a[href^="#diff-"]')) { + const href = link.getAttribute("href")!; + const stats = renderedStats.get(href) ?? (summariesValid ? summaries.get(href) : undefined); + const container = + link.closest(".PRIVATE_TreeView-item-content") ?? + link.querySelector(".ActionList-item-visual--trailing") ?? + link; + const existing = container.querySelector(`.${BADGE_CLASS}`); + if (!stats) { + existing?.remove(); + continue; + } + const key = `${stats.additions}:${stats.deletions}`; + if (existing?.dataset.stats === key) continue; + existing?.remove(); + const badge = buildDiffStatsBadge(stats, BADGE_CLASS); + badge.dataset.stats = key; + if (container.matches(".ActionList-item-visual--trailing")) container.prepend(badge); + else container.appendChild(badge); + } + } +} + +export function injectPRFileTreeDiffStats(): void { + if (!isPRFilesChangedPage()) { + cleanupPRFileTreeDiffStats(); + return; + } + const nextRoot = document.querySelector("main"); + if (root !== nextRoot) { + cleanupPRFileTreeDiffStats(); + root = nextRoot; + if (!root) return; + observer = new MutationObserver((mutations) => { + if (frame !== null) return; + const relevant = mutations.some((mutation) => { + const target = + mutation.target instanceof Element ? mutation.target : mutation.target.parentElement; + if (target?.closest(`.${BADGE_CLASS}`)) return false; + const nodes = [...mutation.addedNodes, ...mutation.removedNodes]; + if ( + nodes.length && + nodes.every((node) => node instanceof Element && node.matches(`.${BADGE_CLASS}`)) + ) + return false; + return ( + target?.closest(RELEVANT_SELECTOR) || + nodes.some( + (node) => + node instanceof Element && + (node.matches(RELEVANT_SELECTOR) || node.querySelector(RELEVANT_SELECTOR)), + ) + ); + }); + if (!relevant) return; + frame = requestAnimationFrame(() => { + frame = null; + updateStats(); + }); + }); + observer.observe(root, { childList: true, subtree: true, characterData: true }); + } + updateStats(); +} diff --git a/src/options.test.ts b/src/options.test.ts index 0714711..7f0ebb5 100644 --- a/src/options.test.ts +++ b/src/options.test.ts @@ -5,6 +5,7 @@ const FEATURE_KEYS = [ "feature-pr-conflict-indicator", "feature-pr-review-status", "feature-pr-diff-stats", + "feature-pr-file-tree-diff-stats", "feature-release-tab", "feature-release-downloads-count", "feature-pr-label-position", diff --git a/src/options.ts b/src/options.ts index d501838..206f2e4 100644 --- a/src/options.ts +++ b/src/options.ts @@ -29,6 +29,7 @@ const FEATURE_KEYS = [ "feature-pr-conflict-indicator", "feature-pr-review-status", "feature-pr-diff-stats", + "feature-pr-file-tree-diff-stats", "feature-release-tab", "feature-release-downloads-count", "feature-pr-label-position", diff --git a/src/styles/content.css b/src/styles/content.css index 38202b8..9305803 100644 --- a/src/styles/content.css +++ b/src/styles/content.css @@ -298,6 +298,27 @@ a.better-github-review-popover-item:hover { margin-top: 4px; } +.better-github-file-tree-diff-stats { + display: inline-flex; + flex-shrink: 0; + align-items: center; + gap: 4px; + margin-left: auto; + padding-left: 8px; + font-size: 11px; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +file-tree .ActionList-item-visual--trailing:has(> .better-github-file-tree-diff-stats) { + width: auto; + gap: 4px; +} + +file-tree a > .better-github-file-tree-diff-stats { + grid-area: trailingVisual; +} + .better-github-diff-stats-add { color: var(--fgColor-success, var(--color-success-fg, #1a7f37)); } diff --git a/static/options.html b/static/options.html index 18d452b..88e52b2 100644 --- a/static/options.html +++ b/static/options.html @@ -649,6 +649,21 @@

Settings

PR details
    +
  • +
    +
    + File Tree Diff Stats +
    +
    + Show additions and deletions beside files in the PR file tree. Works with classic and + preview pages. No token required. +
    +
    + +
  • PR Approve Now
    From 9daee5eb5913a76de4a07f99991aa7490f160f39 Mon Sep 17 00:00:00 2001 From: shawn Date: Wed, 25 Nov 2026 11:16:27 +0800 Subject: [PATCH 2/2] fix: show folder diff totals in the first three PR tree levels --- src/_locales/en/messages.json | 2 +- src/_locales/zh_CN/messages.json | 2 +- src/_locales/zh_TW/messages.json | 2 +- src/features/pr-file-tree-diff-stats.test.ts | 76 +++++++ src/features/pr-file-tree-diff-stats.ts | 197 ++++++++++--------- src/styles/content.css | 20 +- static/options.html | 4 +- 7 files changed, 197 insertions(+), 106 deletions(-) create mode 100644 src/features/pr-file-tree-diff-stats.test.ts diff --git a/src/_locales/en/messages.json b/src/_locales/en/messages.json index 43234d6..ff450ef 100644 --- a/src/_locales/en/messages.json +++ b/src/_locales/en/messages.json @@ -115,7 +115,7 @@ }, "featPrFileTreeDiffStatsName": { "message": "File Tree Diff Stats" }, "featPrFileTreeDiffStatsDesc": { - "message": "Show additions and deletions beside files in the PR file tree. Works with classic and preview pages. No token required." + "message": "Show additions and deletions beside folders in the first three levels of the PR file tree. Totals include all descendants." }, "featPrCollapseExpandName": { "message": "Collapse/Expand All Files" }, "featPrCollapseExpandDesc": { diff --git a/src/_locales/zh_CN/messages.json b/src/_locales/zh_CN/messages.json index 793d34e..48828cc 100644 --- a/src/_locales/zh_CN/messages.json +++ b/src/_locales/zh_CN/messages.json @@ -115,7 +115,7 @@ }, "featPrFileTreeDiffStatsName": { "message": "文件树增删行数" }, "featPrFileTreeDiffStatsDesc": { - "message": "在 PR 文件树的文件名旁显示新增和删除行数,支持经典版和预览版页面,无需 token。" + "message": "在 PR 文件树前三层目录的右侧显示增删行数,包含所有子目录的改动。" }, "featPrCollapseExpandName": { "message": "折叠/展开所有文件" }, "featPrCollapseExpandDesc": { diff --git a/src/_locales/zh_TW/messages.json b/src/_locales/zh_TW/messages.json index 9d0d0a1..bc7e292 100644 --- a/src/_locales/zh_TW/messages.json +++ b/src/_locales/zh_TW/messages.json @@ -115,7 +115,7 @@ }, "featPrFileTreeDiffStatsName": { "message": "檔案樹增刪行數" }, "featPrFileTreeDiffStatsDesc": { - "message": "在 PR 檔案樹的檔名旁顯示新增和刪除行數,支援經典版和預覽版頁面,無需 token。" + "message": "在 PR 檔案樹前三層目錄的右側顯示增刪行數,包含所有子目錄的變更。" }, "featPrCollapseExpandName": { "message": "摺疊/展開所有檔案" }, "featPrCollapseExpandDesc": { diff --git a/src/features/pr-file-tree-diff-stats.test.ts b/src/features/pr-file-tree-diff-stats.test.ts new file mode 100644 index 0000000..e6b117e --- /dev/null +++ b/src/features/pr-file-tree-diff-stats.test.ts @@ -0,0 +1,76 @@ +import { afterEach, expect, it } from "vitest"; +import { setUrl } from "../test-utils/url"; +import { cleanupPRFileTreeDiffStats, injectPRFileTreeDiffStats } from "./pr-file-tree-diff-stats"; + +const badge = ".better-github-file-tree-diff-stats"; +const path = "/owner/repo/pull/42/changes"; + +afterEach(() => { + cleanupPRFileTreeDiffStats(); + document.body.replaceChildren(); +}); + +it.each([ + [path, "pullRequestsChangesRoute"], + [path + "/abc", "pullRequestsChangesWithRangeRoute"], +])("totals nested files independently of the rendered diff on %s", (view, route) => { + setUrl("https://github.com" + view); + const data = { + payload: { + [route]: { + diffSummaries: [ + { path: "src/lib/generated/client/deep/a.ts", linesAdded: 4, linesDeleted: 1 }, + { path: "src/b.ts", linesAdded: 6, linesDeleted: 2 }, + { path: "src2/b.ts", linesAdded: 80, linesDeleted: 20 }, + ], + }, + }, + }; + const label = '
    name
    '; + document.body.innerHTML = `
    + +
    +
    `; + injectPRFileTreeDiffStats(); + const folder = document.getElementById("src")!; + expect(folder.querySelector(badge)?.textContent).toBe("+10−3"); + folder.setAttribute("aria-expanded", "true"); + folder.insertAdjacentHTML( + "beforeend", + `
    • ${label} +
      • ${label} +
        • ${label} +
          • ${label}
          +
        +
      +
    `, + ); + injectPRFileTreeDiffStats(); + expect([...folder.querySelectorAll(badge)].map((el) => el.textContent)).toEqual([ + "+10−3", + "+4−1", + "+4−1", + ]); + expect(document.getElementById("src/lib/generated/client/deep")!.querySelector(badge)).toBeNull(); + expect( + document.getElementById("src/lib/generated/client/deep/a.ts")!.querySelector(badge), + ).toBeNull(); +}); + +it("shows a classic folder total only when all its file headers are available", () => { + setUrl("https://github.com/owner/repo/pull/42/files"); + const header = (id: string) => `
    +
    2 additions & 1 deletion
    `; + document.body.innerHTML = `
    • + +
      • +
          ${["a", "b"].map((id) => `
        • ${id}
        • `).join("")}
        +
    ${header("a")}
    `; + injectPRFileTreeDiffStats(); + expect(document.querySelector(badge)).toBeNull(); + document.querySelector("main")!.insertAdjacentHTML("beforeend", header("b")); + injectPRFileTreeDiffStats(); + expect(document.querySelector(`button > ${badge}`)?.textContent).toBe("+4−2"); + expect(document.querySelectorAll(badge)).toHaveLength(1); + expect(document.querySelector(`a ${badge}`)).toBeNull(); +}); diff --git a/src/features/pr-file-tree-diff-stats.ts b/src/features/pr-file-tree-diff-stats.ts index 3e39616..89b3c7a 100644 --- a/src/features/pr-file-tree-diff-stats.ts +++ b/src/features/pr-file-tree-diff-stats.ts @@ -3,18 +3,16 @@ import { buildDiffStatsBadge, type DiffStats } from "../lib/diff-stats-badge"; const BADGE_CLASS = "better-github-file-tree-diff-stats"; const TREE_SELECTOR = '#pr-file-tree, [class*="PullRequestFileTree-module__sidebar"], file-tree'; -const HEADER_SELECTOR = '.js-file-header, [class*="diff-file-header"]'; +const DISPLAYED_LEVELS = ':is([aria-level="1"], [aria-level="2"], [aria-level="3"])'; +const HEADER_SELECTOR = ".js-file-header[data-anchor]"; const DATA_SELECTOR = 'script[data-target="react-app.embeddedData"]'; const RELEVANT_SELECTOR = `${TREE_SELECTOR}, ${HEADER_SELECTOR}, ${DATA_SELECTOR}`; let root: Element | null = null; let observer: MutationObserver | null = null; let frame: number | null = null; -let view = ""; -let source = ""; -let summariesValid = false; -const summaries = new Map(); -const renderedStats = new Map(); +let summarySource: Node | null = null; +const directoryTotals = new Map(); export function cleanupPRFileTreeDiffStats(): void { observer?.disconnect(); @@ -22,45 +20,100 @@ export function cleanupPRFileTreeDiffStats(): void { root = null; if (frame !== null) cancelAnimationFrame(frame); frame = null; - view = ""; - source = ""; - summariesValid = false; - summaries.clear(); - renderedStats.clear(); + summarySource = null; + directoryTotals.clear(); document.querySelectorAll(`.${BADGE_CLASS}`).forEach((badge) => badge.remove()); } -function readSummaries(): void { - const script = document.querySelector(DATA_SELECTOR); - const text = script?.textContent ?? ""; - if (text === source) return; - source = text; - summaries.clear(); - summariesValid = false; - if (!text) return; - const initialPath = script?.closest("react-app")?.getAttribute("initial-path"); - if (initialPath !== view) return; +function updateBadge(container: Element, stats?: DiffStats): void { + const existing = container.querySelector(`.${BADGE_CLASS}`); + if (!stats) { + existing?.remove(); + return; + } + const key = `${stats.additions}:${stats.deletions}`; + if (existing?.dataset.stats === key) return; + const badge = buildDiffStatsBadge(stats, BADGE_CLASS); + badge.dataset.stats = key; + if (existing) existing.replaceWith(badge); + else container.append(badge); +} + +function readDirectoryTotals(tree: Element): void { + const app = tree.closest("react-app"); + const currentView = location.pathname + location.search; + const source = + app?.getAttribute("initial-path") === currentView + ? (app.querySelector(DATA_SELECTOR)?.firstChild ?? null) + : null; + if (source === summarySource) return; + summarySource = source; + directoryTotals.clear(); + if (!source?.textContent) return; + + let entries; try { - const entries = JSON.parse(text).payload?.pullRequestsChangesRoute?.diffSummaries; - if (!Array.isArray(entries)) return; - for (const entry of entries) { - if ( - typeof entry.pathDigest !== "string" || - !Number.isInteger(entry.linesAdded) || - entry.linesAdded < 0 || - !Number.isInteger(entry.linesDeleted) || - entry.linesDeleted < 0 - ) - continue; - summaries.set(`#diff-${entry.pathDigest}`, { - additions: entry.linesAdded, - deletions: entry.linesDeleted, + const { payload } = JSON.parse(source.textContent); + const route = payload?.pullRequestsChangesWithRangeRoute ?? payload?.pullRequestsChangesRoute; + entries = route?.diffSummaries; + } catch { + return; + } + if (!Array.isArray(entries)) return; + for (const entry of entries) { + if ( + typeof entry?.path !== "string" || + !Number.isInteger(entry.linesAdded) || + !Number.isInteger(entry.linesDeleted) || + entry.linesAdded < 0 || + entry.linesDeleted < 0 + ) + return; + } + for (const { path, linesAdded, linesDeleted } of entries) { + for (let slash = path.indexOf("/"); slash >= 0; slash = path.indexOf("/", slash + 1)) { + const directory = path.slice(0, slash); + const total = directoryTotals.get(directory) ?? { + additions: 0, + deletions: 0, + changedFiles: null, + }; + total.additions += linesAdded; + total.deletions += linesDeleted; + directoryTotals.set(directory, total); + } + } +} + +function updateClassicTree(tree: Element): void { + const files = new Map(); + for (const header of document.querySelectorAll(HEADER_SELECTOR)) { + const match = header + .querySelector(".file-info .sr-only") + ?.textContent?.match(/([\d,]+) additions?\s*&\s*([\d,]+) deletions?/); + if (match) + files.set(`#${header.getAttribute("data-anchor")}`, { + additions: Number(match[1].replaceAll(",", "")), + deletions: Number(match[2].replaceAll(",", "")), changedFiles: null, }); + } + for (const folder of tree.querySelectorAll( + `[data-tree-entry-type="directory"]${DISPLAYED_LEVELS}`, + )) { + const button = folder.querySelector(":scope > button.ActionList-content"); + if (!button) continue; + const links = folder.querySelectorAll('[data-tree-entry-type="file"] > a[href^="#diff-"]'); + const total = { additions: 0, deletions: 0, changedFiles: null }; + let counted = 0; + for (const link of links) { + const stats = files.get(link.getAttribute("href")!); + if (!stats) break; + total.additions += stats.additions; + total.deletions += stats.deletions; + counted++; } - summariesValid = true; - } catch { - // GitHub's embedded JSON is an external input; headers remain usable. + updateBadge(button, counted && counted === links.length ? total : undefined); } } @@ -69,64 +122,18 @@ function updateStats(): void { cleanupPRFileTreeDiffStats(); return; } - const currentView = location.pathname + location.search; - if (view !== currentView) { - view = currentView; - summariesValid = false; - renderedStats.clear(); - } - readSummaries(); - - const headers = new Map(); - for (const header of document.querySelectorAll(HEADER_SELECTOR)) { - const anchor = header.getAttribute("data-anchor"); - const href = anchor - ? `#${anchor}` - : header.querySelector('a[href^="#diff-"]')?.getAttribute("href"); - if (!href) continue; - const match = [...header.querySelectorAll(".sr-only")] - .map((el) => el.textContent?.match(/([\d,]+) additions?\s*&\s*([\d,]+) deletions?/)) - .find(Boolean); - if (!match) continue; - const stats = { - additions: Number(match[1].replaceAll(",", "")), - deletions: Number(match[2].replaceAll(",", "")), - changedFiles: null, - }; - const initial = summaries.get(href); - if ( - summariesValid && - initial && - (initial.additions !== stats.additions || initial.deletions !== stats.deletions) - ) { - summariesValid = false; - renderedStats.clear(); - } - headers.set(href, stats); + const tree = document.querySelector(TREE_SELECTOR); + if (!tree) return; + if (tree.matches("file-tree")) { + updateClassicTree(tree); + return; } - for (const [href, stats] of headers) renderedStats.set(href, stats); - - for (const tree of document.querySelectorAll(TREE_SELECTOR)) { - for (const link of tree.querySelectorAll('a[href^="#diff-"]')) { - const href = link.getAttribute("href")!; - const stats = renderedStats.get(href) ?? (summariesValid ? summaries.get(href) : undefined); - const container = - link.closest(".PRIVATE_TreeView-item-content") ?? - link.querySelector(".ActionList-item-visual--trailing") ?? - link; - const existing = container.querySelector(`.${BADGE_CLASS}`); - if (!stats) { - existing?.remove(); - continue; - } - const key = `${stats.additions}:${stats.deletions}`; - if (existing?.dataset.stats === key) continue; - existing?.remove(); - const badge = buildDiffStatsBadge(stats, BADGE_CLASS); - badge.dataset.stats = key; - if (container.matches(".ActionList-item-visual--trailing")) container.prepend(badge); - else container.appendChild(badge); - } + readDirectoryTotals(tree); + for (const folder of tree.querySelectorAll( + `li[role="treeitem"][aria-expanded]${DISPLAYED_LEVELS}`, + )) { + const label = folder.firstElementChild?.querySelector('[class*="TreeViewItemContentText"]'); + if (label) updateBadge(label, directoryTotals.get(folder.id)); } } diff --git a/src/styles/content.css b/src/styles/content.css index 9305803..171bf73 100644 --- a/src/styles/content.css +++ b/src/styles/content.css @@ -304,18 +304,26 @@ a.better-github-review-popover-item:hover { align-items: center; gap: 4px; margin-left: auto; - padding-left: 8px; - font-size: 11px; + padding-inline-start: 8px; + font-size: 12px; + font-weight: 500; font-variant-numeric: tabular-nums; white-space: nowrap; } -file-tree .ActionList-item-visual--trailing:has(> .better-github-file-tree-diff-stats) { - width: auto; - gap: 4px; +[class*="TreeViewItemContentText"]:has(> .better-github-file-tree-diff-stats) { + display: flex; + align-items: center; + min-width: 0; +} + +[class*="TreeViewItemContentText"]:has(> .better-github-file-tree-diff-stats) > :first-child { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } -file-tree a > .better-github-file-tree-diff-stats { +file-tree button > .better-github-file-tree-diff-stats { grid-area: trailingVisual; } diff --git a/static/options.html b/static/options.html index 88e52b2..d85752f 100644 --- a/static/options.html +++ b/static/options.html @@ -655,8 +655,8 @@

    Settings

    File Tree Diff Stats
    - Show additions and deletions beside files in the PR file tree. Works with classic and - preview pages. No token required. + Show additions and deletions beside folders in the first three levels of the PR file tree. + Totals include all descendants.