forked from databendlabs/snowtree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPierreDiffViewer.tsx
More file actions
978 lines (894 loc) · 35.3 KB
/
PierreDiffViewer.tsx
File metadata and controls
978 lines (894 loc) · 35.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Check, ChevronRight, Eye, EyeOff, Minus, Plus, RotateCcw, UnfoldVertical } from 'lucide-react';
import { FileDiff, WorkerPoolContextProvider } from '@pierre/diffs/react';
import { parsePatchFiles, type DiffLineAnnotation, type FileDiffMetadata, type Hunk } from '@pierre/diffs';
import { API } from '../../../utils/api';
import { withTimeout } from '../../../utils/withTimeout';
import { workerFactory } from '../../../utils/diffsWorker';
import { useThemeStore } from '../../../stores/themeStore';
import { ImagePreview } from './ImagePreview';
import { MarkdownPreview } from './MarkdownPreview';
import { useFilePreviewState } from './useFilePreviewState';
import { isBinaryFile, isImageFile, isPreviewableFile } from './utils/fileUtils';
import { findMatchingHeader, type HunkHeaderEntry } from './utils/diffUtils';
const FILE_CONTENT_TIMEOUT_MS = 15_000;
const FILE_CONTENT_MAX_BYTES = 10 * 1024 * 1024;
const DIFF_SCROLL_CSS = `
[data-column-number],
[data-buffer],
[data-separator-wrapper],
[data-annotation-content] {
position: static !important;
}
[data-buffer] {
background-image: none !important;
}
[data-line-annotation] {
min-height: 0 !important;
}
[data-annotation-content] {
display: flex !important;
align-items: center !important;
height: auto !important;
padding: 1px 8px 2px 8px !important;
}
diffs-container,
[data-diffs],
[data-diffs-header],
[data-error-wrapper] {
position: relative !important;
contain: layout style !important;
isolation: isolate !important;
}
`;
function createConcurrencyLimiter(maxConcurrent: number) {
let active = 0;
const queue: Array<() => void> = [];
const runNext = () => {
if (active >= maxConcurrent) return;
const next = queue.shift();
if (!next) return;
active++;
next();
};
return async function limit<T>(task: () => Promise<T>): Promise<T> {
return await new Promise<T>((resolve, reject) => {
const exec = () => {
task()
.then(resolve, reject)
.finally(() => {
active--;
runNext();
});
};
queue.push(exec);
runNext();
});
};
}
// Prevent a thundering herd of `git show` calls when rendering large diffs.
const limitFileContentReads = createConcurrencyLimiter(6);
function splitLinesPreserveNewline(contents: string): string[] {
if (!contents) return [];
const out: string[] = [];
let start = 0;
for (let i = 0; i < contents.length; i++) {
if (contents[i] === '\n') {
out.push(contents.slice(start, i + 1));
start = i + 1;
}
}
if (start < contents.length) out.push(contents.slice(start));
return out;
}
function normalizePatchName(name: string): string {
if (!name) return name;
return name.replace(/^(?:a|b)\//, '');
}
function extractFileDiffs(diffText: string): FileDiffMetadata[] {
const trimmed = (diffText || '').trim();
if (!trimmed) return [];
const patches = parsePatchFiles(trimmed);
const files = patches.flatMap((p) => p.files || []);
return files
.filter((f) => Boolean(f && f.name))
.map((f) => ({
...f,
name: normalizePatchName(f.name),
prevName: f.prevName ? normalizePatchName(f.prevName) : f.prevName,
}));
}
function orderFileDiffs(files: FileDiffMetadata[], fileOrder?: string[]): FileDiffMetadata[] {
if (!fileOrder || fileOrder.length === 0) return files;
const byPath = new Map<string, FileDiffMetadata[]>();
for (const f of files) {
const list = byPath.get(f.name) ?? [];
list.push(f);
byPath.set(f.name, list);
}
const ordered: FileDiffMetadata[] = [];
for (const path of fileOrder) {
const list = byPath.get(path);
if (!list || list.length === 0) continue;
ordered.push(list.shift()!);
if (list.length === 0) byPath.delete(path);
else byPath.set(path, list);
}
for (const f of files) {
const list = byPath.get(f.name);
if (!list || list.length === 0) continue;
if (list[0] === f) {
ordered.push(f);
list.shift();
if (list.length === 0) byPath.delete(f.name);
else byPath.set(f.name, list);
}
}
return ordered;
}
function hunkSignature(hunk: Hunk): string {
const parts: string[] = [];
for (const content of hunk.hunkContent) {
if (content.type !== 'change') continue;
for (const line of content.deletions) parts.push(`-${line}`);
for (const line of content.additions) parts.push(`+${line}`);
}
return parts.join('\n');
}
function buildHunkHeaderEntries(diffText: string | undefined): Map<string, HunkHeaderEntry[]> {
const map = new Map<string, HunkHeaderEntry[]>();
if (!diffText || !diffText.trim()) return map;
for (const file of extractFileDiffs(diffText)) {
const entries: HunkHeaderEntry[] = [];
for (const hunk of file.hunks) {
const sig = hunkSignature(hunk);
if (!sig) continue;
entries.push({
sig,
oldStart: hunk.deletionStart,
newStart: hunk.additionStart,
header: hunk.hunkSpecs ?? '',
});
}
if (entries.length > 0) map.set(file.name, entries);
}
return map;
}
async function requestFileContent(sessionId: string, filePath: string, ref: string): Promise<string | null> {
return limitFileContentReads(async () => {
const response = await withTimeout(
API.sessions.getFileContent(sessionId, { filePath, ref, maxBytes: FILE_CONTENT_MAX_BYTES }),
FILE_CONTENT_TIMEOUT_MS,
'Load file content'
);
if (!response.success) return null;
return response.data?.content ?? '';
});
}
type PierreDiffViewerProps = {
diff: string;
sessionId?: string;
target?: { kind: 'working'; scope?: 'all' | 'staged' | 'unstaged' | 'untracked' } | { kind: 'commit'; hash: string };
stagedDiff?: string;
unstagedDiff?: string;
previewFileSources?: Record<string, string>;
scrollToFilePath?: string;
fileOrder?: string[];
className?: string;
onChanged?: () => void;
};
type HunkMeta = {
index: number;
sig: string;
oldStart: number;
oldCount: number;
newStart: number;
newCount: number;
header: string;
stagedHeader: string | null;
unstagedHeader: string | null;
status: 'staged' | 'unstaged' | 'untracked';
};
type HunkStatusAnnotation = {
status: HunkMeta['status'];
label: string;
};
function findHoveredHunk(hunks: HunkMeta[], lineNumber: number, side: 'deletions' | 'additions'): HunkMeta | null {
if (!Number.isFinite(lineNumber)) return null;
for (const hunk of hunks) {
if (side === 'deletions') {
if (hunk.oldCount > 0 && lineNumber >= hunk.oldStart && lineNumber <= hunk.oldStart + hunk.oldCount - 1) return hunk;
} else {
if (hunk.newCount > 0 && lineNumber >= hunk.newStart && lineNumber <= hunk.newStart + hunk.newCount - 1) return hunk;
}
}
// Fallback: if we can't map by side (e.g., unified), try either range.
for (const hunk of hunks) {
if (hunk.oldCount > 0 && lineNumber >= hunk.oldStart && lineNumber <= hunk.oldStart + hunk.oldCount - 1) return hunk;
if (hunk.newCount > 0 && lineNumber >= hunk.newStart && lineNumber <= hunk.newStart + hunk.newCount - 1) return hunk;
}
return null;
}
function getRequiredFileLineCount(fileDiff: FileDiffMetadata): { old: number; next: number } {
let oldMax = 0;
let nextMax = 0;
for (const hunk of fileDiff.hunks) {
// Use the hunk header ranges (deletion/addition counts include context lines).
// If the fetched file content is shorter than these ranges, @pierre/diffs can
// produce invalid Shiki decorations due to mismatched line indexing.
const oldEnd = hunk.deletionStart + Math.max(hunk.deletionCount, 0) - 1;
const nextEnd = hunk.additionStart + Math.max(hunk.additionCount, 0) - 1;
oldMax = Math.max(oldMax, Math.max(oldEnd, hunk.deletionStart - 1));
nextMax = Math.max(nextMax, Math.max(nextEnd, hunk.additionStart - 1));
}
return { old: oldMax, next: nextMax };
}
const FileCard = memo(function FileCard({
fileDiff,
stagedEntries,
unstagedEntries,
previewContent,
isCommitView,
sessionId,
target,
enableContextLoading,
onChanged,
scrollToSelf,
isPreviewing,
onTogglePreview,
themeType,
isReviewed,
onToggleReviewed,
isCollapsed,
onToggleCollapsed,
}: {
fileDiff: FileDiffMetadata;
stagedEntries: HunkHeaderEntry[] | undefined;
unstagedEntries: HunkHeaderEntry[] | undefined;
previewContent: string | undefined;
isCommitView: boolean;
sessionId?: string;
target?: PierreDiffViewerProps['target'];
enableContextLoading: boolean;
onChanged?: () => void;
scrollToSelf?: boolean;
isPreviewing: boolean;
onTogglePreview: () => void;
themeType: 'light' | 'dark';
isReviewed: boolean;
onToggleReviewed: () => void;
isCollapsed: boolean;
onToggleCollapsed: () => void;
}) {
const headerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!scrollToSelf) return;
headerRef.current?.scrollIntoView({ block: 'start' });
}, [scrollToSelf]);
const [pendingKeys, setPendingKeys] = useState<Set<string>>(() => new Set());
const setPending = useCallback((key: string, pending: boolean) => {
setPendingKeys((prev) => {
const next = new Set(prev);
if (pending) next.add(key);
else next.delete(key);
return next;
});
}, []);
// Flash feedback: tracks which button key just completed an action
const [flashKey, setFlashKey] = useState<string | null>(null);
const flashTimeout = useRef<ReturnType<typeof setTimeout>>(undefined);
const triggerFlash = useCallback((key: string) => {
setFlashKey(key);
clearTimeout(flashTimeout.current);
flashTimeout.current = setTimeout(() => setFlashKey(null), 600);
}, []);
useEffect(() => () => clearTimeout(flashTimeout.current), []);
const hunksMeta = useMemo<HunkMeta[]>(() => {
return fileDiff.hunks.map((hunk, idx) => {
const sig = hunkSignature(hunk);
const oldStart = hunk.deletionStart;
const newStart = hunk.additionStart;
const stagedHeader = findMatchingHeader(stagedEntries, sig, oldStart, newStart);
const unstagedHeader = findMatchingHeader(unstagedEntries, sig, oldStart, newStart);
const status: HunkMeta['status'] = stagedHeader ? 'staged' : unstagedHeader ? 'unstaged' : 'untracked';
return {
index: idx,
sig,
oldStart,
oldCount: hunk.deletionCount,
newStart,
newCount: hunk.additionCount,
header: hunk.hunkSpecs ?? '',
stagedHeader,
unstagedHeader,
status,
};
});
}, [fileDiff.hunks, stagedEntries, unstagedEntries]);
const hasStaged = Boolean(stagedEntries && stagedEntries.length > 0);
const hasUnstaged = Boolean(unstagedEntries && unstagedEntries.length > 0);
const isFullyStaged = hasStaged && !hasUnstaged;
const isFullyUnstaged = !hasStaged && hasUnstaged;
const hunkStatusAnnotations = useMemo<DiffLineAnnotation<HunkStatusAnnotation>[]>(() => {
if (isCommitView) return [];
const annotations: DiffLineAnnotation<HunkStatusAnnotation>[] = [];
const seen = new Set<string>();
for (const hunk of hunksMeta) {
const lineNumber = hunk.newStart > 0 ? hunk.newStart : hunk.oldStart;
if (!Number.isFinite(lineNumber) || lineNumber <= 0) continue;
const key = `${lineNumber}:${hunk.status}`;
if (seen.has(key)) continue;
seen.add(key);
annotations.push({
side: 'additions',
lineNumber,
metadata: {
status: hunk.status,
label: hunk.status === 'staged' ? 'Staged' : hunk.status === 'unstaged' ? 'Unstaged' : 'Untracked',
},
});
}
return annotations;
}, [hunksMeta, isCommitView]);
const renderHunkStatusAnnotation = useCallback((annotation: DiffLineAnnotation<HunkStatusAnnotation>) => {
const metadata = annotation.metadata;
if (!metadata) return null;
const tone =
metadata.status === 'staged'
? {
bg: 'color-mix(in srgb, var(--st-success) 16%, transparent)',
border: 'color-mix(in srgb, var(--st-success) 42%, transparent)',
dot: 'var(--st-success)',
}
: metadata.status === 'unstaged'
? {
bg: 'color-mix(in srgb, var(--st-warning) 14%, transparent)',
border: 'color-mix(in srgb, var(--st-warning) 38%, transparent)',
dot: 'var(--st-warning)',
}
: {
bg: 'color-mix(in srgb, var(--st-accent) 14%, transparent)',
border: 'color-mix(in srgb, var(--st-accent) 36%, transparent)',
dot: 'var(--st-accent)',
};
return (
<span
className="inline-flex items-center gap-1 rounded border px-1.5 py-[1px] text-[10px] font-medium leading-none select-none pointer-events-none"
style={{ backgroundColor: tone.bg, borderColor: tone.border, color: 'var(--st-text-faint)' }}
>
<span className="inline-block w-1.5 h-1.5 rounded-full" style={{ backgroundColor: tone.dot }} />
{metadata.label}
</span>
);
}, []);
const stageFile = useCallback(
async (stage: boolean) => {
if (!sessionId) return;
const key = `file:${fileDiff.name}`;
try {
setPending(key, true);
await API.sessions.changeFileStage(sessionId, { filePath: fileDiff.name, stage });
triggerFlash(stage ? 'file-stage' : 'file-unstage');
onChanged?.();
} catch (err) {
console.error(`[Diffs] Failed to ${stage ? 'stage' : 'unstage'} file`, { filePath: fileDiff.name, err });
} finally {
setPending(key, false);
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
}
},
[fileDiff.name, onChanged, sessionId, setPending, triggerFlash]
);
const restoreFile = useCallback(async () => {
if (!sessionId) return;
const key = `file:${fileDiff.name}:restore`;
try {
setPending(key, true);
await API.sessions.restoreFile(sessionId, { filePath: fileDiff.name });
triggerFlash('file-restore');
onChanged?.();
} catch (err) {
console.error('[Diffs] Failed to restore file', { filePath: fileDiff.name, err });
} finally {
setPending(key, false);
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
}
}, [fileDiff.name, onChanged, sessionId, setPending, triggerFlash]);
const stageHunk = useCallback(
async (hunk: HunkMeta, stage: boolean) => {
if (!sessionId) return;
const key = `hunk:${fileDiff.name}:${hunk.index}`;
try {
setPending(key, true);
await API.sessions.stageHunk(sessionId, { filePath: fileDiff.name, isStaging: stage, hunkHeader: hunk.stagedHeader || hunk.unstagedHeader || hunk.header });
triggerFlash(`hunk-${stage ? 'stage' : 'unstage'}-${hunk.index}`);
onChanged?.();
} catch (err) {
console.error(`[Diffs] Failed to ${stage ? 'stage' : 'unstage'} hunk`, { filePath: fileDiff.name, hunkHeader: hunk.header, err });
} finally {
setPending(key, false);
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
}
},
[fileDiff.name, onChanged, sessionId, setPending, triggerFlash]
);
const restoreHunk = useCallback(
async (hunk: HunkMeta) => {
if (!sessionId) return;
const key = `hunk:${fileDiff.name}:${hunk.index}:restore`;
if (hunk.status !== 'staged' && hunk.status !== 'unstaged') return;
try {
setPending(key, true);
await API.sessions.restoreHunk(sessionId, { filePath: fileDiff.name, scope: hunk.status, hunkHeader: hunk.stagedHeader || hunk.unstagedHeader || hunk.header });
triggerFlash(`hunk-restore-${hunk.index}`);
onChanged?.();
} catch (err) {
console.error('[Diffs] Failed to restore hunk', { filePath: fileDiff.name, hunkHeader: hunk.header, err });
} finally {
setPending(key, false);
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
}
},
[fileDiff.name, onChanged, sessionId, setPending, triggerFlash]
);
const [hoveredHunk, setHoveredHunk] = useState<HunkMeta | null>(null);
const enableHoverUtility = !isCommitView && Boolean(sessionId);
const targetKind = target?.kind;
const targetHash = target?.kind === 'commit' ? target.hash : null;
const oldRef = targetKind === 'working' ? 'HEAD' : targetHash ? `${targetHash}^` : null;
const newRef = targetKind === 'working' ? 'WORKTREE' : targetHash;
const [isContextEnabled, setIsContextEnabled] = useState<boolean>(() => Boolean(scrollToSelf));
const [isContextLoading, setIsContextLoading] = useState(false);
const [contextRequestId, setContextRequestId] = useState(0);
useEffect(() => {
if (scrollToSelf) setIsContextEnabled(true);
}, [scrollToSelf]);
const [contextLines, setContextLines] = useState<{ oldLines: string[]; newLines: string[] } | null>(null);
const shouldLoadContext = useMemo(() => {
if (!isContextEnabled) return false;
if (!sessionId || !enableContextLoading || oldRef == null || newRef == null) return false;
if (fileDiff.type === 'new' || fileDiff.type === 'deleted') return false;
return fileDiff.hunks.length > 0;
}, [enableContextLoading, fileDiff.hunks.length, fileDiff.type, isContextEnabled, newRef, oldRef, sessionId]);
const contextLoadKey = useMemo(() => {
if (!shouldLoadContext || oldRef == null || newRef == null) return null;
const oldPath = fileDiff.prevName || fileDiff.name;
const newPath = fileDiff.name;
return `${oldRef}:${oldPath}=>${newRef}:${newPath}#${contextRequestId}`;
}, [contextRequestId, fileDiff.name, fileDiff.prevName, newRef, oldRef, shouldLoadContext]);
useEffect(() => {
if (!sessionId || !shouldLoadContext || contextLoadKey == null || oldRef == null || newRef == null) {
setContextLines(null);
setIsContextLoading(false);
return;
}
let cancelled = false;
setIsContextLoading(true);
void (async () => {
try {
const oldPath = fileDiff.prevName || fileDiff.name;
const newPath = fileDiff.name;
const [oldContent, newContent] = await Promise.all([
requestFileContent(sessionId, oldPath, oldRef),
requestFileContent(sessionId, newPath, newRef),
]);
if (cancelled) return;
if (oldContent == null || newContent == null) return;
const oldLines = splitLinesPreserveNewline(oldContent);
const newLines = splitLinesPreserveNewline(newContent);
const required = getRequiredFileLineCount(fileDiff);
const hasEnoughLines = oldLines.length >= required.old && newLines.length >= required.next;
if (!hasEnoughLines) return;
setContextLines({ oldLines, newLines });
} catch {
// best-effort
} finally {
if (!cancelled) setIsContextLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [contextLoadKey, fileDiff, newRef, oldRef, sessionId, shouldLoadContext]);
const diffOptions = useMemo(() => {
const base = {
diffStyle: 'unified' as const,
hunkSeparators: 'line-info' as const,
expansionLineCount: 20,
overflow: 'scroll' as const,
themeType: themeType as 'light' | 'dark',
disableFileHeader: true,
unsafeCSS: DIFF_SCROLL_CSS,
enableHoverUtility,
onLineEnter: (props: any) => {
const h = findHoveredHunk(hunksMeta, props.lineNumber, props.annotationSide);
setHoveredHunk(h);
},
onLineLeave: () => {
setHoveredHunk(null);
},
};
if (!enableHoverUtility) {
return {
diffStyle: base.diffStyle,
hunkSeparators: base.hunkSeparators,
expansionLineCount: base.expansionLineCount,
overflow: base.overflow,
themeType: base.themeType,
disableFileHeader: true,
unsafeCSS: DIFF_SCROLL_CSS,
};
}
return base;
}, [enableHoverUtility, hunksMeta, themeType]);
const fileDiffForRender = useMemo(() => {
if (!contextLines) return fileDiff;
return {
...fileDiff,
oldLines: contextLines.oldLines,
newLines: contextLines.newLines,
} satisfies FileDiffMetadata;
}, [contextLines, fileDiff]);
const hoverUtility = useMemo(() => {
if (!enableHoverUtility || hoveredHunk == null) return null;
const canStageOrUnstage = Boolean(sessionId);
const isPending = pendingKeys.has(`hunk:${fileDiff.name}:${hoveredHunk.index}`);
const isRestorePending = pendingKeys.has(`hunk:${fileDiff.name}:${hoveredHunk.index}:restore`);
const stageLabel = hoveredHunk.status === 'staged' ? 'Unstage' : 'Stage';
const canRestore = hoveredHunk.status === 'staged' || hoveredHunk.status === 'unstaged';
return (
<div className="flex h-full items-center gap-1 pr-1">
<button
type="button"
className="st-icon-button st-focus-ring !w-5 !h-5 disabled:opacity-40"
data-testid="diff-hunk-stage"
title={stageLabel}
disabled={!canStageOrUnstage || isPending}
onClick={(e) => {
e.stopPropagation();
if (hoveredHunk.status === 'untracked') return stageFile(true);
if (fileDiff.type === 'deleted') return stageFile(stageLabel === 'Stage');
return stageHunk(hoveredHunk, stageLabel === 'Stage');
}}
>
{stageLabel === 'Stage' ? <Plus className="w-3.5 h-3.5" /> : <Minus className="w-3.5 h-3.5" />}
</button>
<button
type="button"
className="st-icon-button st-focus-ring !w-5 !h-5 disabled:opacity-40"
data-testid="diff-hunk-restore"
title="Restore"
disabled={!canRestore || isRestorePending}
onClick={(e) => {
e.stopPropagation();
if (fileDiff.type === 'deleted') return restoreFile();
return restoreHunk(hoveredHunk);
}}
>
<RotateCcw className="w-3.5 h-3.5" />
</button>
</div>
);
}, [enableHoverUtility, fileDiff.name, fileDiff.type, hoveredHunk, pendingKeys, restoreFile, restoreHunk, sessionId, stageFile, stageHunk]);
const containerStyle = useMemo(
() =>
({
['--diffs-font-family' as any]: 'var(--st-font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, monospace)',
['--diffs-font-size' as any]: 'var(--st-font-sm, 12px)',
['--diffs-line-height' as any]: 1.5,
['--diffs-tab-size' as any]: 2,
// Reserve enough space for per-hunk hover controls in the gutter.
['--diffs-min-number-column-width' as any]: '6ch',
['--diffs-light-bg' as any]: 'var(--st-diff-bg, var(--st-bg))',
['--diffs-dark-bg' as any]: 'var(--st-diff-bg, var(--st-bg))',
['--diffs-addition-color-override' as any]: 'var(--st-diff-added-marker)',
['--diffs-deletion-color-override' as any]: 'var(--st-diff-deleted-marker)',
['--diffs-modified-color-override' as any]: 'var(--st-diff-modified-marker)',
['--diffs-fg-number-override' as any]: 'var(--st-diff-gutter-fg)',
}) as React.CSSProperties,
[]
);
const canPreview = Boolean(previewContent) && isPreviewableFile(fileDiff.name);
const canLoadContext = Boolean(
sessionId &&
enableContextLoading &&
oldRef != null &&
newRef != null &&
fileDiff.type !== 'new' &&
fileDiff.type !== 'deleted' &&
fileDiff.hunks.length > 0
);
const flashStyle = useCallback(
(key: string): React.CSSProperties =>
flashKey === key
? { animation: 'st-btn-flash 0.6s ease-out' }
: {},
[flashKey]
);
return (
<div className="st-diff-file" data-testid="diff-file" data-diff-file-path={fileDiff.name}>
<div
ref={headerRef}
data-testid="diff-file-header"
className="sticky top-0 z-20 px-3 py-2 text-xs font-semibold flex items-center justify-between gap-2"
style={{ backgroundColor: 'var(--st-surface)', borderBottom: '1px solid var(--st-border-variant)' }}
>
<div className="flex items-center gap-1.5 min-w-0 flex-1">
<button
type="button"
className="st-icon-button st-focus-ring !w-5 !h-5 flex-shrink-0"
onClick={onToggleCollapsed}
title={isCollapsed ? 'Expand file' : 'Collapse file'}
>
<ChevronRight
className="w-3.5 h-3.5 transition-transform duration-150"
style={{ transform: isCollapsed ? 'rotate(0deg)' : 'rotate(90deg)' }}
/>
</button>
<div className="min-w-0 flex-1 cursor-pointer" onClick={onToggleCollapsed}>
<div className="font-mono truncate" title={fileDiff.name}>
{fileDiff.name}
{isReviewed && (
<span
className="ml-2 inline-flex items-center gap-0.5 rounded border px-1 py-[1px] text-[10px] font-medium leading-none select-none align-middle"
style={{
backgroundColor: 'color-mix(in srgb, var(--st-success) 12%, transparent)',
borderColor: 'color-mix(in srgb, var(--st-success) 30%, transparent)',
color: 'var(--st-text-faint)',
}}
>
Viewed
</span>
)}
</div>
{fileDiff.prevName && fileDiff.prevName !== fileDiff.name && (
<div className="text-[11px] font-mono truncate mt-0.5" style={{ color: 'var(--st-text-faint)' }} title={fileDiff.prevName}>
{fileDiff.prevName}
</div>
)}
</div>
</div>
<div className="flex items-center gap-1.5 flex-shrink-0">
{!isCommitView && (
<button
type="button"
className="st-icon-button st-focus-ring !w-5 !h-5"
onClick={onToggleReviewed}
title={isReviewed ? 'Mark as not reviewed' : 'Mark as reviewed'}
style={isReviewed ? { color: 'var(--st-success)' } : { color: 'var(--st-text-faint)' }}
>
<Check className="w-3.5 h-3.5" />
</button>
)}
{canLoadContext && !contextLines && (
<button
type="button"
className="st-icon-button st-focus-ring disabled:opacity-40"
onClick={() => {
setIsContextEnabled(true);
setContextRequestId((v) => v + 1);
}}
disabled={isContextLoading}
title={isContextLoading ? 'Loading context...' : 'Load context for expand'}
>
<UnfoldVertical className={`w-3.5 h-3.5 ${isContextLoading ? 'animate-spin' : ''}`} />
</button>
)}
{canPreview && (
<button
type="button"
className="st-icon-button st-focus-ring"
onClick={onTogglePreview}
title={isPreviewing ? 'Show diff' : 'Preview'}
>
{isPreviewing ? <EyeOff className="w-3.5 h-3.5" /> : <Eye className="w-3.5 h-3.5" />}
</button>
)}
{!isCommitView && (
<>
{!isFullyStaged && (
<button
type="button"
className="px-2 py-1 rounded text-[11px] font-medium st-focus-ring disabled:opacity-40"
style={{ backgroundColor: 'color-mix(in srgb, var(--st-success) 14%, transparent)', color: 'var(--st-text)', ...flashStyle('file-stage') }}
disabled={!sessionId || pendingKeys.has(`file:${fileDiff.name}`)}
onClick={() => stageFile(true)}
title="Stage file"
>
Stage
</button>
)}
{!isFullyUnstaged && hasStaged && (
<button
type="button"
className="px-2 py-1 rounded text-[11px] font-medium st-focus-ring disabled:opacity-40"
style={{ backgroundColor: 'color-mix(in srgb, var(--st-warning) 14%, transparent)', color: 'var(--st-text)', ...flashStyle('file-unstage') }}
disabled={!sessionId || pendingKeys.has(`file:${fileDiff.name}`)}
onClick={() => stageFile(false)}
title="Unstage file"
>
Unstage
</button>
)}
<span className="w-px h-4 mx-0.5" style={{ backgroundColor: 'var(--st-border-variant)' }} />
<button
type="button"
className="px-2 py-1 rounded text-[11px] font-medium st-focus-ring disabled:opacity-40"
style={{ backgroundColor: 'color-mix(in srgb, var(--st-danger) 10%, transparent)', color: 'var(--st-text)', ...flashStyle('file-restore') }}
disabled={!sessionId || pendingKeys.has(`file:${fileDiff.name}:restore`)}
onClick={() => restoreFile()}
title="Restore file"
>
Restore
</button>
</>
)}
</div>
</div>
{!isCollapsed && (
<div style={containerStyle}>
{isPreviewing && previewContent ? (
isImageFile(fileDiff.name) ? (
<ImagePreview content={previewContent} filePath={fileDiff.name} />
) : (
<MarkdownPreview content={previewContent} />
)
) : fileDiff.hunks.length === 0 ? (
<div className="px-3 py-6 text-xs" style={{ color: 'var(--st-text-faint)' }}>
{isImageFile(fileDiff.name) ? 'Binary file (image)' : isBinaryFile(fileDiff.name) ? 'Binary file' : 'Diff unavailable.'}
</div>
) : (
<FileDiff<HunkStatusAnnotation>
fileDiff={fileDiffForRender}
options={diffOptions as any}
lineAnnotations={hunkStatusAnnotations}
renderAnnotation={renderHunkStatusAnnotation}
renderHoverUtility={() => hoverUtility}
style={{ width: '100%', maxWidth: '100%', minWidth: 0 }}
/>
)}
</div>
)}
</div>
);
});
export const PierreDiffViewer: React.FC<PierreDiffViewerProps> = memo(function PierreDiffViewer({
diff,
sessionId,
target,
stagedDiff,
unstagedDiff,
previewFileSources,
scrollToFilePath,
fileOrder,
className,
onChanged,
}: PierreDiffViewerProps) {
const theme = useThemeStore((s) => s.theme);
const themeType = theme === 'light' ? 'light' : 'dark';
const isCommitView = target?.kind === 'commit';
const parsedFiles = useMemo(() => {
return orderFileDiffs(extractFileDiffs(diff), fileOrder);
}, [diff, fileOrder]);
const stagedEntriesByFile = useMemo(() => buildHunkHeaderEntries(stagedDiff), [stagedDiff]);
const unstagedEntriesByFile = useMemo(() => buildHunkHeaderEntries(unstagedDiff), [unstagedDiff]);
// --- Reviewed / collapsed file tracking ---
// reviewedFiles: Map<filePath, diffSignature> — stores the diff signature at the time of marking reviewed
const [reviewedFiles, setReviewedFiles] = useState<Map<string, string>>(() => new Map());
const [collapsedFiles, setCollapsedFiles] = useState<Set<string>>(() => new Set());
// Compute a simple signature per file for change detection
const fileDiffSignatures = useMemo(() => {
const sigs = new Map<string, string>();
for (const file of parsedFiles) {
const parts = file.hunks.map((h) => hunkSignature(h));
sigs.set(file.name, parts.join('\n---\n'));
}
return sigs;
}, [parsedFiles]);
// When diff changes, check if any reviewed file's signature changed — if so, un-collapse and un-review it
useEffect(() => {
setReviewedFiles((prev) => {
let changed = false;
const next = new Map(prev);
for (const [path, oldSig] of prev) {
const currentSig = fileDiffSignatures.get(path);
if (currentSig === undefined || currentSig !== oldSig) {
next.delete(path);
changed = true;
}
}
if (!changed) return prev;
// Also un-collapse those files
setCollapsedFiles((prevCollapsed) => {
const nextCollapsed = new Set(prevCollapsed);
for (const [path] of prev) {
const currentSig = fileDiffSignatures.get(path);
if (currentSig === undefined || currentSig !== prev.get(path)) {
nextCollapsed.delete(path);
}
}
return nextCollapsed;
});
return next;
});
}, [fileDiffSignatures]);
const toggleReviewed = useCallback((filePath: string) => {
setReviewedFiles((prev) => {
const next = new Map(prev);
if (next.has(filePath)) {
next.delete(filePath);
// Un-collapse when un-reviewing
setCollapsedFiles((c) => {
const nc = new Set(c);
nc.delete(filePath);
return nc;
});
} else {
// Mark reviewed with current signature, and collapse
next.set(filePath, fileDiffSignatures.get(filePath) ?? '');
setCollapsedFiles((c) => new Set(c).add(filePath));
}
return next;
});
}, [fileDiffSignatures]);
const toggleCollapsed = useCallback((filePath: string) => {
setCollapsedFiles((prev) => {
const next = new Set(prev);
if (next.has(filePath)) next.delete(filePath);
else next.add(filePath);
return next;
});
}, []);
const autoPreviewPaths = useMemo(() => {
return parsedFiles.map((f) => f.name).filter((p) => isImageFile(p));
}, [parsedFiles]);
const { previewFiles, togglePreview } = useFilePreviewState(autoPreviewPaths, { defaultPreview: true });
const enableWorkerPool = typeof window !== 'undefined' && typeof Worker !== 'undefined';
const poolOptions = useMemo(() => (enableWorkerPool ? { workerFactory } : undefined), [enableWorkerPool]);
const highlighterOptions = useMemo(
() => ({ theme: { dark: 'pierre-dark', light: 'pierre-light' } }),
[]
);
const content = (
<div className={className ? `h-full ${className}` : 'h-full'}>
<div className="h-full overflow-y-auto" data-testid="diff-scroll-container" style={{ paddingBottom: 12 }}>
{parsedFiles.length === 0 ? (
<div className="flex items-center justify-center h-full text-xs" style={{ color: 'var(--st-text-faint)' }}>
No changes to display
</div>
) : (
parsedFiles.map((file) => (
<FileCard
key={file.cacheKey ?? file.name}
fileDiff={file}
stagedEntries={stagedEntriesByFile.get(file.name)}
unstagedEntries={unstagedEntriesByFile.get(file.name)}
previewContent={previewFileSources?.[file.name]}
isCommitView={Boolean(isCommitView)}
sessionId={sessionId}
target={target}
enableContextLoading={Boolean(sessionId && target)}
onChanged={onChanged}
scrollToSelf={Boolean(scrollToFilePath && file.name === scrollToFilePath)}
isPreviewing={previewFiles.has(file.name)}
onTogglePreview={() => togglePreview(file.name)}
themeType={themeType}
isReviewed={reviewedFiles.has(file.name)}
onToggleReviewed={() => toggleReviewed(file.name)}
isCollapsed={collapsedFiles.has(file.name)}
onToggleCollapsed={() => toggleCollapsed(file.name)}
/>
))
)}
</div>
</div>
);
if (!enableWorkerPool) return content;
return (
<WorkerPoolContextProvider poolOptions={poolOptions as any} highlighterOptions={highlighterOptions as any}>
{content}
</WorkerPoolContextProvider>
);
});
PierreDiffViewer.displayName = 'PierreDiffViewer';
export default PierreDiffViewer;