Sources/OrgApp/DiffView.swift
cmc Board: keyword colours as in the agenda; theme colours in the diff and board
7e86cdaf6e 11 hours ago90 lines · 3182 bytes
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 let removedColor: Color
9 let addedColor: Color
10 let foreground: Color?
11 let background: Color?
12
13 /// `removed` and `added` tint the changed lines; `foreground` and `background` default to
14 /// the system's text colours.
15 public init(old: String, new: String, removed: Color = .red, added: Color = .green, foreground: Color? = nil, background: Color? = nil) {
16 lines = lineDiff(old: old, new: new)
17 removedColor = removed
18 addedColor = added
19 self.foreground = foreground
20 self.background = background
21 }
22
23 /// Lines to show, nil standing for a run of unchanged lines left out.
24 private var shown: [DiffLine?] {
25 let changed = lines.indices.filter { lines[$0].kind != .same }
26 guard !changed.isEmpty else { return [] }
27 var keep = Set<Int>()
28 for i in changed { keep.formUnion(max(0, i - context)...min(lines.count - 1, i + context)) }
29 var out: [DiffLine?] = []
30 var skipped = false
31 for i in lines.indices {
32 if keep.contains(i) {
33 out.append(lines[i])
34 skipped = false
35 } else if !skipped {
36 out.append(nil)
37 skipped = true
38 }
39 }
40 return out
41 }
42
43 public var body: some View {
44 let shown = shown
45 ScrollView([.vertical, .horizontal]) {
46 VStack(alignment: .leading, spacing: 0) {
47 if shown.isEmpty { Text("No differences").foregroundStyle(.secondary).padding(8) }
48 ForEach(shown.indices, id: \.self) { i in
49 if let line = shown[i] {
50 Text(prefix(line.kind) + line.text.trimmingCharacters(in: .newlines))
51 .frame(maxWidth: .infinity, alignment: .leading)
52 .background(background(line.kind))
53 } else {
54 Text("⋯").foregroundStyle(.secondary)
55 }
56 }
57 }
58 #if os(macOS)
59 .font(.system(.callout, design: .monospaced))
60 #else
61 .font(.system(.footnote, design: .monospaced))
62 #endif
63 .foregroundStyle(foreground ?? .primary)
64 .textSelection(.enabled)
65 .padding(8)
66 }
67 .defaultScrollAnchor(.topLeading)
68 #if os(macOS)
69 .background(background ?? Color(nsColor: .textBackgroundColor))
70 #else
71 .background(background ?? Color(uiColor: .secondarySystemBackground))
72 #endif
73 }
74
75 private func prefix(_ kind: DiffLine.Kind) -> String {
76 switch kind {
77 case .same: " "
78 case .removed: "- "
79 case .added: "+ "
80 }
81 }
82
83 private func background(_ kind: DiffLine.Kind) -> Color {
84 switch kind {
85 case .same: .clear
86 case .removed: removedColor.opacity(0.18)
87 case .added: addedColor.opacity(0.18)
88 }
89 }
90}