diff --git a/e2e/regression.spec.mjs b/e2e/regression.spec.mjs
index 35d2ff5..ddd9384 100644
--- a/e2e/regression.spec.mjs
+++ b/e2e/regression.spec.mjs
@@ -140,6 +140,65 @@ test("places the commit fold control on the hydrated toolbar", async ({ page })
await expect(page.locator(fold)).toBeVisible(promptly);
});
+test("shows directory totals after switching from a PR conversation to Files changed", async ({
+ page,
+ context,
+}) => {
+ const conversation = `${repo}/pull/42`;
+ const changes = `${conversation}/changes`;
+ const range = `${changes}/abc123`;
+ let requests = 0;
+ await context.route(`https://github.com${changes}**`, (route) => {
+ requests++;
+ const isRange = new URL(route.request().url()).pathname === range;
+ const key = isRange ? "pullRequestsChangesWithRangeRoute" : "pullRequestsChangesRoute";
+ return route.fulfill({
+ json: {
+ payload: {
+ [key]: {
+ diffSummaries: [{ path: "src/lib/a.ts", linesAdded: isRange ? 3 : 9, linesDeleted: 1 }],
+ },
+ },
+ },
+ });
+ });
+
+ const tree = `
`;
+ await openFixture(
+ page,
+ "pull/42",
+ `${nav}
+
+ Conversation
+ `,
+ );
+ await expect(page.locator(releases)).toBeVisible();
+ const switchView = (view) =>
+ page.evaluate(
+ ({ view, tree }) => {
+ history.pushState(null, "", view);
+ document.querySelector("#pr-view").innerHTML = tree;
+ },
+ { view, tree },
+ );
+
+ const folderTotal = page.locator(".better-github-file-tree-diff-stats");
+ await switchView(changes);
+ await expect(folderTotal).toHaveText("+9−1", promptly);
+ await switchView(range);
+ await expect(folderTotal).toHaveText("+3−1", promptly);
+ await page.evaluate((tree) => {
+ document.querySelector("#pr-view").innerHTML = tree;
+ }, tree);
+ await expect(folderTotal).toHaveText("+3−1", promptly);
+ await switchView(changes);
+ await expect(folderTotal).toHaveText("+9−1", promptly);
+ await folderTotal.evaluate((element) => element.remove());
+ await expect(folderTotal).toHaveText("+9−1", promptly);
+ expect(requests).toBe(2);
+});
+
test("shows diff stats after hydration and after in-page commit pagination", async ({
page,
context,
diff --git a/src/features/pr-file-tree-diff-stats.ts b/src/features/pr-file-tree-diff-stats.ts
index 89b3c7a..c3aea5b 100644
--- a/src/features/pr-file-tree-diff-stats.ts
+++ b/src/features/pr-file-tree-diff-stats.ts
@@ -1,5 +1,7 @@
import { isPRFilesChangedPage } from "../lib/page-detect";
import { buildDiffStatsBadge, type DiffStats } from "../lib/diff-stats-badge";
+import { fetchPRFileDiffSummaries } from "../lib/github-api";
+import { parsePRFileDiffSummaries, type PRFileDiffSummary } from "../lib/pr-file-diff-summaries";
const BADGE_CLASS = "better-github-file-tree-diff-stats";
const TREE_SELECTOR = '#pr-file-tree, [class*="PullRequestFileTree-module__sidebar"], file-tree';
@@ -11,8 +13,12 @@ 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 summarySource: Node | null = null;
-const directoryTotals = new Map();
+let summary: {
+ view: string;
+ source: Node | null;
+ requested: boolean;
+ totals: Map | null;
+} | null = null;
export function cleanupPRFileTreeDiffStats(): void {
observer?.disconnect();
@@ -20,8 +26,7 @@ export function cleanupPRFileTreeDiffStats(): void {
root = null;
if (frame !== null) cancelAnimationFrame(frame);
frame = null;
- summarySource = null;
- directoryTotals.clear();
+ summary = null;
document.querySelectorAll(`.${BADGE_CLASS}`).forEach((badge) => badge.remove());
}
@@ -39,37 +44,43 @@ function updateBadge(container: Element, stats?: DiffStats): void {
else container.append(badge);
}
-function readDirectoryTotals(tree: Element): void {
+function readDirectoryTotals(tree: Element): Map | null {
const app = tree.closest("react-app");
const currentView = location.pathname + location.search;
+ const state =
+ summary?.view === currentView
+ ? summary
+ : { view: currentView, source: null, requested: false, totals: null };
+ summary = state;
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 { payload } = JSON.parse(source.textContent);
- const route = payload?.pullRequestsChangesWithRangeRoute ?? payload?.pullRequestsChangesRoute;
- entries = route?.diffSummaries;
- } catch {
- return;
+ if (source?.textContent && source !== state.source) {
+ state.source = source;
+ const entries = parsePRFileDiffSummaries(source.textContent);
+ if (entries) state.totals = totalByDirectory(entries);
}
- 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;
+ if (!state.totals && !state.requested) {
+ state.requested = true;
+ void fetchPRFileDiffSummaries(currentView).then((entries) => {
+ if (
+ !entries ||
+ summary !== state ||
+ state.totals ||
+ location.pathname + location.search !== currentView
+ ) {
+ return;
+ }
+ state.totals = totalByDirectory(entries);
+ updateStats();
+ });
}
+ return state.totals;
+}
+
+function totalByDirectory(entries: PRFileDiffSummary[]): Map {
+ const directoryTotals = new Map();
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);
@@ -83,6 +94,7 @@ function readDirectoryTotals(tree: Element): void {
directoryTotals.set(directory, total);
}
}
+ return directoryTotals;
}
function updateClassicTree(tree: Element): void {
@@ -128,12 +140,12 @@ function updateStats(): void {
updateClassicTree(tree);
return;
}
- readDirectoryTotals(tree);
+ const directoryTotals = 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));
+ if (label) updateBadge(label, directoryTotals?.get(folder.id));
}
}
@@ -155,7 +167,7 @@ export function injectPRFileTreeDiffStats(): void {
if (target?.closest(`.${BADGE_CLASS}`)) return false;
const nodes = [...mutation.addedNodes, ...mutation.removedNodes];
if (
- nodes.length &&
+ mutation.addedNodes.length &&
nodes.every((node) => node instanceof Element && node.matches(`.${BADGE_CLASS}`))
)
return false;
diff --git a/src/lib/github-api.ts b/src/lib/github-api.ts
index 8fba033..418d5d0 100644
--- a/src/lib/github-api.ts
+++ b/src/lib/github-api.ts
@@ -15,6 +15,7 @@ import type {
ReleaseAssetDownload,
ContributorInfo,
} from "./messages";
+import type { PRFileDiffSummary } from "./pr-file-diff-summaries";
function sendMessage(request: ServiceWorkerRequest): Promise {
return new Promise((resolve, reject) => {
@@ -171,6 +172,15 @@ export async function fetchPRDiffStats(
}
}
+export async function fetchPRFileDiffSummaries(view: string): Promise {
+ try {
+ return await sendMessage({ type: "FETCH_PR_FILE_DIFF_SUMMARIES", view });
+ } catch (err) {
+ console.error("[Better GitHub] Failed to fetch PR file diff summaries:", err);
+ return null;
+ }
+}
+
export async function fetchCommitDiffStats(
owner: string,
repo: string,
diff --git a/src/lib/messages.ts b/src/lib/messages.ts
index 79ff3ac..353e886 100644
--- a/src/lib/messages.ts
+++ b/src/lib/messages.ts
@@ -116,6 +116,7 @@ export type ServiceWorkerRequest =
| { type: "FETCH_PR_REVIEW_STATUSES"; owner: string; repo: string; prNumbers: number[] }
| { type: "FETCH_PR_REVIEW_THREAD_DETAILS"; owner: string; repo: string; prNumber: number }
| { type: "FETCH_PR_DIFF_STATS"; owner: string; repo: string; prNumbers: number[] }
+ | { type: "FETCH_PR_FILE_DIFF_SUMMARIES"; view: string }
| { type: "FETCH_COMMIT_DIFF_STATS"; owner: string; repo: string; shas: string[] }
| { type: "APPROVE_PR"; owner: string; repo: string; prNumber: number; body?: string }
| { type: "FETCH_REPO_TAGS"; owner: string; repo: string }
diff --git a/src/lib/navigation.ts b/src/lib/navigation.ts
index bacdd73..491372f 100644
--- a/src/lib/navigation.ts
+++ b/src/lib/navigation.ts
@@ -1,4 +1,4 @@
-import { isCommitsListPage, isIssueOrPRListPage } from "./page-detect";
+import { isCommitsListPage, isIssueOrPRListPage, isPRFilesChangedPage } from "./page-detect";
import { ISSUE_TITLE_SELECTOR, PR_DASHBOARD_SELECTOR, PR_TITLE_SELECTOR } from "./pr-list-dom";
import { watchReactReady } from "./react-ready";
@@ -44,6 +44,14 @@ window.addEventListener("popstate", () => {
setTimeout(runHandlers, 0);
});
+window.navigation?.addEventListener("currententrychange", ({ from }) => {
+ if (!isPRFilesChangedPage() || !from.url) return;
+ const previous = new URL(from.url);
+ if (previous.pathname !== location.pathname || previous.search !== location.search) {
+ scheduleHandlers();
+ }
+});
+
// Polling fallback — GitHub's SPA doesn't always fire Turbo events reliably.
// Always re-run handlers because GitHub may re-render the nav (destroying
// injected elements) without changing the URL. All inject functions are
diff --git a/src/lib/pr-file-diff-summaries.ts b/src/lib/pr-file-diff-summaries.ts
new file mode 100644
index 0000000..79d0bf1
--- /dev/null
+++ b/src/lib/pr-file-diff-summaries.ts
@@ -0,0 +1,38 @@
+export interface PRFileDiffSummary {
+ path: string;
+ linesAdded: number;
+ linesDeleted: number;
+}
+
+export function parsePRFileDiffSummaries(json: string): PRFileDiffSummary[] | null {
+ let data: {
+ payload?: {
+ pullRequestsChangesWithRangeRoute?: { diffSummaries?: unknown };
+ pullRequestsChangesRoute?: { diffSummaries?: unknown };
+ };
+ } | null;
+ try {
+ data = JSON.parse(json);
+ } catch {
+ return null;
+ }
+ const payload = data?.payload;
+ const route = payload?.pullRequestsChangesWithRangeRoute ?? payload?.pullRequestsChangesRoute;
+ const entries = route?.diffSummaries;
+ if (!Array.isArray(entries)) return null;
+ const summaries: PRFileDiffSummary[] = [];
+ 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 null;
+ }
+ const { path, linesAdded, linesDeleted } = entry;
+ summaries.push({ path, linesAdded, linesDeleted });
+ }
+ return summaries;
+}
diff --git a/src/service-worker.ts b/src/service-worker.ts
index f2fc6a1..5723016 100644
--- a/src/service-worker.ts
+++ b/src/service-worker.ts
@@ -16,6 +16,7 @@ import type {
ReleaseAssetDownload,
ContributorInfo,
} from "./lib/messages";
+import { parsePRFileDiffSummaries, type PRFileDiffSummary } from "./lib/pr-file-diff-summaries";
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
const CACHE_MISS = Symbol("cache-miss");
@@ -83,6 +84,28 @@ function restHeaders(
return headers;
}
+async function fetchPRFileDiffSummaries(view: string): Promise {
+ const url = new URL(view, "https://github.com");
+ if (
+ url.origin !== "https://github.com" ||
+ !/^\/[^/]+\/[^/]+\/pull\/\d+\/(changes|files)(\/.*)?$/.test(url.pathname)
+ ) {
+ throw new Error("Invalid PR changes route");
+ }
+
+ return cachedFetch(`cache:pr-file-diff-summaries:${url.pathname}${url.search}`, async () => {
+ const response = await fetch(url, {
+ credentials: "include",
+ headers: { Accept: "application/json" },
+ redirect: "error",
+ });
+ if (!response.ok) throw new Error(`PR changes request returned ${response.status}`);
+ const summaries = parsePRFileDiffSummaries(await response.text());
+ if (!summaries) throw new Error("Missing PR file diff summaries");
+ return summaries;
+ });
+}
+
async function fetchPRBranches(
owner: string,
repo: string,
@@ -944,6 +967,8 @@ async function handleMessage(
ok: true,
data: await fetchPRDiffStats(request.owner, request.repo, request.prNumbers),
};
+ case "FETCH_PR_FILE_DIFF_SUMMARIES":
+ return { ok: true, data: await fetchPRFileDiffSummaries(request.view) };
case "FETCH_COMMIT_DIFF_STATS":
return {
ok: true,
diff --git a/static/manifest.json b/static/manifest.json
index 47af602..f737f4b 100644
--- a/static/manifest.json
+++ b/static/manifest.json
@@ -15,7 +15,7 @@
"page": "options.html",
"open_in_tab": false
},
- "host_permissions": ["https://api.github.com/*"],
+ "host_permissions": ["https://api.github.com/*", "https://github.com/*"],
"content_scripts": [
{
"matches": ["https://github.com/*"],