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