Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions e2e/regression.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `<ul id="pr-file-tree"><li role="treeitem" aria-level="1" aria-expanded="false" id="src">
<div><span class="TreeViewItemContentText">src</span></div></li></ul>`;
await openFixture(
page,
"pull/42",
`${nav}<main><react-app initial-path="${conversation}">
<script type="application/json" data-target="react-app.embeddedData">{"payload":{"pullRequestsConversationsRoute":{}}}</script>
<div id="pr-view">Conversation</div>
</react-app></main>`,
);
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,
Expand Down
72 changes: 42 additions & 30 deletions src/features/pr-file-tree-diff-stats.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -11,17 +13,20 @@ 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<string, DiffStats>();
let summary: {
view: string;
source: Node | null;
requested: boolean;
totals: Map<string, DiffStats> | null;
} | null = null;

export function cleanupPRFileTreeDiffStats(): void {
observer?.disconnect();
observer = null;
root = null;
if (frame !== null) cancelAnimationFrame(frame);
frame = null;
summarySource = null;
directoryTotals.clear();
summary = null;
document.querySelectorAll(`.${BADGE_CLASS}`).forEach((badge) => badge.remove());
}

Expand All @@ -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<string, DiffStats> | 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<string, DiffStats> {
const directoryTotals = new Map<string, DiffStats>();
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);
Expand All @@ -83,6 +94,7 @@ function readDirectoryTotals(tree: Element): void {
directoryTotals.set(directory, total);
}
}
return directoryTotals;
}

function updateClassicTree(tree: Element): void {
Expand Down Expand Up @@ -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));
}
}

Expand All @@ -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;
Expand Down
10 changes: 10 additions & 0 deletions src/lib/github-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type {
ReleaseAssetDownload,
ContributorInfo,
} from "./messages";
import type { PRFileDiffSummary } from "./pr-file-diff-summaries";

function sendMessage<T>(request: ServiceWorkerRequest): Promise<T> {
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -171,6 +172,15 @@ export async function fetchPRDiffStats(
}
}

export async function fetchPRFileDiffSummaries(view: string): Promise<PRFileDiffSummary[] | null> {
try {
return await sendMessage<PRFileDiffSummary[]>({ 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,
Expand Down
1 change: 1 addition & 0 deletions src/lib/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
10 changes: 9 additions & 1 deletion src/lib/navigation.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions src/lib/pr-file-diff-summaries.ts
Original file line number Diff line number Diff line change
@@ -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;
}
25 changes: 25 additions & 0 deletions src/service-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -83,6 +84,28 @@ function restHeaders(
return headers;
}

async function fetchPRFileDiffSummaries(view: string): Promise<PRFileDiffSummary[]> {
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,
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion static/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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/*"],
Expand Down