Open History to see the last commit
1import { FileDiff, Virtualizer } from "@pierre/diffs/react";
2import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
3import { scopeThreadRef } from "@t3tools/client-runtime";
4import type { TurnId } from "@t3tools/contracts";
5import {
6 ChevronDownIcon,
7 ChevronLeftIcon,
8 ChevronRightIcon,
9 Columns2Icon,
10 PilcrowIcon,
11 Rows3Icon,
12 TextWrapIcon,
13} from "lucide-react";
14import {
15 type WheelEvent as ReactWheelEvent,
16 useCallback,
17 useEffect,
18 useMemo,
19 useRef,
20 useState,
21} from "react";
22import { openInPreferredEditor } from "../editorPreferences";
23import { useCheckpointDiff } from "~/lib/checkpointDiffState";
24import { useVcsStatus } from "~/lib/vcsStatusState";
25import { cn } from "~/lib/utils";
26import { readLocalApi } from "../localApi";
27import { resolvePathLinkTarget } from "../terminal-links";
28import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
29import { useTheme } from "../hooks/useTheme";
30import {
31 buildFileDiffRenderKey,
32 getDiffCollapseIconClassName,
33 getRenderablePatch,
34 resolveDiffThemeName,
35 resolveFileDiffPath,
36} from "../lib/diffRendering";
37import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
38import { selectProjectByRef, useStore } from "../store";
39import { createThreadSelectorByRef } from "../storeSelectors";
40import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
41import { useSettings } from "../hooks/useSettings";
42import { formatShortTimestamp } from "../timestampFormat";
43import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
44import { ToggleGroup, Toggle } from "./ui/toggle-group";
45
46type DiffRenderMode = "stacked" | "split";
47type DiffThemeType = "light" | "dark";
48
49const DIFF_PANEL_UNSAFE_CSS = `
50[data-diffs-header],
51[data-diff],
52[data-file],
53[data-error-wrapper],
54[data-virtualizer-buffer] {
55 --diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
56 --diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
57 --diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
58 --diffs-token-light-bg: transparent;
59 --diffs-token-dark-bg: transparent;
60
61 --diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
62 --diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
63 --diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
64 --diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
65
66 --diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
67 --diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
68 --diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
69 --diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
70
71 --diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
72 --diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
73 --diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
74 --diffs-bg-deletion-emphasis-override: color-mix(
75 in srgb,
76 var(--background) 80%,
77 var(--destructive)
78 );
79
80 background-color: var(--diffs-bg) !important;
81}
82
83[data-file-info] {
84 background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
85 border-block-color: var(--border) !important;
86 color: var(--foreground) !important;
87}
88
89[data-diffs-header] {
90 position: sticky !important;
91 top: 0;
92 z-index: 4;
93 background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
94 border-bottom: 1px solid var(--border) !important;
95}
96
97[data-title] {
98 cursor: pointer;
99 transition:
100 color 120ms ease,
101 text-decoration-color 120ms ease;
102 text-decoration: underline;
103 text-decoration-color: transparent;
104 text-underline-offset: 2px;
105}
106
107[data-title]:hover {
108 color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
109 text-decoration-color: currentColor;
110}
111`;
112
113interface DiffPanelProps {
114 mode?: DiffPanelMode;
115}
116
117export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
118
119export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
120 const navigate = useNavigate();
121 const { resolvedTheme } = useTheme();
122 const settings = useSettings();
123 const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
124 const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
125 const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
126 const [collapsedDiffFileKeys, setCollapsedDiffFileKeys] = useState<ReadonlySet<string>>(
127 () => new Set(),
128 );
129 const patchViewportRef = useRef<HTMLDivElement>(null);
130 const turnStripRef = useRef<HTMLDivElement>(null);
131 const previousDiffOpenRef = useRef(false);
132 const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
133 const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
134 const routeThreadRef = useParams({
135 strict: false,
136 select: (params) => resolveThreadRouteRef(params),
137 });
138 const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
139 const diffOpen = diffSearch.diff === "1";
140 const activeThreadId = routeThreadRef?.threadId ?? null;
141 const activeThread = useStore(
142 useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]),
143 );
144 const activeProjectId = activeThread?.projectId ?? null;
145 const activeProject = useStore((store) =>
146 activeThread && activeProjectId
147 ? selectProjectByRef(store, {
148 environmentId: activeThread.environmentId,
149 projectId: activeProjectId,
150 })
151 : undefined,
152 );
153 const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
154 const gitStatusQuery = useVcsStatus({
155 environmentId: activeThread?.environmentId ?? null,
156 cwd: activeCwd ?? null,
157 });
158 const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
159 const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
160 useTurnDiffSummaries(activeThread);
161 const orderedTurnDiffSummaries = useMemo(
162 () =>
163 [...turnDiffSummaries].toSorted((left, right) => {
164 const leftTurnCount =
165 left.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[left.turnId] ?? 0;
166 const rightTurnCount =
167 right.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[right.turnId] ?? 0;
168 if (leftTurnCount !== rightTurnCount) {
169 return rightTurnCount - leftTurnCount;
170 }
171 return right.completedAt.localeCompare(left.completedAt);
172 }),
173 [inferredCheckpointTurnCountByTurnId, turnDiffSummaries],
174 );
175
176 const selectedTurnId = diffSearch.diffTurnId ?? null;
177 const selectedFilePath = selectedTurnId !== null ? (diffSearch.diffFilePath ?? null) : null;
178 const selectedTurn =
179 selectedTurnId === null
180 ? undefined
181 : (orderedTurnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
182 orderedTurnDiffSummaries[0]);
183 const selectedCheckpointTurnCount =
184 selectedTurn &&
185 (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
186 const selectedCheckpointRange = useMemo(
187 () =>
188 typeof selectedCheckpointTurnCount === "number"
189 ? {
190 fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
191 toTurnCount: selectedCheckpointTurnCount,
192 }
193 : null,
194 [selectedCheckpointTurnCount],
195 );
196 const conversationCheckpointTurnCount = useMemo(() => {
197 const turnCounts: Array<number> = [];
198 for (const summary of orderedTurnDiffSummaries) {
199 const value =
200 summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];
201 if (typeof value === "number") {
202 turnCounts.push(value);
203 }
204 }
205 if (turnCounts.length === 0) {
206 return undefined;
207 }
208 const latest = Math.max(...turnCounts);
209 return latest > 0 ? latest : undefined;
210 }, [inferredCheckpointTurnCountByTurnId, orderedTurnDiffSummaries]);
211 const conversationCheckpointRange = useMemo(
212 () =>
213 !selectedTurn && typeof conversationCheckpointTurnCount === "number"
214 ? {
215 fromTurnCount: 0,
216 toTurnCount: conversationCheckpointTurnCount,
217 }
218 : null,
219 [conversationCheckpointTurnCount, selectedTurn],
220 );
221 const activeCheckpointRange = selectedTurn
222 ? selectedCheckpointRange
223 : conversationCheckpointRange;
224 const conversationCacheScope = useMemo(() => {
225 if (selectedTurn || orderedTurnDiffSummaries.length === 0) {
226 return null;
227 }
228 return `conversation:${orderedTurnDiffSummaries.map((summary) => summary.turnId).join(",")}`;
229 }, [orderedTurnDiffSummaries, selectedTurn]);
230 const activeCheckpointDiff = useCheckpointDiff(
231 {
232 environmentId: activeThread?.environmentId ?? null,
233 threadId: activeThreadId,
234 fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
235 toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
236 ignoreWhitespace: diffIgnoreWhitespace,
237 cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
238 },
239 { enabled: isGitRepo },
240 );
241 const selectedTurnCheckpointDiff = selectedTurn ? activeCheckpointDiff.data?.diff : undefined;
242 const conversationCheckpointDiff = selectedTurn ? undefined : activeCheckpointDiff.data?.diff;
243 const isLoadingCheckpointDiff = activeCheckpointDiff.isPending;
244 const checkpointDiffError = activeCheckpointDiff.error;
245
246 const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
247 const hasResolvedPatch = typeof selectedPatch === "string";
248 const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
249 const renderablePatch = useMemo(
250 () => getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`),
251 [resolvedTheme, selectedPatch],
252 );
253 const renderableFiles = useMemo(() => {
254 if (!renderablePatch || renderablePatch.kind !== "files") {
255 return [];
256 }
257 return renderablePatch.files.toSorted((left, right) =>
258 resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
259 numeric: true,
260 sensitivity: "base",
261 }),
262 );
263 }, [renderablePatch]);
264
265 useEffect(() => {
266 if (renderableFiles.length === 0) {
267 setCollapsedDiffFileKeys((current) => (current.size === 0 ? current : new Set()));
268 return;
269 }
270
271 const visibleFileKeys = new Set(renderableFiles.map(buildFileDiffRenderKey));
272 setCollapsedDiffFileKeys((current) => {
273 const next = new Set([...current].filter((fileKey) => visibleFileKeys.has(fileKey)));
274 return next.size === current.size ? current : next;
275 });
276 }, [renderableFiles]);
277
278 useEffect(() => {
279 if (diffOpen && !previousDiffOpenRef.current) {
280 setDiffWordWrap(settings.diffWordWrap);
281 setDiffIgnoreWhitespace(settings.diffIgnoreWhitespace);
282 }
283 previousDiffOpenRef.current = diffOpen;
284 }, [diffOpen, settings.diffIgnoreWhitespace, settings.diffWordWrap]);
285
286 useEffect(() => {
287 if (!selectedFilePath || !patchViewportRef.current) {
288 return;
289 }
290 const target = Array.from(
291 patchViewportRef.current.querySelectorAll<HTMLElement>("[data-diff-file-path]"),
292 ).find((element) => element.dataset.diffFilePath === selectedFilePath);
293 target?.scrollIntoView({ block: "nearest" });
294 }, [selectedFilePath, renderableFiles]);
295
296 const openDiffFileInEditor = useCallback(
297 (filePath: string) => {
298 const api = readLocalApi();
299 if (!api) return;
300 const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
301 void openInPreferredEditor(api, targetPath).catch((error) => {
302 console.warn("Failed to open diff file in editor.", error);
303 });
304 },
305 [activeCwd],
306 );
307 const toggleDiffFileCollapsed = useCallback((fileKey: string) => {
308 setCollapsedDiffFileKeys((current) => {
309 const next = new Set(current);
310 if (next.has(fileKey)) {
311 next.delete(fileKey);
312 } else {
313 next.add(fileKey);
314 }
315 return next;
316 });
317 }, []);
318
319 const selectTurn = (turnId: TurnId) => {
320 if (!activeThread) return;
321 void navigate({
322 to: "/$environmentId/$threadId",
323 params: buildThreadRouteParams(scopeThreadRef(activeThread.environmentId, activeThread.id)),
324 search: (previous) => {
325 const rest = stripDiffSearchParams(previous);
326 return { ...rest, diff: "1", diffTurnId: turnId };
327 },
328 });
329 };
330 const selectWholeConversation = () => {
331 if (!activeThread) return;
332 void navigate({
333 to: "/$environmentId/$threadId",
334 params: buildThreadRouteParams(scopeThreadRef(activeThread.environmentId, activeThread.id)),
335 search: (previous) => {
336 const rest = stripDiffSearchParams(previous);
337 return { ...rest, diff: "1" };
338 },
339 });
340 };
341 const updateTurnStripScrollState = useCallback(() => {
342 const element = turnStripRef.current;
343 if (!element) {
344 setCanScrollTurnStripLeft(false);
345 setCanScrollTurnStripRight(false);
346 return;
347 }
348
349 const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth);
350 setCanScrollTurnStripLeft(element.scrollLeft > 4);
351 setCanScrollTurnStripRight(element.scrollLeft < maxScrollLeft - 4);
352 }, []);
353 const scrollTurnStripBy = useCallback((offset: number) => {
354 const element = turnStripRef.current;
355 if (!element) return;
356 element.scrollBy({ left: offset, behavior: "smooth" });
357 }, []);
358 const onTurnStripWheel = useCallback((event: ReactWheelEvent<HTMLDivElement>) => {
359 const element = turnStripRef.current;
360 if (!element) return;
361 if (element.scrollWidth <= element.clientWidth + 1) return;
362 if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
363
364 event.preventDefault();
365 element.scrollBy({ left: event.deltaY, behavior: "auto" });
366 }, []);
367
368 useEffect(() => {
369 const element = turnStripRef.current;
370 if (!element) return;
371
372 const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
373 const onScroll = () => updateTurnStripScrollState();
374
375 element.addEventListener("scroll", onScroll, { passive: true });
376
377 const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
378 resizeObserver.observe(element);
379
380 return () => {
381 window.cancelAnimationFrame(frameId);
382 element.removeEventListener("scroll", onScroll);
383 resizeObserver.disconnect();
384 };
385 }, [updateTurnStripScrollState]);
386
387 useEffect(() => {
388 const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
389 return () => {
390 window.cancelAnimationFrame(frameId);
391 };
392 }, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
393
394 useEffect(() => {
395 const element = turnStripRef.current;
396 if (!element) return;
397
398 const selectedChip = element.querySelector<HTMLElement>("[data-turn-chip-selected='true']");
399 selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
400 }, [selectedTurn?.turnId, selectedTurnId]);
401
402 const headerRow = (
403 <>
404 <div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
405 <button
406 type="button"
407 className={cn(
408 "absolute left-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
409 canScrollTurnStripLeft
410 ? "border-border/70 hover:border-border hover:text-foreground"
411 : "cursor-not-allowed border-border/40 text-muted-foreground/40",
412 )}
413 onClick={() => scrollTurnStripBy(-180)}
414 disabled={!canScrollTurnStripLeft}
415 aria-label="Scroll turn list left"
416 >
417 <ChevronLeftIcon className="size-3.5" />
418 </button>
419 <button
420 type="button"
421 className={cn(
422 "absolute right-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
423 canScrollTurnStripRight
424 ? "border-border/70 hover:border-border hover:text-foreground"
425 : "cursor-not-allowed border-border/40 text-muted-foreground/40",
426 )}
427 onClick={() => scrollTurnStripBy(180)}
428 disabled={!canScrollTurnStripRight}
429 aria-label="Scroll turn list right"
430 >
431 <ChevronRightIcon className="size-3.5" />
432 </button>
433 <div
434 ref={turnStripRef}
435 className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
436 style={
437 canScrollTurnStripLeft || canScrollTurnStripRight
438 ? {
439 maskImage: `linear-gradient(to right, ${canScrollTurnStripLeft ? "transparent 24px, black 72px" : "black"}, ${canScrollTurnStripRight ? "black calc(100% - 72px), transparent calc(100% - 24px)" : "black"})`,
440 }
441 : undefined
442 }
443 onWheel={onTurnStripWheel}
444 >
445 <button
446 type="button"
447 className="shrink-0 rounded-md"
448 onClick={selectWholeConversation}
449 data-turn-chip-selected={selectedTurnId === null}
450 >
451 <div
452 className={cn(
453 "rounded-md border px-2 py-1 text-left transition-colors",
454 selectedTurnId === null
455 ? "border-border bg-accent text-accent-foreground"
456 : "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
457 )}
458 >
459 <div className="text-[10px] leading-tight font-medium">All turns</div>
460 </div>
461 </button>
462 {orderedTurnDiffSummaries.map((summary) => (
463 <button
464 key={summary.turnId}
465 type="button"
466 className="shrink-0 rounded-md"
467 onClick={() => selectTurn(summary.turnId)}
468 title={summary.turnId}
469 data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
470 >
471 <div
472 className={cn(
473 "rounded-md border px-2 py-1 text-left transition-colors",
474 summary.turnId === selectedTurn?.turnId
475 ? "border-border bg-accent text-accent-foreground"
476 : "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
477 )}
478 >
479 <div className="flex items-center gap-1">
480 <span className="text-[10px] leading-tight font-medium">
481 Turn{" "}
482 {summary.checkpointTurnCount ??
483 inferredCheckpointTurnCountByTurnId[summary.turnId] ??
484 "?"}
485 </span>
486 <span className="text-[9px] leading-tight opacity-70">
487 {formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
488 </span>
489 </div>
490 </div>
491 </button>
492 ))}
493 </div>
494 </div>
495 <div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
496 <ToggleGroup
497 className="shrink-0"
498 variant="outline"
499 size="xs"
500 value={[diffRenderMode]}
501 onValueChange={(value) => {
502 const next = value[0];
503 if (next === "stacked" || next === "split") {
504 setDiffRenderMode(next);
505 }
506 }}
507 >
508 <Toggle aria-label="Stacked diff view" value="stacked">
509 <Rows3Icon className="size-3" />
510 </Toggle>
511 <Toggle aria-label="Split diff view" value="split">
512 <Columns2Icon className="size-3" />
513 </Toggle>
514 </ToggleGroup>
515 <Toggle
516 aria-label={diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
517 title={diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
518 variant="outline"
519 size="xs"
520 pressed={diffWordWrap}
521 onPressedChange={(pressed) => {
522 setDiffWordWrap(Boolean(pressed));
523 }}
524 >
525 <TextWrapIcon className="size-3" />
526 </Toggle>
527 <Toggle
528 aria-label={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
529 title={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
530 variant="outline"
531 size="xs"
532 pressed={diffIgnoreWhitespace}
533 onPressedChange={(pressed) => {
534 setDiffIgnoreWhitespace(Boolean(pressed));
535 }}
536 >
537 <PilcrowIcon className="size-3" />
538 </Toggle>
539 </div>
540 </>
541 );
542
543 return (
544 <DiffPanelShell mode={mode} header={headerRow}>
545 {!activeThread ? (
546 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
547 Select a thread to inspect turn diffs.
548 </div>
549 ) : !isGitRepo ? (
550 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
551 Turn diffs are unavailable because this project is not a git repository.
552 </div>
553 ) : orderedTurnDiffSummaries.length === 0 ? (
554 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
555 No completed turns yet.
556 </div>
557 ) : (
558 <>
559 <div
560 ref={patchViewportRef}
561 className="diff-panel-viewport min-h-0 min-w-0 flex-1 overflow-hidden"
562 >
563 {checkpointDiffError && !renderablePatch && (
564 <div className="px-3">
565 <p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
566 </div>
567 )}
568 {!renderablePatch ? (
569 isLoadingCheckpointDiff ? (
570 <DiffPanelLoadingState label="Loading checkpoint diff..." />
571 ) : (
572 <div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
573 <p>
574 {hasNoNetChanges
575 ? "No net changes in this selection."
576 : "No patch available for this selection."}
577 </p>
578 </div>
579 )
580 ) : renderablePatch.kind === "files" ? (
581 <Virtualizer
582 className="diff-render-surface h-full min-h-0 overflow-auto px-2 pb-2"
583 config={{
584 overscrollSize: 600,
585 intersectionObserverMargin: 1200,
586 }}
587 >
588 {renderableFiles.map((fileDiff) => {
589 const filePath = resolveFileDiffPath(fileDiff);
590 const fileKey = buildFileDiffRenderKey(fileDiff);
591 const themedFileKey = `${fileKey}:${resolvedTheme}`;
592 const collapsed = collapsedDiffFileKeys.has(fileKey);
593 return (
594 <div
595 key={themedFileKey}
596 data-diff-file-path={filePath}
597 className="diff-render-file group/diff-file mb-2 rounded-md first:mt-2 last:mb-0"
598 onClickCapture={(event) => {
599 const nativeEvent = event.nativeEvent as MouseEvent;
600 const composedPath = nativeEvent.composedPath?.() ?? [];
601 const clickedHeader = composedPath.some((node) => {
602 if (!(node instanceof Element)) return false;
603 return node.hasAttribute("data-title");
604 });
605 if (!clickedHeader) return;
606 openDiffFileInEditor(filePath);
607 }}
608 >
609 <FileDiff
610 fileDiff={fileDiff}
611 renderHeaderPrefix={() => (
612 <button
613 type="button"
614 className={cn(
615 "inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
616 getDiffCollapseIconClassName(fileDiff),
617 )}
618 aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
619 aria-expanded={!collapsed}
620 title={collapsed ? "Expand diff" : "Collapse diff"}
621 onClick={(event) => {
622 event.stopPropagation();
623 toggleDiffFileCollapsed(fileKey);
624 }}
625 >
626 {collapsed ? (
627 <ChevronRightIcon className="size-4" />
628 ) : (
629 <ChevronDownIcon className="size-4" />
630 )}
631 </button>
632 )}
633 options={{
634 collapsed,
635 diffStyle: diffRenderMode === "split" ? "split" : "unified",
636 lineDiffType: "none",
637 overflow: diffWordWrap ? "wrap" : "scroll",
638 theme: resolveDiffThemeName(resolvedTheme),
639 themeType: resolvedTheme as DiffThemeType,
640 unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
641 }}
642 />
643 </div>
644 );
645 })}
646 </Virtualizer>
647 ) : (
648 <div className="h-full overflow-auto p-2">
649 <div className="space-y-2">
650 <p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
651 <pre
652 className={cn(
653 "max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
654 diffWordWrap
655 ? "overflow-auto whitespace-pre-wrap wrap-break-word"
656 : "overflow-auto",
657 )}
658 >
659 {renderablePatch.text}
660 </pre>
661 </div>
662 </div>
663 )}
664 </div>
665 </>
666 )}
667 </DiffPanelShell>
668 );
669}