Sources/OrgApp/DiffView.swift

79 lines · 2621 bytes

3 symbols in this file
 1import OrgDocument
 2import SwiftUI
 3
 4/// Lines removed and added between two versions, with a few lines of context around each change.
 5public struct DiffView: View {
 6    let lines: [DiffLine]
 7    var context = 3
 8
 9    public init(old: String, new: String) {
10        lines = lineDiff(old: old, new: new)
11    }
12
13    /// Lines to show, nil standing for a run of unchanged lines left out.
14    private var shown: [DiffLine?] {
15        let changed = lines.indices.filter { lines[$0].kind != .same }
16        guard !changed.isEmpty else { return [] }
17        var keep = Set<Int>()
18        for i in changed { keep.formUnion(max(0, i - context)...min(lines.count - 1, i + context)) }
19        var out: [DiffLine?] = []
20        var skipped = false
21        for i in lines.indices {
22            if keep.contains(i) {
23                out.append(lines[i])
24                skipped = false
25            } else if !skipped {
26                out.append(nil)
27                skipped = true
28            }
29        }
30        return out
31    }
32
33    public var body: some View {
34        let shown = shown
35        ScrollView([.vertical, .horizontal]) {
36            VStack(alignment: .leading, spacing: 0) {
37                if shown.isEmpty { Text("No differences").foregroundStyle(.secondary).padding(8) }
38                ForEach(shown.indices, id: \.self) { i in
39                    if let line = shown[i] {
40                        Text(prefix(line.kind) + line.text.trimmingCharacters(in: .newlines))
41                            .frame(maxWidth: .infinity, alignment: .leading)
42                            .background(background(line.kind))
43                    } else {
44                        Text("⋯").foregroundStyle(.secondary)
45                    }
46                }
47            }
48            #if os(macOS)
49            .font(.system(.callout, design: .monospaced))
50            #else
51            .font(.system(.footnote, design: .monospaced))
52            #endif
53            .textSelection(.enabled)
54            .padding(8)
55        }
56        .defaultScrollAnchor(.topLeading)
57        #if os(macOS)
58        .background(Color(nsColor: .textBackgroundColor))
59        #else
60        .background(Color(uiColor: .secondarySystemBackground))
61        #endif
62    }
63
64    private func prefix(_ kind: DiffLine.Kind) -> String {
65        switch kind {
66        case .same: "  "
67        case .removed: "- "
68        case .added: "+ "
69        }
70    }
71
72    private func background(_ kind: DiffLine.Kind) -> Color {
73        switch kind {
74        case .same: .clear
75        case .removed: .red.opacity(0.18)
76        case .added: .green.opacity(0.18)
77        }
78    }
79}