Open History to see the last commit
1import { useSyncLayout } from "@legendapp/list/react";
2import { type OrchestrationV2CheckpointFileTotals, type RunId } from "@t3tools/contracts";
3import { T, useGT } from "gt-react";
4import { type MouseEvent, type ReactNode, memo, useLayoutEffect, useRef, useState } from "react";
5import { type TurnDiffFileChange } from "../../types";
6import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
7import {
8 ChevronRightIcon,
9 FileDiffIcon,
10 ChevronsDownUpIcon,
11 ChevronsUpDownIcon,
12 FolderClosedIcon,
13 FolderGit2Icon,
14 FolderIcon,
15} from "lucide-react";
16import { cn } from "~/lib/utils";
17import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
18import { PierreEntryIcon } from "./PierreEntryIcon";
19import { Button } from "../ui/button";
20import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
21import { MiddleTruncate } from "../ui/middle-truncate";
22import { observeResize } from "~/lib/observeResize";
23import { repositoryFilePath } from "@t3tools/client-runtime/state/thread-repositories";
24
25const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
26const VIRTUALIZE_AFTER_ROWS = 250;
27const ROW_OVERSCAN = 8;
28
29interface ChangedFileRow {
30 node: TurnDiffTreeNode;
31 depth: number;
32}
33
34/** One folder's share of a turn that changed several repositories. */
35export interface ChangedFilesGroup {
36 readonly key: string;
37 readonly name: string;
38 /** Paths relative to this group's folder. */
39 readonly files: ReadonlyArray<TurnDiffFileChange>;
40 readonly totals: OrchestrationV2CheckpointFileTotals;
41 /** The folder from the thread's folder; undefined when the diff cannot be opened at a file. */
42 readonly relativePath: string | undefined;
43 /** Shown in place of the files when they cannot be listed. */
44 readonly note?: string | undefined;
45}
46
47type ChangedFileContextMenuHandler = (
48 filePath: string,
49 event: MouseEvent,
50 group?: ChangedFilesGroup,
51) => void;
52
53function groupDiffPath(group: ChangedFilesGroup, filePath: string | undefined) {
54 return filePath === undefined || group.relativePath === undefined
55 ? undefined
56 : repositoryFilePath(group.relativePath, filePath);
57}
58
59export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
60 runId: RunId;
61 /** May be a prefix of the changed files; `totals` covers all of them. */
62 files: ReadonlyArray<TurnDiffFileChange>;
63 totals: OrchestrationV2CheckpointFileTotals;
64 /** Set when the turn changed tracked repositories; replaces the single tree built from `files`. */
65 groups?: ReadonlyArray<ChangedFilesGroup> | undefined;
66 allDirectoriesExpanded: boolean;
67 resolvedTheme: "light" | "dark";
68 onToggleAllDirectories: () => void;
69 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
70 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
71}) {
72 const {
73 runId,
74 files,
75 totals,
76 groups,
77 allDirectoriesExpanded,
78 resolvedTheme,
79 onToggleAllDirectories,
80 onOpenTurnDiff,
81 onFileContextMenu,
82 } = props;
83 const gt = useGT();
84 const syncTimelineLayout = useSyncLayout();
85 const listedFiles = groups ? groups.flatMap((group) => group.files) : files;
86 const hiddenFileCount = totals.count - listedFiles.length;
87 const hasDirectories = listedFiles.some((file) => /[/\\]/.test(file.path));
88 const firstGroup = groups?.find((group) => group.files.length > 0);
89 const firstFilePath = groups
90 ? firstGroup && groupDiffPath(firstGroup, firstGroup.files[0]?.path)
91 : files[0]?.path;
92
93 return (
94 <div
95 className="@container/changed-files mt-4 rounded-lg bg-secondary dark:bg-input/20"
96 data-changed-files-state="tree"
97 >
98 <div
99 data-changed-files-header=""
100 className="sticky top-2 z-10 flex items-center justify-between gap-2 rounded-t-lg bg-secondary px-3 py-2 dark:bg-background dark:bg-linear-to-b dark:from-input/20 dark:to-input/20"
101 >
102 <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs font-medium text-foreground">
103 <span>
104 {gt(
105 "{count, plural, one {{formattedCount} changed file} other {{formattedCount} changed files}}",
106 { count: totals.count, formattedCount: totals.count.toLocaleString() },
107 )}
108 </span>
109 {hasNonZeroStat(totals) && (
110 <DiffStatLabel
111 additions={totals.additions}
112 deletions={totals.deletions}
113 layout="inline"
114 className="text-xs leading-4"
115 />
116 )}
117 </div>
118 <div className="flex shrink-0 items-center gap-1">
119 {hasDirectories && (
120 <Tooltip>
121 <TooltipTrigger
122 render={
123 <Button
124 type="button"
125 size="icon-xs"
126 variant="ghost-muted"
127 aria-label={
128 allDirectoriesExpanded ? gt("Collapse all folders") : gt("Expand all folders")
129 }
130 data-scroll-anchor-ignore
131 onClick={() => {
132 onToggleAllDirectories();
133 syncTimelineLayout();
134 }}
135 />
136 }
137 >
138 {allDirectoriesExpanded ? (
139 <ChevronsDownUpIcon className="size-3" />
140 ) : (
141 <ChevronsUpDownIcon className="size-3" />
142 )}
143 </TooltipTrigger>
144 <TooltipPopup side="top">
145 {allDirectoriesExpanded ? gt("Collapse all folders") : gt("Expand all folders")}
146 </TooltipPopup>
147 </Tooltip>
148 )}
149 <Tooltip>
150 <TooltipTrigger
151 render={
152 <Button
153 type="button"
154 size="xs"
155 variant="ghost-muted"
156 aria-label={gt("Open diff")}
157 onClick={() => onOpenTurnDiff(runId, firstFilePath)}
158 />
159 }
160 >
161 <FileDiffIcon className="size-3" />
162 <span className="hidden @[24rem]/changed-files:inline">
163 <T>Open diff</T>
164 </span>
165 </TooltipTrigger>
166 <TooltipPopup side="top">
167 <T>Open the full diff</T>
168 </TooltipPopup>
169 </Tooltip>
170 </div>
171 </div>
172 <div className="p-2">
173 {groups ? (
174 groups.map((group) => (
175 <ChangedFilesGroupSection
176 key={group.key}
177 runId={runId}
178 group={group}
179 allDirectoriesExpanded={allDirectoriesExpanded}
180 resolvedTheme={resolvedTheme}
181 onOpenTurnDiff={onOpenTurnDiff}
182 onFileContextMenu={onFileContextMenu}
183 />
184 ))
185 ) : (
186 <ChangedFilesTree
187 key={`${runId}:${allDirectoriesExpanded}`}
188 runId={runId}
189 files={files}
190 allDirectoriesExpanded={allDirectoriesExpanded}
191 resolvedTheme={resolvedTheme}
192 onOpenTurnDiff={onOpenTurnDiff}
193 onFileContextMenu={onFileContextMenu}
194 />
195 )}
196 </div>
197 {hiddenFileCount > 0 && (
198 <div className="px-3 pb-2">
199 <Button
200 type="button"
201 size="xs"
202 variant="ghost-muted"
203 onClick={() => onOpenTurnDiff(runId, firstFilePath)}
204 >
205 {gt(
206 "{count, plural, one {{formattedCount} more file in the full diff} other {{formattedCount} more files in the full diff}}",
207 { count: hiddenFileCount, formattedCount: hiddenFileCount.toLocaleString() },
208 )}
209 </Button>
210 </div>
211 )}
212 </div>
213 );
214});
215
216function ChangedFilesGroupSection(props: {
217 runId: RunId;
218 group: ChangedFilesGroup;
219 allDirectoriesExpanded: boolean;
220 resolvedTheme: "light" | "dark";
221 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
222 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
223}) {
224 const { runId, group, allDirectoriesExpanded, resolvedTheme, onOpenTurnDiff, onFileContextMenu } =
225 props;
226 const [collapsed, setCollapsed] = useState(false);
227 const syncTimelineLayout = useSyncLayout();
228 return (
229 <section data-changed-files-group={group.name}>
230 <button
231 type="button"
232 data-scroll-anchor-ignore
233 aria-expanded={!collapsed}
234 className="group flex h-7 w-full cursor-pointer items-center gap-2 rounded-md py-1.5 pr-2 pl-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
235 onClick={() => {
236 setCollapsed(!collapsed);
237 syncTimelineLayout();
238 }}
239 >
240 <ChevronRightIcon
241 aria-hidden="true"
242 className={cn(
243 "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
244 !collapsed && "rotate-90",
245 )}
246 />
247 <FolderGit2Icon className="size-3.5 shrink-0 text-muted-foreground/75" />
248 <span className="truncate font-mono text-2xs text-foreground/90">{group.name}</span>
249 {hasNonZeroStat(group.totals) && (
250 <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
251 <DiffStatLabel additions={group.totals.additions} deletions={group.totals.deletions} />
252 </span>
253 )}
254 </button>
255 {collapsed ? null : group.note !== undefined ? (
256 <p className="py-1.5 pr-2 pl-9.5 text-2xs text-muted-foreground">{group.note}</p>
257 ) : (
258 <ChangedFilesTree
259 key={`${runId}:${allDirectoriesExpanded}`}
260 runId={runId}
261 files={group.files}
262 baseDepth={1}
263 allDirectoriesExpanded={allDirectoriesExpanded}
264 resolvedTheme={resolvedTheme}
265 onOpenTurnDiff={(run, filePath) => onOpenTurnDiff(run, groupDiffPath(group, filePath))}
266 onFileContextMenu={
267 onFileContextMenu
268 ? (filePath, event) => onFileContextMenu(filePath, event, group)
269 : undefined
270 }
271 />
272 )}
273 </section>
274 );
275}
276
277const ChangedFilesTree = memo(function ChangedFilesTree(props: {
278 runId: RunId;
279 files: ReadonlyArray<TurnDiffFileChange>;
280 /** Rows start this deep, below the row of the folder the files belong to. */
281 baseDepth?: number;
282 allDirectoriesExpanded: boolean;
283 resolvedTheme: "light" | "dark";
284 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
285 onFileContextMenu?: ChangedFileContextMenuHandler | undefined;
286}) {
287 const baseDepth = props.baseDepth ?? 0;
288 const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId, onFileContextMenu } =
289 props;
290 // Place state before tree derivation to preserve its compiler cache.
291 const [directoryExpansionState, setDirectoryExpansionState] = useState<{
292 key: string | null;
293 overrides: Record<string, boolean>;
294 }>({ key: null, overrides: {} });
295 const syncTimelineLayout = useSyncLayout();
296 const treeNodes = buildTurnDiffTree(files);
297 const directoryPathsKey = collectDirectoryPaths(treeNodes).join("\u0000");
298 const hasDirectoryNodes = directoryPathsKey.length > 0;
299 const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`;
300 const expandedDirectories =
301 directoryExpansionState.key === expansionStateKey
302 ? directoryExpansionState.overrides
303 : EMPTY_DIRECTORY_OVERRIDES;
304
305 const toggleDirectory = (pathValue: string) => {
306 setDirectoryExpansionState((current) => {
307 const nextOverrides = current.key === expansionStateKey ? current.overrides : {};
308 return {
309 key: expansionStateKey,
310 overrides: {
311 ...nextOverrides,
312 [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded),
313 },
314 };
315 });
316 // Measure before paint instead of waiting for LegendList's deferred shrink measurement.
317 syncTimelineLayout();
318 };
319
320 const rows = collectExpandedRows(treeNodes, expandedDirectories, allDirectoriesExpanded);
321 const virtualized = rows.length > VIRTUALIZE_AFTER_ROWS;
322
323 const renderRow = ({ node, depth }: ChangedFileRow) => {
324 const leftPadding = 8 + (baseDepth + depth) * 14;
325 if (node.kind === "directory") {
326 const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded;
327 return (
328 <button
329 key={`dir:${node.path}`}
330 type="button"
331 data-scroll-anchor-ignore
332 aria-expanded={isExpanded}
333 className="group flex h-7 w-full cursor-pointer items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
334 style={{ paddingLeft: `${leftPadding}px` }}
335 onClick={() => toggleDirectory(node.path)}
336 >
337 <ChevronRightIcon
338 aria-hidden="true"
339 className={cn(
340 "size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
341 isExpanded && "rotate-90",
342 )}
343 />
344 {isExpanded ? (
345 <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
346 ) : (
347 <FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
348 )}
349 <span className="truncate font-mono text-2xs text-muted-foreground/90 group-hover:text-foreground/90">
350 {node.name}
351 </span>
352 {hasNonZeroStat(node.stat) && (
353 <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
354 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
355 </span>
356 )}
357 </button>
358 );
359 }
360
361 return (
362 <button
363 key={`file:${node.path}`}
364 type="button"
365 className="group flex h-7 w-full cursor-pointer items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
366 style={{ paddingLeft: `${leftPadding}px` }}
367 onClick={() => onOpenTurnDiff(runId, node.path)}
368 onContextMenu={
369 onFileContextMenu
370 ? (event) => {
371 event.preventDefault();
372 onFileContextMenu(node.path, event);
373 }
374 : undefined
375 }
376 >
377 {hasDirectoryNodes || baseDepth + depth > 0 ? (
378 <span aria-hidden="true" className="size-3.5 shrink-0" />
379 ) : null}
380 <PierreEntryIcon
381 pathValue={node.path}
382 kind="file"
383 theme={resolvedTheme}
384 className="size-3.5 text-muted-foreground/70"
385 />
386 <span className="flex min-w-0 font-mono text-xs text-foreground/85 group-hover:text-foreground">
387 <MiddleTruncate value={node.name} />
388 </span>
389 {node.stat && (
390 <span className="ml-auto shrink-0 font-mono text-3xs tabular-nums">
391 <DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
392 </span>
393 )}
394 </button>
395 );
396 };
397
398 return <ChangedFilesRows rows={rows} renderRow={renderRow} virtualized={virtualized} />;
399});
400
401function ChangedFilesRows({
402 rows,
403 renderRow,
404 virtualized,
405}: {
406 rows: ReadonlyArray<ChangedFileRow>;
407 renderRow: (row: ChangedFileRow) => ReactNode;
408 virtualized: boolean;
409}) {
410 const containerRef = useRef<HTMLDivElement>(null);
411 const rowSizeRef = useRef<HTMLDivElement>(null);
412 const [range, setRange] = useState({ start: 0, end: 40, rowHeight: 28 });
413 const [focusedPath, setFocusedPath] = useState<string | null>(null);
414
415 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes scroll, window resize and ancestor resizes to compute the virtualized row range
416 useLayoutEffect(() => {
417 const container = containerRef.current;
418 const rowSize = rowSizeRef.current;
419 if (!virtualized || !container || !rowSize) return;
420
421 // The card is inside a virtualized timeline item, so its own scrollTop is always zero.
422 // Observe its ancestors too: streaming text and timeline layout can move the card.
423 const ancestors: HTMLElement[] = [container, rowSize];
424 let scrollElement: HTMLElement | null = null;
425 for (let parent = container.parentElement; parent; parent = parent.parentElement) {
426 ancestors.push(parent);
427 if (/auto|scroll/.test(getComputedStyle(parent).overflowY)) {
428 scrollElement = parent;
429 break;
430 }
431 }
432
433 const measure = () => {
434 const rowHeight = rowSize.getBoundingClientRect().height;
435 if (rowHeight <= 0) return;
436 const listTop = container.getBoundingClientRect().top;
437 const viewportTop = scrollElement
438 ? scrollElement.getBoundingClientRect().top + scrollElement.clientTop
439 : 0;
440 const viewportHeight = scrollElement?.clientHeight ?? document.documentElement.clientHeight;
441 const start = Math.max(
442 0,
443 Math.min(rows.length, Math.floor((viewportTop - listTop) / rowHeight) - ROW_OVERSCAN),
444 );
445 const end = Math.max(
446 start,
447 Math.min(
448 rows.length,
449 Math.ceil((viewportTop + viewportHeight - listTop) / rowHeight) + ROW_OVERSCAN,
450 ),
451 );
452 setRange((current) =>
453 current.start === start && current.end === end && current.rowHeight === rowHeight
454 ? current
455 : { start, end, rowHeight },
456 );
457 };
458 measure();
459 const scrollTarget = scrollElement ?? globalThis.window;
460 let frame = 0;
461 const onScroll = () => {
462 if (frame) return;
463 frame = requestAnimationFrame(() => {
464 frame = 0;
465 measure();
466 });
467 };
468 scrollTarget.addEventListener("scroll", onScroll, { passive: true });
469 globalThis.window.addEventListener("resize", onScroll);
470 const stopObserving = observeResize(ancestors, measure);
471 return () => {
472 scrollTarget.removeEventListener("scroll", onScroll);
473 globalThis.window.removeEventListener("resize", onScroll);
474 if (frame) cancelAnimationFrame(frame);
475 stopObserving();
476 };
477 }, [virtualized, rows.length]);
478
479 const focusedIndex =
480 focusedPath === null ? -1 : rows.findIndex((row) => row.node.path === focusedPath);
481 const start = virtualized ? range.start : 0;
482 const end = virtualized ? Math.min(rows.length, range.end) : rows.length;
483 const indices = Array.from({ length: Math.max(0, end - start) }, (_, index) => start + index);
484 // Keep keyboard focus on its row when mouse scrolling moves it outside the render window.
485 if (focusedIndex >= 0 && focusedIndex < start) indices.unshift(focusedIndex);
486 if (focusedIndex >= end) indices.push(focusedIndex);
487 return (
488 <div
489 ref={containerRef}
490 className="relative"
491 style={virtualized ? { height: rows.length * range.rowHeight } : undefined}
492 onFocusCapture={(event) => {
493 const row = event.target.closest<HTMLElement>("[data-changed-file-row]");
494 setFocusedPath(row?.dataset.changedFileRow ?? null);
495 }}
496 onBlurCapture={(event) => {
497 if (!event.currentTarget.contains(event.relatedTarget)) setFocusedPath(null);
498 }}
499 >
500 {virtualized && (
501 <div
502 ref={rowSizeRef}
503 aria-hidden="true"
504 className="pointer-events-none invisible absolute h-7"
505 />
506 )}
507 {indices.map((index) => {
508 const row = rows[index]!;
509 return (
510 <div
511 key={`${row.node.kind}:${row.node.path}`}
512 data-changed-file-row={row.node.path}
513 className={virtualized ? "absolute inset-x-0" : undefined}
514 style={virtualized ? { top: index * range.rowHeight } : undefined}
515 >
516 {renderRow(row)}
517 </div>
518 );
519 })}
520 </div>
521 );
522}
523
524function collectExpandedRows(
525 nodes: ReadonlyArray<TurnDiffTreeNode>,
526 overrides: Readonly<Record<string, boolean>>,
527 allDirectoriesExpanded: boolean,
528 depth = 0,
529 rows: ChangedFileRow[] = [],
530): ChangedFileRow[] {
531 for (const node of nodes) {
532 rows.push({ node, depth });
533 if (node.kind === "directory" && (overrides[node.path] ?? allDirectoriesExpanded)) {
534 collectExpandedRows(node.children, overrides, allDirectoriesExpanded, depth + 1, rows);
535 }
536 }
537 return rows;
538}
539
540function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
541 const paths: string[] = [];
542 for (const node of nodes) {
543 if (node.kind !== "directory") continue;
544 paths.push(node.path);
545 paths.push(...collectDirectoryPaths(node.children));
546 }
547 return paths;
548}