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
4 changes: 4 additions & 0 deletions src/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 folders in the first three levels of the PR file tree. Totals include all descendants."
},
"featPrCollapseExpandName": { "message": "Collapse/Expand All Files" },
"featPrCollapseExpandDesc": {
"message": "Add a button to collapse or expand all file diffs on PR, commit, and compare pages."
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/zh_CN/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@
"featPrApproveNowDesc": {
"message": "在 PR 详情页的 Reviewers 侧边栏添加「立即批准」快捷入口。需要令牌。"
},
"featPrFileTreeDiffStatsName": { "message": "文件树增删行数" },
"featPrFileTreeDiffStatsDesc": {
"message": "在 PR 文件树前三层目录的右侧显示增删行数,包含所有子目录的改动。"
},
"featPrCollapseExpandName": { "message": "折叠/展开所有文件" },
"featPrCollapseExpandDesc": {
"message": "在 PR、Commit 和对比页面添加一个折叠或展开所有文件差异的按钮。"
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/zh_TW/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@
"featPrApproveNowDesc": {
"message": "在 PR 詳情頁的 Reviewers 側邊欄新增「立即核准」快速入口。需要權杖。"
},
"featPrFileTreeDiffStatsName": { "message": "檔案樹增刪行數" },
"featPrFileTreeDiffStatsDesc": {
"message": "在 PR 檔案樹前三層目錄的右側顯示增刪行數,包含所有子目錄的變更。"
},
"featPrCollapseExpandName": { "message": "摺疊/展開所有檔案" },
"featPrCollapseExpandDesc": {
"message": "在 PR、Commit 和比較頁面新增一個摺疊或展開所有檔案差異的按鈕。"
Expand Down
10 changes: 10 additions & 0 deletions src/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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",
Expand All @@ -51,6 +56,7 @@ type FeatureKey = (typeof FEATURE_KEYS)[number];

// CSS classes used by each feature's injected elements
const FEATURE_CLASSES: Record<FeatureKey, string[]> = {
"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"],
Expand All @@ -72,6 +78,7 @@ const FEATURE_CLASSES: Record<FeatureKey, string[]> = {
// DOM run a cleanup hook on disable, before removeFeatureElements() strips their
// elements by class.
const FEATURE_CLEANUPS: Partial<Record<FeatureKey, () => void>> = {
"feature-pr-file-tree-diff-stats": cleanupPRFileTreeDiffStats,
"feature-pr-conflict-indicator": cleanupPRConflictIndicator,
"feature-pr-label-position": cleanupPRLabelPosition,
"feature-watch-fork-star-popup": cleanupWatchForkStarPopup,
Expand Down Expand Up @@ -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;
Expand Down
76 changes: 76 additions & 0 deletions src/features/pr-file-tree-diff-stats.test.ts
Original file line number Diff line number Diff line change
@@ -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 = '<div><span class="TreeViewItemContentText"><span>name</span></span></div>';
document.body.innerHTML = `<main><react-app initial-path="${view}">
<script data-target="react-app.embeddedData" type="application/json">${JSON.stringify(data)}</script>
<ul id="pr-file-tree"><li role="treeitem" aria-level="1" aria-expanded="false" id="src">${label}</li></ul>
</react-app></main>`;
injectPRFileTreeDiffStats();
const folder = document.getElementById("src")!;
expect(folder.querySelector(badge)?.textContent).toBe("+10−3");
folder.setAttribute("aria-expanded", "true");
folder.insertAdjacentHTML(
"beforeend",
`<ul><li role="treeitem" aria-level="2" id="src/lib" aria-expanded="true">${label}
<ul><li role="treeitem" aria-level="3" id="src/lib/generated/client" aria-expanded="true">${label}
<ul><li role="treeitem" aria-level="4" id="src/lib/generated/client/deep" aria-expanded="true">${label}
<ul><li role="treeitem" aria-level="5" id="src/lib/generated/client/deep/a.ts">${label}</li></ul>
</li></ul>
</li></ul>
</li></ul>`,
);
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) => `<div class="js-file-header" data-anchor="diff-${id}">
<div class="file-info"><span class="sr-only">2 additions &amp; 1 deletion</span></div></div>`;
document.body.innerHTML = `<main><file-tree><ul><li aria-level="3" data-tree-entry-type="directory">
<button class="ActionList-content" aria-expanded="false">src/lib</button>
<ul><li aria-level="4" data-tree-entry-type="directory"><button class="ActionList-content">deep</button>
<ul>${["a", "b"].map((id) => `<li data-tree-entry-type="file"><a href="#diff-${id}">${id}</a></li>`).join("")}</ul>
</li></ul></li></ul></file-tree>${header("a")}</main>`;
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();
});
180 changes: 180 additions & 0 deletions src/features/pr-file-tree-diff-stats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
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 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 summarySource: Node | null = null;
const directoryTotals = new Map<string, DiffStats>();

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

function updateBadge(container: Element, stats?: DiffStats): void {
const existing = container.querySelector<HTMLElement>(`.${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 { 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<string, DiffStats>();
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++;
}
updateBadge(button, counted && counted === links.length ? total : undefined);
}
}

function updateStats(): void {
if (!isPRFilesChangedPage()) {
cleanupPRFileTreeDiffStats();
return;
}
const tree = document.querySelector(TREE_SELECTOR);
if (!tree) return;
if (tree.matches("file-tree")) {
updateClassicTree(tree);
return;
}
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));
}
}

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();
}
1 change: 1 addition & 0 deletions src/options.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
29 changes: 29 additions & 0 deletions src/styles/content.css
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,35 @@ 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-inline-start: 8px;
font-size: 12px;
font-weight: 500;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}

[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 button > .better-github-file-tree-diff-stats {
grid-area: trailingVisual;
}

.better-github-diff-stats-add {
color: var(--fgColor-success, var(--color-success-fg, #1a7f37));
}
Expand Down
Loading