import SwiftUI import Charts import BucksleyKit /// Net worth over time, drawn the way each theme describes it: /// Afterhours, a stacked area of what it's made of; Evergreen, one smooth line over a soft fade; /// Almanac, a thin ink line with a point per month. public struct NetWorthChart: View { @Environment(\.palette) private var palette let series: [Ledger.NetWorthPoint] public init(_ series: [Ledger.NetWorthPoint]) { self.series = series } struct Layer: Identifiable { let id: String; let day: Date; let group: AccountGroup; let start: Double; let end: Double } func layers(_ points: [(Date, Ledger.NetWorthPoint)]) -> [Layer] { points.flatMap { day, p in var base = 0.0 return stackOrder.map { group in let value = max(0, (p.byGroup[group] ?? 0).double) defer { base += value } return Layer(id: "\(group.rawValue)-\(p.day)", day: day, group: group, start: base, end: base + value) } } } public var body: some View { let points = series.compactMap { p in DayKey.date(p.day).map { ($0, p) } } Chart { switch palette.theme { case .afterhours: // Assets stacked by group, each layer fading down, with net worth drawn on top. ForEach(layers(points)) { layer in 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)) .foregroundStyle(LinearGradient(colors: [palette.color(for: layer.group).opacity(0.55), palette.color(for: layer.group).opacity(0.06)], startPoint: .top, endPoint: .bottom)) .interpolationMethod(.monotone) } ForEach(points, id: \.0) { day, p in LineMark(x: .value("Day", day), y: .value("Net worth", p.total.double)) .foregroundStyle(palette.accent).lineStyle(StrokeStyle(lineWidth: 2.25, lineCap: .round, lineJoin: .round)) .interpolationMethod(.monotone) } case .evergreen: ForEach(points, id: \.0) { day, p in AreaMark(x: .value("Day", day), yStart: .value("Base", lowerBound), yEnd: .value("Net worth", p.total.double)) .foregroundStyle(LinearGradient(colors: [palette.accent.opacity(0.28), palette.accent.opacity(0.0)], startPoint: .top, endPoint: .bottom)) .interpolationMethod(.catmullRom) LineMark(x: .value("Day", day), y: .value("Net worth", p.total.double)) .foregroundStyle(palette.accent).lineStyle(StrokeStyle(lineWidth: 2.5, lineCap: .round)) .interpolationMethod(.catmullRom) } case .almanac: ForEach(points, id: \.0) { day, p in LineMark(x: .value("Day", day), y: .value("Net worth", p.total.double)) .foregroundStyle(palette.text).lineStyle(StrokeStyle(lineWidth: 1.2)) } ForEach(monthEnds(points), id: \.0) { day, p in PointMark(x: .value("Day", day), y: .value("Net worth", p.total.double)) .foregroundStyle(palette.text).symbolSize(18) } if let last = points.last { PointMark(x: .value("Day", last.0), y: .value("Net worth", last.1.total.double)) .foregroundStyle(palette.accent).symbolSize(40) .annotation(position: .top, alignment: .trailing) { Text(Money.short(last.1.total) + " today").font(.system(size: 11, design: .serif).italic()).foregroundStyle(palette.muted) } } } } .chartLegend(.hidden) .chartYScale(domain: lowerBound...max(lowerBound + 1, upperBound)) .clipped() .chartYAxis { AxisMarks(position: .trailing, values: .automatic(desiredCount: 3)) { v in AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5, dash: palette.theme == .almanac ? [2, 3] : [])).foregroundStyle(palette.line) AxisValueLabel { if let d = v.as(Double.self) { Text(Money.short(Decimal(d))).font(palette.figure(10, weight: .regular)).foregroundStyle(palette.muted) } } } } .chartXAxis { AxisMarks(values: .automatic(desiredCount: 6)) { _ in AxisValueLabel(format: series.count > 120 ? .dateTime.month(.abbreviated) : .dateTime.month(.abbreviated).day()).font(.system(size: 10)).foregroundStyle(palette.muted) } } .accessibilityLabel("Net worth chart") } var stackOrder: [AccountGroup] { AccountGroup.allCases.filter { g in g != .credit && g != .loans && series.contains { ($0.byGroup[g] ?? 0) > 0 } } } /// Net worth, plus the top of the asset stack in Afterhours. var plotted: [Double] { let totals = series.map(\.total.double) guard palette.theme == .afterhours else { return totals } return totals + series.map { p in stackOrder.reduce(0) { $0 + max(0, (p.byGroup[$1] ?? 0).double) } } } var lowerBound: Double { let values = plotted guard let lo = values.min(), let hi = values.max() else { return 0 } return max(0, lo - (hi - lo) * 0.25 - 1) } var upperBound: Double { let values = plotted guard let lo = values.min(), let hi = values.max() else { return 1 } return hi + (hi - lo) * 0.1 + 1 } func monthEnds(_ points: [(Date, Ledger.NetWorthPoint)]) -> [(Date, Ledger.NetWorthPoint)] { Dictionary(grouping: points) { MonthKey.of($0.1.day) }.values.compactMap { $0.max { $0.0 < $1.0 } }.sorted { $0.0 < $1.0 } } } /// Spending by category: a donut with the total inside (Afterhours), one stacked bar with a /// legend (Evergreen), or a ranked list with hairline bars (Almanac). public struct SpendingChart: View { @Environment(\.palette) private var palette let rows: [(categoryID: String, amount: Decimal)] let workspace: Workspace var compact = false public init(_ rows: [(categoryID: String, amount: Decimal)], workspace: Workspace, compact: Bool = false) { self.rows = rows; self.workspace = workspace; self.compact = compact } var top: [(name: String, amount: Decimal, color: Int)] { let named = rows.map { (workspace.category($0.categoryID)?.name ?? $0.categoryID, $0.amount, workspace.category($0.categoryID)?.colorIndex ?? 5) } guard named.count > 6 else { return named } let rest = named.dropFirst(5).reduce(Decimal(0)) { $0 + $1.1 } return Array(named.prefix(5)) + [("Rest", rest, 5)] } var total: Decimal { rows.reduce(0) { $0 + $1.amount } } public var body: some View { if rows.isEmpty { Text("No spending yet this month.").font(.system(size: 13)).foregroundStyle(palette.muted).frame(maxWidth: .infinity, minHeight: 80) } else { switch palette.theme { case .afterhours: donut case .evergreen: stackedBar case .almanac: ranked } } } var donut: some View { HStack(spacing: 18) { Chart(top.indices, id: \.self) { i in SectorMark(angle: .value("Amount", top[i].amount.double), innerRadius: .ratio(0.68), angularInset: 1.5) .foregroundStyle(palette.color(i)) .cornerRadius(3) } .chartBackground { _ in VStack(spacing: 0) { Text(Money.format(total, cents: false)).font(palette.figure(compact ? 15 : 18)).tracking(-0.5) Text(MonthKey.title(MonthKey.current).components(separatedBy: " ").first ?? "").font(.system(size: 10)).foregroundStyle(palette.muted) } } .frame(width: compact ? 110 : 140, height: compact ? 110 : 140) legend } } var stackedBar: some View { VStack(alignment: .leading, spacing: 12) { GeometryReader { geo in HStack(spacing: 2) { ForEach(top.indices, id: \.self) { i in Rectangle().fill(palette.color(i)) .frame(width: max(2, geo.size.width * CGFloat((top[i].amount / max(total, 1)).double) - 2)) } } .clipShape(Capsule()) } .frame(height: 14) legend } } var ranked: some View { VStack(spacing: 0) { ForEach(top.indices, id: \.self) { i in VStack(alignment: .leading, spacing: 4) { HStack(alignment: .firstTextBaseline) { Text(top[i].name).font(.system(size: 13)) Spacer() MoneyText(top[i].amount, size: 13, cents: false) } GeometryReader { geo in Rectangle().fill(palette.accent).frame(width: geo.size.width * CGFloat((top[i].amount / max(top.first?.amount ?? 1, 1)).double), height: 1.5) } .frame(height: 2) } .padding(.vertical, 6) .overlay(alignment: .bottom) { Rectangle().fill(palette.line).frame(height: 0.5) } } } } var legend: some View { LazyVGrid(columns: [GridItem(.flexible(), alignment: .leading), GridItem(.flexible(), alignment: .leading)], alignment: .leading, spacing: 6) { ForEach(top.indices, id: \.self) { i in HStack(spacing: 6) { RoundedRectangle(cornerRadius: 2).fill(palette.color(i)).frame(width: 8, height: 8) Text(top[i].name).font(.system(size: 12)).foregroundStyle(palette.muted).lineLimit(1) Spacer(minLength: 2) MoneyText(top[i].amount, size: 12, cents: false) } } } } } /// One budget's progress: a ring (Afterhours), a capsule with today's pace tick (Evergreen) or a /// ledger rule with a pace tick (Almanac). public struct BudgetProgress: View { @Environment(\.palette) private var palette let status: Ledger.BudgetStatus let name: String let colorIndex: Int public init(_ status: Ledger.BudgetStatus, name: String, colorIndex: Int) { self.status = status; self.name = name; self.colorIndex = colorIndex } var over: Bool { status.remaining < 0 } var barColor: Color { over ? palette.loss : status.aheadOfPace ? palette.color(3) : palette.color(colorIndex) } public var body: some View { switch palette.theme { case .afterhours: ring case .evergreen: capsule case .almanac: ledger } } var caption: String { over ? "\(Money.format(-status.remaining, cents: false)) over" : "\(Money.format(status.remaining, cents: false)) left" } var ring: some View { HStack(spacing: 12) { ZStack { Circle().stroke(palette.line, lineWidth: 6) Circle().trim(from: 0, to: min(1, status.progress)).stroke(barColor, style: StrokeStyle(lineWidth: 6, lineCap: .round)).rotationEffect(.degrees(-90)) Text("\(Int((status.progress * 100).rounded()))%").font(palette.figure(10, weight: .medium)) } .frame(width: 44, height: 44) VStack(alignment: .leading, spacing: 2) { Text(name).font(.system(size: 13, weight: .semibold)) HStack(spacing: 4) { Text(Money.format(status.spent, cents: false) + "/" + Money.format(status.available, cents: false)).font(palette.figure(11, weight: .regular)).foregroundStyle(palette.muted) if status.carried != 0 { Text("incl. \(Money.format(status.carried, cents: false, signed: true)) rollover").font(.system(size: 10)).foregroundStyle(palette.muted) } } } Spacer() Text(caption).font(.system(size: 11, weight: .semibold)).foregroundStyle(over ? palette.loss : palette.muted) } } var capsule: some View { VStack(alignment: .leading, spacing: 6) { HStack(alignment: .firstTextBaseline) { Text(name).font(.system(size: 13, weight: .semibold)) Spacer() Text(caption).font(.system(size: 12, weight: .medium)).foregroundStyle(over ? palette.loss : palette.muted) } GeometryReader { geo in ZStack(alignment: .leading) { Capsule().fill(palette.line) Capsule().fill(barColor).frame(width: geo.size.width * CGFloat(min(1, status.progress))) Rectangle().fill(palette.text).frame(width: 2, height: 14).offset(x: geo.size.width * CGFloat(status.pace) - 1) .accessibilityHidden(true) } } .frame(height: 10) 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" : "")) .font(palette.figure(11, weight: .regular)).foregroundStyle(palette.muted) } } var ledger: some View { VStack(alignment: .leading, spacing: 4) { HStack(alignment: .firstTextBaseline) { Text(name).font(.system(size: 14, design: .serif)) Text("\(NSDecimalNumber(decimal: status.spent.rounded(0)).intValue) of \(NSDecimalNumber(decimal: status.available.rounded(0)).intValue)") .font(.system(size: 12, design: .serif).italic()).foregroundStyle(palette.muted) Spacer() Text(caption).font(.system(size: 13, design: .serif)).foregroundStyle(over ? palette.loss : palette.text) } GeometryReader { geo in ZStack(alignment: .leading) { Rectangle().fill(palette.line).frame(height: 1) Rectangle().fill(over ? palette.loss : palette.text).frame(width: geo.size.width * CGFloat(min(1, status.progress)), height: 2) Rectangle().fill(palette.accent).frame(width: 1.5, height: 9).offset(x: geo.size.width * CGFloat(status.pace)) } } .frame(height: 9) } .padding(.vertical, 4) } } /// Tiny bars of the last weeks of an account's balance (Afterhours account cards). public struct Sparkline: View { @Environment(\.palette) private var palette let values: [Double] let colorIndex: Int public init(_ values: [Double], colorIndex: Int) { self.values = values; self.colorIndex = colorIndex } public var body: some View { let lo = values.min() ?? 0, hi = values.max() ?? 1, span = max(hi - lo, 1) HStack(alignment: .bottom, spacing: 2) { ForEach(values.indices, id: \.self) { i in RoundedRectangle(cornerRadius: 1).fill(palette.color(colorIndex).opacity(i == values.count - 1 ? 1 : 0.55)) .frame(width: 3, height: 4 + 18 * CGFloat((values[i] - lo) / span)) } } .frame(height: 22, alignment: .bottom) .accessibilityHidden(true) } }