Repository navigation
Expand file tree
/
Copy pathdiff-view.tsx
More file actions
89 lines (76 loc) · 2.71 KB
/
Copy pathdiff-view.tsx
File metadata and controls
89 lines (76 loc) · 2.71 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
import { memo, useMemo } from 'react'
import { TextAttributes } from '@opentui/core'
import { useTheme } from '../hooks/use-theme'
/** Diff hunk shape rendered by DiffView. */
export interface EditDiff {
startLine: number
removedLines: string[]
addedLines: string[]
contextBefore: string[]
contextAfter: string[]
}
interface DiffViewProps {
diffs: readonly EditDiff[]
dimmed?: boolean
}
interface DiffLine {
lineNum: number
sign: '+' | '-'
content: string
type: 'added' | 'removed'
}
export const DiffView = memo(function DiffView({ diffs, dimmed = false }: DiffViewProps) {
const theme = useTheme()
// Build flat list of lines with line numbers and separators
const { lines, gutterWidth } = useMemo(() => {
const allLines: (DiffLine | 'separator')[] = []
let maxLineNum = 0
for (let di = 0; di < diffs.length; di++) {
const diff = diffs[di]
if (di > 0) allLines.push('separator')
for (let li = 0; li < diff.removedLines.length; li++) {
const lineNum = diff.startLine + li
maxLineNum = Math.max(maxLineNum, lineNum)
allLines.push({ lineNum, sign: '-', content: diff.removedLines[li], type: 'removed' })
}
for (let li = 0; li < diff.addedLines.length; li++) {
const lineNum = diff.startLine + li
maxLineNum = Math.max(maxLineNum, lineNum)
allLines.push({ lineNum, sign: '+', content: diff.addedLines[li], type: 'added' })
}
}
return {
lines: allLines,
gutterWidth: Math.max(1, maxLineNum.toString().length),
}
}, [diffs])
if (lines.length === 0) return null
return (
<box style={{ flexDirection: 'column' }}>
{lines.map((line, i) => {
if (line === 'separator') {
const pad = ' '.repeat(gutterWidth)
return (
<text key={`sep-${i}`} style={{ fg: theme.text.supporting }} attributes={TextAttributes.DIM}>
{pad} ⋮
</text>
)
}
const color = line.type === 'added' ? theme.status.success : theme.status.failure
const numStr = line.lineNum.toString().padStart(gutterWidth)
return (
<text key={`${line.type[0]}-${i}`} attributes={dimmed ? TextAttributes.DIM : undefined}>
<span fg={theme.text.supporting} attributes={TextAttributes.DIM}>{numStr}</span>
{' '}
<span fg={color}>{line.sign} {line.content}</span>
</text>
)
})}
</box>
)
})
export function computeDiffStats(diffs: readonly EditDiff[]) {
const totalRemoved = diffs.reduce((sum, d) => sum + d.removedLines.length, 0)
const totalAdded = diffs.reduce((sum, d) => sum + d.addedLines.length, 0)
return { totalRemoved, totalAdded, changeCount: diffs.length }
}