Branchwell

Bucksley / app / Sources / BucksleyUI / ChartViews.swift

1import SwiftUI
2import Charts
3import BucksleyKit
4
5/// Net worth over time, drawn the way each theme describes it:
6/// Afterhours, a stacked area of what it's made of; Evergreen, one smooth line over a soft fade;
7/// Almanac, a thin ink line with a point per month.
8public struct NetWorthChart: View {
9 @Environment(\.palette) private var palette
10 let series: [Ledger.NetWorthPoint]
11 public init(_ series: [Ledger.NetWorthPoint]) { self.series = series }
12
13 struct Layer: Identifiable { let id: String; let day: Date; let group: AccountGroup; let start: Double; let end: Double }
14
15 func layers(_ points: [(Date, Ledger.NetWorthPoint)]) -> [Layer] {
16 points.flatMap { day, p in
17 var base = 0.0
18 return stackOrder.map { group in
19 let value = max(0, (p.byGroup[group] ?? 0).double)
20 defer { base += value }
21 return Layer(id: "\(group.rawValue)-\(p.day)", day: day, group: group, start: base, end: base + value)
22 }
23 }
24 }
25
26 public var body: some View {
27 let points = series.compactMap { p in DayKey.date(p.day).map { ($0, p) } }
28 Chart {
29 switch palette.theme {
30 case .afterhours:
31 // Assets stacked by group, each layer fading down, with net worth drawn on top.
32 ForEach(layers(points)) { layer in
33 AreaMark(x: .value("Day", layer.day), yStart: .value("Base", max(lowerBound, layer.start)), yEnd: .value("Value", max(lowerBound, layer.end)), series: .value("Group", layer.group.title))
34 .foregroundStyle(LinearGradient(colors: [palette.color(for: layer.group).opacity(0.55), palette.color(for: layer.group).opacity(0.06)], startPoint: .top, endPoint: .bottom))
35 .interpolationMethod(.monotone)
36 }
37 ForEach(points, id: \.0) { day, p in
38 LineMark(x: .value("Day", day), y: .value("Net worth", p.total.double))
39 .foregroundStyle(palette.accent).lineStyle(StrokeStyle(lineWidth: 2.25, lineCap: .round, lineJoin: .round))
40 .interpolationMethod(.monotone)
41 }
42 case .evergreen:
43 ForEach(points, id: \.0) { day, p in
44 AreaMark(x: .value("Day", day), yStart: .value("Base", lowerBound), yEnd: .value("Net worth", p.total.double))
45 .foregroundStyle(LinearGradient(colors: [palette.accent.opacity(0.28), palette.accent.opacity(0.0)], startPoint: .top, endPoint: .bottom))
46 .interpolationMethod(.catmullRom)
47 LineMark(x: .value("Day", day), y: .value("Net worth", p.total.double))
48 .foregroundStyle(palette.accent).lineStyle(StrokeStyle(lineWidth: 2.5, lineCap: .round))
49 .interpolationMethod(.catmullRom)
50 }
51 case .almanac:
52 ForEach(points, id: \.0) { day, p in
53 LineMark(x: .value("Day", day), y: .value("Net worth", p.total.double))
54 .foregroundStyle(palette.text).lineStyle(StrokeStyle(lineWidth: 1.2))
55 }
56 ForEach(monthEnds(points), id: \.0) { day, p in
57 PointMark(x: .value("Day", day), y: .value("Net worth", p.total.double))
58 .foregroundStyle(palette.text).symbolSize(18)
59 }
60 if let last = points.last {
61 PointMark(x: .value("Day", last.0), y: .value("Net worth", last.1.total.double))
62 .foregroundStyle(palette.accent).symbolSize(40)
63 .annotation(position: .top, alignment: .trailing) {
64 Text(Money.short(last.1.total) + " today").font(.system(size: 11, design: .serif).italic()).foregroundStyle(palette.muted)
65 }
66 }
67 }
68 }
69 .chartLegend(.hidden)
70 .chartYScale(domain: lowerBound...max(lowerBound + 1, upperBound))
71 .clipped()
72 .chartYAxis {
73 AxisMarks(position: .trailing, values: .automatic(desiredCount: 3)) { v in
74 AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5, dash: palette.theme == .almanac ? [2, 3] : [])).foregroundStyle(palette.line)
75 AxisValueLabel { if let d = v.as(Double.self) { Text(Money.short(Decimal(d))).font(palette.figure(10, weight: .regular)).foregroundStyle(palette.muted) } }
76 }
77 }
78 .chartXAxis {
79 AxisMarks(values: .automatic(desiredCount: 6)) { _ in
80 AxisValueLabel(format: series.count > 120 ? .dateTime.month(.abbreviated) : .dateTime.month(.abbreviated).day()).font(.system(size: 10)).foregroundStyle(palette.muted)
81 }
82 }
83 .accessibilityLabel("Net worth chart")
84 }
85
86 var stackOrder: [AccountGroup] {
87 AccountGroup.allCases.filter { g in g != .credit && g != .loans && series.contains { ($0.byGroup[g] ?? 0) > 0 } }
88 }
89 /// Net worth, plus the top of the asset stack in Afterhours.
90 var plotted: [Double] {
91 let totals = series.map(\.total.double)
92 guard palette.theme == .afterhours else { return totals }
93 return totals + series.map { p in stackOrder.reduce(0) { $0 + max(0, (p.byGroup[$1] ?? 0).double) } }
94 }
95 var lowerBound: Double {
96 let values = plotted
97 guard let lo = values.min(), let hi = values.max() else { return 0 }
98 return max(0, lo - (hi - lo) * 0.25 - 1)
99 }
100 var upperBound: Double {
101 let values = plotted
102 guard let lo = values.min(), let hi = values.max() else { return 1 }
103 return hi + (hi - lo) * 0.1 + 1
104 }
105 func monthEnds(_ points: [(Date, Ledger.NetWorthPoint)]) -> [(Date, Ledger.NetWorthPoint)] {
106 Dictionary(grouping: points) { MonthKey.of($0.1.day) }.values.compactMap { $0.max { $0.0 < $1.0 } }.sorted { $0.0 < $1.0 }
107 }
108}
109
110/// Spending by category: a donut with the total inside (Afterhours), one stacked bar with a
111/// legend (Evergreen), or a ranked list with hairline bars (Almanac).
112public struct SpendingChart: View {
113 @Environment(\.palette) private var palette
114 let rows: [(categoryID: String, amount: Decimal)]
115 let workspace: Workspace
116 var compact = false
117 public init(_ rows: [(categoryID: String, amount: Decimal)], workspace: Workspace, compact: Bool = false) {
118 self.rows = rows; self.workspace = workspace; self.compact = compact
119 }
120
121 var top: [(name: String, amount: Decimal, color: Int)] {
122 let named = rows.map { (workspace.category($0.categoryID)?.name ?? $0.categoryID, $0.amount, workspace.category($0.categoryID)?.colorIndex ?? 5) }
123 guard named.count > 6 else { return named }
124 let rest = named.dropFirst(5).reduce(Decimal(0)) { $0 + $1.1 }
125 return Array(named.prefix(5)) + [("Rest", rest, 5)]
126 }
127 var total: Decimal { rows.reduce(0) { $0 + $1.amount } }
128
129 public var body: some View {
130 if rows.isEmpty {
131 Text("No spending yet this month.").font(.system(size: 13)).foregroundStyle(palette.muted).frame(maxWidth: .infinity, minHeight: 80)
132 } else {
133 switch palette.theme {
134 case .afterhours: donut
135 case .evergreen: stackedBar
136 case .almanac: ranked
137 }
138 }
139 }
140
141 var donut: some View {
142 HStack(spacing: 18) {
143 Chart(top.indices, id: \.self) { i in
144 SectorMark(angle: .value("Amount", top[i].amount.double), innerRadius: .ratio(0.68), angularInset: 1.5)
145 .foregroundStyle(palette.color(i))
146 .cornerRadius(3)
147 }
148 .chartBackground { _ in
149 VStack(spacing: 0) {
150 Text(Money.format(total, cents: false)).font(palette.figure(compact ? 15 : 18)).tracking(-0.5)
151 Text(MonthKey.title(MonthKey.current).components(separatedBy: " ").first ?? "").font(.system(size: 10)).foregroundStyle(palette.muted)
152 }
153 }
154 .frame(width: compact ? 110 : 140, height: compact ? 110 : 140)
155 legend
156 }
157 }
158
159 var stackedBar: some View {
160 VStack(alignment: .leading, spacing: 12) {
161 GeometryReader { geo in
162 HStack(spacing: 2) {
163 ForEach(top.indices, id: \.self) { i in
164 Rectangle().fill(palette.color(i))
165 .frame(width: max(2, geo.size.width * CGFloat((top[i].amount / max(total, 1)).double) - 2))
166 }
167 }
168 .clipShape(Capsule())
169 }
170 .frame(height: 14)
171 legend
172 }
173 }
174
175 var ranked: some View {
176 VStack(spacing: 0) {
177 ForEach(top.indices, id: \.self) { i in
178 VStack(alignment: .leading, spacing: 4) {
179 HStack(alignment: .firstTextBaseline) {
180 Text(top[i].name).font(.system(size: 13))
181 Spacer()
182 MoneyText(top[i].amount, size: 13, cents: false)
183 }
184 GeometryReader { geo in
185 Rectangle().fill(palette.accent).frame(width: geo.size.width * CGFloat((top[i].amount / max(top.first?.amount ?? 1, 1)).double), height: 1.5)
186 }
187 .frame(height: 2)
188 }
189 .padding(.vertical, 6)
190 .overlay(alignment: .bottom) { Rectangle().fill(palette.line).frame(height: 0.5) }
191 }
192 }
193 }
194
195 var legend: some View {
196 LazyVGrid(columns: [GridItem(.flexible(), alignment: .leading), GridItem(.flexible(), alignment: .leading)], alignment: .leading, spacing: 6) {
197 ForEach(top.indices, id: \.self) { i in
198 HStack(spacing: 6) {
199 RoundedRectangle(cornerRadius: 2).fill(palette.color(i)).frame(width: 8, height: 8)
200 Text(top[i].name).font(.system(size: 12)).foregroundStyle(palette.muted).lineLimit(1)
201 Spacer(minLength: 2)
202 MoneyText(top[i].amount, size: 12, cents: false)
203 }
204 }
205 }
206 }
207}
208
209/// One budget's progress: a ring (Afterhours), a capsule with today's pace tick (Evergreen) or a
210/// ledger rule with a pace tick (Almanac).
211public struct BudgetProgress: View {
212 @Environment(\.palette) private var palette
213 let status: Ledger.BudgetStatus
214 let name: String
215 let colorIndex: Int
216 public init(_ status: Ledger.BudgetStatus, name: String, colorIndex: Int) { self.status = status; self.name = name; self.colorIndex = colorIndex }
217
218 var over: Bool { status.remaining < 0 }
219 var barColor: Color { over ? palette.loss : status.aheadOfPace ? palette.color(3) : palette.color(colorIndex) }
220
221 public var body: some View {
222 switch palette.theme {
223 case .afterhours: ring
224 case .evergreen: capsule
225 case .almanac: ledger
226 }
227 }
228
229 var caption: String {
230 over ? "\(Money.format(-status.remaining, cents: false)) over" : "\(Money.format(status.remaining, cents: false)) left"
231 }
232
233 var ring: some View {
234 HStack(spacing: 12) {
235 ZStack {
236 Circle().stroke(palette.line, lineWidth: 6)
237 Circle().trim(from: 0, to: min(1, status.progress)).stroke(barColor, style: StrokeStyle(lineWidth: 6, lineCap: .round)).rotationEffect(.degrees(-90))
238 Text("\(Int((status.progress * 100).rounded()))%").font(palette.figure(10, weight: .medium))
239 }
240 .frame(width: 44, height: 44)
241 VStack(alignment: .leading, spacing: 2) {
242 Text(name).font(.system(size: 13, weight: .semibold))
243 HStack(spacing: 4) {
244 Text(Money.format(status.spent, cents: false) + "/" + Money.format(status.available, cents: false)).font(palette.figure(11, weight: .regular)).foregroundStyle(palette.muted)
245 if status.carried != 0 { Text("incl. \(Money.format(status.carried, cents: false, signed: true)) rollover").font(.system(size: 10)).foregroundStyle(palette.muted) }
246 }
247 }
248 Spacer()
249 Text(caption).font(.system(size: 11, weight: .semibold)).foregroundStyle(over ? palette.loss : palette.muted)
250 }
251 }
252
253 var capsule: some View {
254 VStack(alignment: .leading, spacing: 6) {
255 HStack(alignment: .firstTextBaseline) {
256 Text(name).font(.system(size: 13, weight: .semibold))
257 Spacer()
258 Text(caption).font(.system(size: 12, weight: .medium)).foregroundStyle(over ? palette.loss : palette.muted)
259 }
260 GeometryReader { geo in
261 ZStack(alignment: .leading) {
262 Capsule().fill(palette.line)
263 Capsule().fill(barColor).frame(width: geo.size.width * CGFloat(min(1, status.progress)))
264 Rectangle().fill(palette.text).frame(width: 2, height: 14).offset(x: geo.size.width * CGFloat(status.pace) - 1)
265 .accessibilityHidden(true)
266 }
267 }
268 .frame(height: 10)
269 Text("\(Money.format(status.spent, cents: false)) of \(Money.format(status.available, cents: false))" + (status.carried != 0 ? " · \(Money.format(status.carried, cents: false, signed: true)) rolled over" : ""))
270 .font(palette.figure(11, weight: .regular)).foregroundStyle(palette.muted)
271 }
272 }
273
274 var ledger: some View {
275 VStack(alignment: .leading, spacing: 4) {
276 HStack(alignment: .firstTextBaseline) {
277 Text(name).font(.system(size: 14, design: .serif))
278 Text("\(NSDecimalNumber(decimal: status.spent.rounded(0)).intValue) of \(NSDecimalNumber(decimal: status.available.rounded(0)).intValue)")
279 .font(.system(size: 12, design: .serif).italic()).foregroundStyle(palette.muted)
280 Spacer()
281 Text(caption).font(.system(size: 13, design: .serif)).foregroundStyle(over ? palette.loss : palette.text)
282 }
283 GeometryReader { geo in
284 ZStack(alignment: .leading) {
285 Rectangle().fill(palette.line).frame(height: 1)
286 Rectangle().fill(over ? palette.loss : palette.text).frame(width: geo.size.width * CGFloat(min(1, status.progress)), height: 2)
287 Rectangle().fill(palette.accent).frame(width: 1.5, height: 9).offset(x: geo.size.width * CGFloat(status.pace))
288 }
289 }
290 .frame(height: 9)
291 }
292 .padding(.vertical, 4)
293 }
294}
295
296/// Tiny bars of the last weeks of an account's balance (Afterhours account cards).
297public struct Sparkline: View {
298 @Environment(\.palette) private var palette
299 let values: [Double]
300 let colorIndex: Int
301 public init(_ values: [Double], colorIndex: Int) { self.values = values; self.colorIndex = colorIndex }
302 public var body: some View {
303 let lo = values.min() ?? 0, hi = values.max() ?? 1, span = max(hi - lo, 1)
304 HStack(alignment: .bottom, spacing: 2) {
305 ForEach(values.indices, id: \.self) { i in
306 RoundedRectangle(cornerRadius: 1).fill(palette.color(colorIndex).opacity(i == values.count - 1 ? 1 : 0.55))
307 .frame(width: 3, height: 4 + 18 * CGFloat((values[i] - lo) / span))
308 }
309 }
310 .frame(height: 22, alignment: .bottom)
311 .accessibilityHidden(true)
312 }
313}