Open History to see the last commit
1import { type TurnDiffFileChange } from "../../types";
2import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
3
4export const CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT = 5;
5export const CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT = 200;
6export const CHANGED_FILES_PREVIEW_FILE_LIMIT = 3;
7export const CHANGED_FILES_PREVIEW_SCOPE_LIMIT = 4;
8
9export interface ChangedFilesScopeSummary {
10 readonly label: string;
11 readonly fileCount: number;
12}
13
14function pathSegments(pathValue: string): string[] {
15 return pathValue
16 .replaceAll("\\", "/")
17 .split("/")
18 .filter((segment) => segment.length > 0);
19}
20
21export function changedFileName(pathValue: string): string {
22 return pathSegments(pathValue).at(-1) ?? pathValue;
23}
24
25function changedFileScope(pathValue: string): string {
26 const segments = pathSegments(pathValue);
27 return segments.length > 1 ? (segments[0] ?? "root") : "root";
28}
29
30export function shouldAutoExpandChangedFiles(
31 files: ReadonlyArray<TurnDiffFileChange>,
32 isLatestTurn: boolean,
33): boolean {
34 if (!isLatestTurn || files.length > CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT) {
35 return false;
36 }
37 const stat = summarizeTurnDiffStats(files);
38 return stat.additions + stat.deletions <= CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT;
39}
40
41export function summarizeChangedFileScopes(
42 files: ReadonlyArray<TurnDiffFileChange>,
43 limit = CHANGED_FILES_PREVIEW_SCOPE_LIMIT,
44): ChangedFilesScopeSummary[] {
45 const scopes = new Map<string, { fileCount: number; firstIndex: number }>();
46 files.forEach((file, index) => {
47 const label = changedFileScope(file.path);
48 const current = scopes.get(label);
49 scopes.set(label, {
50 fileCount: (current?.fileCount ?? 0) + 1,
51 firstIndex: current?.firstIndex ?? index,
52 });
53 });
54
55 return Array.from(scopes, ([label, scope]) => ({
56 label,
57 fileCount: scope.fileCount,
58 firstIndex: scope.firstIndex,
59 }))
60 .toSorted(
61 (left, right) =>
62 right.fileCount - left.fileCount ||
63 left.firstIndex - right.firstIndex ||
64 left.label.localeCompare(right.label),
65 )
66 .slice(0, limit)
67 .map(({ label, fileCount }) => ({ label, fileCount }));
68}
69
70export function selectChangedFilePreview(
71 files: ReadonlyArray<TurnDiffFileChange>,
72 limit = CHANGED_FILES_PREVIEW_FILE_LIMIT,
73): TurnDiffFileChange[] {
74 const selected: TurnDiffFileChange[] = [];
75 const selectedPaths = new Set<string>();
76 const selectedScopes = new Set<string>();
77
78 for (const file of files) {
79 const scope = changedFileScope(file.path);
80 if (selectedScopes.has(scope)) {
81 continue;
82 }
83 selected.push(file);
84 selectedPaths.add(file.path);
85 selectedScopes.add(scope);
86 if (selected.length === limit) {
87 return selected;
88 }
89 }
90
91 for (const file of files) {
92 if (selectedPaths.has(file.path)) {
93 continue;
94 }
95 selected.push(file);
96 if (selected.length === limit) {
97 break;
98 }
99 }
100
101 return selected;
102}