krz/hutch

an ios client for sourcehut

clone: git clone https://gitbay.org/krz/hutch.git

v2.3.0: Hutch/Views/Repositories/DiffView.swift · raw

  1import SwiftUI
  2
  3/// Renders a unified diff string with syntax highlighting:
  4/// - Green background for added lines (+)
  5/// - Red background for removed lines (-)
  6/// - Gray for hunk headers (@@)
  7/// - File headers (--- / +++ / diff) in bold
  8struct DiffView: View {
  9    let diff: String
 10
 11    var body: some View {
 12        VStack(alignment: .leading, spacing: 12) {
 13            ForEach(fileSections) { section in
 14                DiffFileSectionView(section: section)
 15            }
 16        }
 17    }
 18
 19    private var fileSections: [DiffFileSection] {
 20        DiffFileSection.parse(from: normalizedDiff)
 21    }
 22
 23    private var normalizedDiff: String {
 24        diff
 25            .replacingOccurrences(of: "\r\n", with: "\n")
 26            .replacingOccurrences(of: "\r", with: "\n")
 27    }
 28}
 29
 30private struct DiffFileSectionView: View {
 31    let section: DiffFileSection
 32    @State private var isExpanded = true
 33
 34    var body: some View {
 35        VStack(alignment: .leading, spacing: 0) {
 36            Button {
 37                isExpanded.toggle()
 38            } label: {
 39                HStack(spacing: 10) {
 40                    Image(systemName: isExpanded ? "chevron.down" : "chevron.right")
 41                        .font(.caption.weight(.semibold))
 42                        .foregroundStyle(.secondary)
 43                        .frame(width: 12)
 44
 45                    Text(section.filename)
 46                        .font(.subheadline.weight(.semibold))
 47                        .foregroundStyle(.primary)
 48                        .lineLimit(1)
 49
 50                    Spacer(minLength: 8)
 51
 52                    Text(section.changeSummary)
 53                        .font(.caption.weight(.medium))
 54                        .foregroundStyle(.secondary)
 55                }
 56                .padding(.horizontal, 10)
 57                .padding(.vertical, 8)
 58                .contentShape(Rectangle())
 59            }
 60            .buttonStyle(.plain)
 61            .background(Color(.tertiarySystemBackground))
 62
 63            if isExpanded {
 64                DiffBlockView(lines: section.lines)
 65            }
 66        }
 67        .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
 68        .overlay {
 69            RoundedRectangle(cornerRadius: 8, style: .continuous)
 70                .strokeBorder(Color.primary.opacity(0.06))
 71        }
 72    }
 73}
 74
 75private struct DiffBlockView: View {
 76    let lines: [String]
 77
 78    var body: some View {
 79        VStack(alignment: .leading, spacing: 0) {
 80            ForEach(Array(lines.enumerated()), id: \.offset) { _, line in
 81                DiffLineView(line: line)
 82            }
 83        }
 84        .font(.system(.caption, design: .monospaced))
 85        .frame(maxWidth: .infinity, alignment: .leading)
 86        .background(Color(.secondarySystemBackground))
 87    }
 88}
 89
 90private struct DiffFileSection: Identifiable {
 91    let id: String
 92    let filename: String
 93    let lines: [String]
 94    let additions: Int
 95    let deletions: Int
 96
 97    var changeSummary: String {
 98        "+\(additions)  -\(deletions)"
 99    }
100
101    static func parse(from diff: String) -> [DiffFileSection] {
102        let lines = diff.components(separatedBy: "\n")
103        guard !lines.isEmpty else { return [] }
104
105        let boundaries = lines.enumerated().compactMap { index, line in
106            line.hasPrefix("diff --git ") ? index : nil
107        }
108
109        guard !boundaries.isEmpty else {
110            let section = makeSection(lines: lines, fallbackIndex: 0)
111            return section.lines.isEmpty ? [] : [section]
112        }
113
114        var sections: [DiffFileSection] = []
115        for (position, startIndex) in boundaries.enumerated() {
116            let endIndex = position + 1 < boundaries.count ? boundaries[position + 1] : lines.count
117            let sectionLines = Array(lines[startIndex..<endIndex])
118            let section = makeSection(lines: sectionLines, fallbackIndex: position)
119            if !section.lines.isEmpty {
120                sections.append(section)
121            }
122        }
123        return sections
124    }
125
126    private static func makeSection(lines: [String], fallbackIndex: Int) -> DiffFileSection {
127        let filename = fileName(from: lines) ?? "File \(fallbackIndex + 1)"
128        let additions = lines.filter { $0.hasPrefix("+") && !$0.hasPrefix("+++") }.count
129        let deletions = lines.filter { $0.hasPrefix("-") && !$0.hasPrefix("---") }.count
130        return DiffFileSection(
131            id: "\(fallbackIndex)-\(filename)",
132            filename: filename,
133            lines: lines,
134            additions: additions,
135            deletions: deletions
136        )
137    }
138
139    private static func fileName(from lines: [String]) -> String? {
140        if let diffHeader = lines.first(where: { $0.hasPrefix("diff --git ") }) {
141            let parts = diffHeader.split(separator: " ")
142            if let rhs = parts.last, rhs.hasPrefix("b/") {
143                return String(rhs.dropFirst(2))
144            }
145        }
146
147        if let plusHeader = lines.first(where: { $0.hasPrefix("+++ ") }) {
148            let path = String(plusHeader.dropFirst(4))
149            if path.hasPrefix("b/") {
150                return String(path.dropFirst(2))
151            }
152            return path
153        }
154
155        if let minusHeader = lines.first(where: { $0.hasPrefix("--- ") }) {
156            let path = String(minusHeader.dropFirst(4))
157            if path.hasPrefix("a/") {
158                return String(path.dropFirst(2))
159            }
160            return path
161        }
162
163        return nil
164    }
165}
166
167private struct DiffLineView: View {
168    let line: String
169
170    var body: some View {
171        Text(line.isEmpty ? " " : line)
172            .frame(maxWidth: .infinity, alignment: .leading)
173            .padding(.horizontal, 8)
174            .background(backgroundColor)
175            .foregroundStyle(foregroundColor)
176            .fontWeight(isHeader ? .semibold : .regular)
177    }
178
179    private var kind: DiffLineKind {
180        if line.hasPrefix("@@") { return .hunk }
181        if line.hasPrefix("+++") || line.hasPrefix("---") { return .fileHeader }
182        if line.hasPrefix("diff ") { return .fileHeader }
183        if line.hasPrefix("index ") { return .meta }
184        if line.hasPrefix("+") { return .added }
185        if line.hasPrefix("-") { return .removed }
186        return .context
187    }
188
189    private var backgroundColor: Color {
190        switch kind {
191        case .added:      .green.opacity(0.15)
192        case .removed:    .red.opacity(0.15)
193        case .hunk:       .clear
194        case .fileHeader: .clear
195        case .meta:       .clear
196        case .context:    .clear
197        }
198    }
199
200    private var foregroundColor: Color {
201        switch kind {
202        case .added:   .green
203        case .removed: .red
204        case .hunk:    .secondary
205        case .meta:    .secondary
206        default:       .primary
207        }
208    }
209
210    private var isHeader: Bool {
211        kind == .fileHeader
212    }
213}
214
215private enum DiffLineKind {
216    case added
217    case removed
218    case hunk
219    case fileHeader
220    case meta
221    case context
222}