summaryrefslogtreecommitdiff
path: root/Hutch/Views/Repositories/DiffView.swift
blob: a370dfb157096af9fb4b878024352e4c9aa51c92 (plain) (blame)
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
import SwiftUI

/// Renders a unified diff string with syntax highlighting:
/// - Green background for added lines (+)
/// - Red background for removed lines (-)
/// - Gray for hunk headers (@@)
/// - File headers (--- / +++ / diff) in bold
struct DiffView: View {
    let diff: String

    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            ForEach(fileSections) { section in
                DiffFileSectionView(section: section)
            }
        }
    }

    private var fileSections: [DiffFileSection] {
        DiffFileSection.parse(from: normalizedDiff)
    }

    private var normalizedDiff: String {
        diff
            .replacingOccurrences(of: "\r\n", with: "\n")
            .replacingOccurrences(of: "\r", with: "\n")
    }
}

private struct DiffFileSectionView: View {
    let section: DiffFileSection
    @State private var isExpanded = true

    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            Button {
                isExpanded.toggle()
            } label: {
                HStack(spacing: 10) {
                    Image(systemName: isExpanded ? "chevron.down" : "chevron.right")
                        .font(.caption.weight(.semibold))
                        .foregroundStyle(.secondary)
                        .frame(width: 12)

                    Text(section.filename)
                        .font(.subheadline.weight(.semibold))
                        .foregroundStyle(.primary)
                        .lineLimit(1)

                    Spacer(minLength: 8)

                    Text(section.changeSummary)
                        .font(.caption.weight(.medium))
                        .foregroundStyle(.secondary)
                }
                .padding(.horizontal, 10)
                .padding(.vertical, 8)
                .contentShape(Rectangle())
            }
            .buttonStyle(.plain)
            .background(Color(.tertiarySystemBackground))

            if isExpanded {
                DiffBlockView(lines: section.lines)
            }
        }
        .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
        .overlay {
            RoundedRectangle(cornerRadius: 8, style: .continuous)
                .strokeBorder(Color.primary.opacity(0.06))
        }
    }
}

private struct DiffBlockView: View {
    let lines: [String]

    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            LazyVStack(alignment: .leading, spacing: 0) {
                ForEach(Array(lines.enumerated()), id: \.offset) { _, line in
                    DiffLineView(line: line)
                }
            }
            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
        }
        .font(.system(.caption, design: .monospaced))
        .background(Color(.secondarySystemBackground))
    }
}

private struct DiffFileSection: Identifiable {
    let id: String
    let filename: String
    let lines: [String]
    let additions: Int
    let deletions: Int

    var changeSummary: String {
        "+\(additions)  -\(deletions)"
    }

    static func parse(from diff: String) -> [DiffFileSection] {
        let lines = diff.components(separatedBy: "\n")
        guard !lines.isEmpty else { return [] }

        let boundaries = lines.enumerated().compactMap { index, line in
            line.hasPrefix("diff --git ") ? index : nil
        }

        guard !boundaries.isEmpty else {
            let section = makeSection(lines: lines, fallbackIndex: 0)
            return section.lines.isEmpty ? [] : [section]
        }

        var sections: [DiffFileSection] = []
        for (position, startIndex) in boundaries.enumerated() {
            let endIndex = position + 1 < boundaries.count ? boundaries[position + 1] : lines.count
            let sectionLines = Array(lines[startIndex..<endIndex])
            let section = makeSection(lines: sectionLines, fallbackIndex: position)
            if !section.lines.isEmpty {
                sections.append(section)
            }
        }
        return sections
    }

    private static func makeSection(lines: [String], fallbackIndex: Int) -> DiffFileSection {
        let filename = fileName(from: lines) ?? "File \(fallbackIndex + 1)"
        let additions = lines.filter { $0.hasPrefix("+") && !$0.hasPrefix("+++") }.count
        let deletions = lines.filter { $0.hasPrefix("-") && !$0.hasPrefix("---") }.count
        return DiffFileSection(
            id: "\(fallbackIndex)-\(filename)",
            filename: filename,
            lines: lines,
            additions: additions,
            deletions: deletions
        )
    }

    private static func fileName(from lines: [String]) -> String? {
        if let diffHeader = lines.first(where: { $0.hasPrefix("diff --git ") }) {
            let parts = diffHeader.split(separator: " ")
            if let rhs = parts.last, rhs.hasPrefix("b/") {
                return String(rhs.dropFirst(2))
            }
        }

        if let plusHeader = lines.first(where: { $0.hasPrefix("+++ ") }) {
            let path = String(plusHeader.dropFirst(4))
            if path.hasPrefix("b/") {
                return String(path.dropFirst(2))
            }
            return path
        }

        if let minusHeader = lines.first(where: { $0.hasPrefix("--- ") }) {
            let path = String(minusHeader.dropFirst(4))
            if path.hasPrefix("a/") {
                return String(path.dropFirst(2))
            }
            return path
        }

        return nil
    }
}

private struct DiffLineView: View {
    let line: String

    var body: some View {
        Text(line.isEmpty ? " " : line)
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding(.horizontal, 8)
            .background(backgroundColor)
            .foregroundStyle(foregroundColor)
            .fontWeight(isHeader ? .semibold : .regular)
    }

    private var kind: DiffLineKind {
        if line.hasPrefix("@@") { return .hunk }
        if line.hasPrefix("+++") || line.hasPrefix("---") { return .fileHeader }
        if line.hasPrefix("diff ") { return .fileHeader }
        if line.hasPrefix("index ") { return .meta }
        if line.hasPrefix("+") { return .added }
        if line.hasPrefix("-") { return .removed }
        return .context
    }

    private var backgroundColor: Color {
        switch kind {
        case .added:      .green.opacity(0.15)
        case .removed:    .red.opacity(0.15)
        case .hunk:       .clear
        case .fileHeader: .clear
        case .meta:       .clear
        case .context:    .clear
        }
    }

    private var foregroundColor: Color {
        switch kind {
        case .added:   .green
        case .removed: .red
        case .hunk:    .secondary
        case .meta:    .secondary
        default:       .primary
        }
    }

    private var isHeader: Bool {
        kind == .fileHeader
    }
}

private enum DiffLineKind {
    case added
    case removed
    case hunk
    case fileHeader
    case meta
    case context
}