Branchwell

Graphley / app · graphley.ai / Sources / AnalyticsUI / Charts.swift

Raw 7.7 KB on d69ca9c4c8ff088be085e80dbb7478e9463bddf8
1import SwiftUI
2import Charts
3import AnalyticsKit
4
5/// Daily values with an area fill, a faint grid, an emphasized last point and a hover/drag readout.
6public struct TrendChart: View {
7 let days: [String], values: [Double], color: Color, label: String
8 @State private var selected: String?
9 @State private var plotWidth: CGFloat = 600
10 public init(days: [String], values: [Double], color: Color = Tide.accent, label: String) {
11 self.days = days; self.values = values; self.color = color; self.label = label
12 }
13 public var body: some View {
14 Chart {
15 ForEach(Array(zip(days, values)), id: \.0) { day, v in
16 AreaMark(x: .value("Day", Self.date(day)), y: .value(label, v))
17 .foregroundStyle(LinearGradient(colors: [color.opacity(0.28), color.opacity(0.02)], startPoint: .top, endPoint: .bottom))
18 LineMark(x: .value("Day", Self.date(day)), y: .value(label, v)).foregroundStyle(color).lineStyle(.init(lineWidth: 2))
19 }
20 if let last = days.last, let v = values.last {
21 PointMark(x: .value("Day", Self.date(last)), y: .value(label, v)).foregroundStyle(color).symbolSize(40)
22 }
23 if let selected, let i = days.firstIndex(of: selected) {
24 RuleMark(x: .value("Day", Self.date(selected))).foregroundStyle(Tide.ink.opacity(0.3))
25 .annotation(position: .top, overflowResolution: .init(x: .fit, y: .disabled)) {
26 VStack(alignment: .leading, spacing: 2) {
27 Text(Self.date(selected), format: .dateTime.month().day()).font(Tide.caption)
28 Text(Tide.number(values[i])).font(Tide.figure(13))
29 }
30 .foregroundStyle(Tide.surface)
31 .padding(.vertical, 6).padding(.horizontal, 8)
32 .background(Tide.ink, in: RoundedRectangle(cornerRadius: 6))
33 .shadow(color: Color(light: 0x0E2830, dark: 0x000000).opacity(0.35), radius: 8, y: 6)
34 }
35 }
36 }
37 .chartXSelection(value: Binding(get: { selected.map(Self.date) }, set: { selected = $0.map { DayKey.string($0) } }))
38 .chartYAxis { AxisMarks(position: .leading) { _ in AxisGridLine(stroke: StrokeStyle(lineWidth: 1, dash: [2, 3])).foregroundStyle(Tide.line); AxisValueLabel().font(Tide.figure(10.5)).foregroundStyle(Tide.muted) } }
39 .chartXAxis { AxisMarks(values: dayTicks(days, width: plotWidth)) { value in AxisValueLabel(format: .dateTime.month(.abbreviated).day(), anchor: value.index == value.count - 1 ? .topTrailing : .top).font(Tide.figure(10.5)).foregroundStyle(Tide.muted) } }
40 .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { plotWidth = $0 }
41 .accessibilityLabel(label)
42 }
43 static func date(_ s: String) -> Date { ISO8601DateFormatter.day.date(from: s) ?? .now }
44}
45
46/// Stacked daily totals, one color per series (sites, or platforms for App Store downloads).
47public struct StackedChart: View {
48 public struct Series: Identifiable { public let id: String; public let name: String; public let color: Color; public let values: [Double]
49 public init(id: String, name: String, color: Color, values: [Double]) { self.id = id; self.name = name; self.color = color; self.values = values } }
50 let days: [String], series: [Series], bars: Bool
51 @State private var plotWidth: CGFloat = 600
52 public init(days: [String], series: [Series], bars: Bool = false) { self.days = days; self.series = series; self.bars = bars }
53 public var body: some View {
54 Chart {
55 ForEach(series) { s in
56 ForEach(Array(zip(days, s.values)), id: \.0) { day, v in
57 if bars {
58 BarMark(x: .value("Day", TrendChart.date(day), unit: .day), y: .value("Count", v)).foregroundStyle(by: .value("Series", s.name))
59 } else {
60 AreaMark(x: .value("Day", TrendChart.date(day)), y: .value("Count", v), stacking: .standard).foregroundStyle(by: .value("Series", s.name))
61 }
62 }
63 }
64 }
65 .chartForegroundStyleScale(domain: series.map(\.name), range: series.map(\.color))
66 .chartYAxis { AxisMarks(position: .leading) { _ in AxisGridLine(stroke: StrokeStyle(lineWidth: 1, dash: [2, 3])).foregroundStyle(Tide.line); AxisValueLabel().font(Tide.figure(10.5)).foregroundStyle(Tide.muted) } }
67 .chartXAxis { AxisMarks(values: dayTicks(days, width: plotWidth)) { value in AxisValueLabel(format: .dateTime.month(.abbreviated).day(), anchor: value.index == value.count - 1 ? .topTrailing : .top).font(Tide.figure(10.5)).foregroundStyle(Tide.muted) } }
68 .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { plotWidth = $0 }
69 .chartLegend(position: .bottom, alignment: .leading) {
70 HStack(spacing: 14) {
71 ForEach(series) { s in
72 HStack(spacing: 6) {
73 RoundedRectangle(cornerRadius: 2).fill(s.color).frame(width: 9, height: 9)
74 Text(s.name).font(Tide.caption).foregroundStyle(Tide.muted).lineLimit(1)
75 }
76 }
77 }
78 }
79 }
80}
81
82public struct Sparkline: View {
83 let values: [Double], color: Color
84 public init(_ values: [Double], color: Color) { self.values = values; self.color = color }
85 public var body: some View {
86 Chart(Array(values.enumerated()), id: \.offset) { i, v in
87 AreaMark(x: .value("i", i), y: .value("v", v)).foregroundStyle(color.opacity(0.18))
88 LineMark(x: .value("i", i), y: .value("v", v)).foregroundStyle(color)
89 }
90 .chartXAxis(.hidden).chartYAxis(.hidden).frame(width: 80, height: 26)
91 .accessibilityHidden(true)
92 }
93}
94
95/// Ranked rows: label and value on one line, a thin bar under them, so the fill never cuts through text.
96public struct BarList: View {
97 let rows: [(String, Double)]
98 public init(_ rows: [(String, Double)]) { self.rows = rows }
99 public var body: some View {
100 let top = max(1, rows.map(\.1).max() ?? 1)
101 VStack(spacing: 10) {
102 ForEach(rows, id: \.0) { label, v in
103 VStack(spacing: 5) {
104 HStack(alignment: .firstTextBaseline) {
105 Text(label).lineLimit(1).truncationMode(.middle).font(Tide.secondary).foregroundStyle(Tide.ink)
106 Spacer(minLength: 8)
107 Text(Tide.number(v)).font(Tide.figure(12)).foregroundStyle(Tide.ink)
108 }
109 GeometryReader { g in
110 ZStack(alignment: .leading) {
111 Capsule().fill(Tide.line)
112 Capsule().fill(Tide.accent).frame(width: max(4, g.size.width * v / top))
113 }
114 }.frame(height: 5)
115 }
116 }
117 }
118 }
119}
120
121/// X-axis ticks counted back from the last day, so the newest day always gets a label, spaced
122/// for the chart's width (about 90 pt per date, room for the newest label to shift inside the edge) so labels never touch.
123func dayTicks(_ days: [String], width: CGFloat) -> [Date] {
124 guard !days.isEmpty else { return [] }
125 let fits = max(2, Int(width / 90))
126 let needed = Int((Double(days.count - 1) / Double(fits - 1)).rounded(.up))
127 let steps = days.count <= 10 ? [1, 2, 3, 5] : [7, 14, 21, 30, 60, 90]
128 let step = steps.first { $0 >= needed } ?? needed
129 return stride(from: days.count - 1, through: 0, by: -step).map { TrendChart.date(days[$0]) }.reversed()
130}
131
132extension ISO8601DateFormatter {
133 nonisolated(unsafe) static let day: ISO8601DateFormatter = { let f = ISO8601DateFormatter(); f.formatOptions = [.withFullDate]; f.timeZone = .current; return f }()
134}