← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Views/Charts/TrendChart.swift (6384B)

1import Charts
2import SwiftUI
3
4/// A value over the period, one bar for each span, or for each span its
5/// range with its average marked. Touching the chart shows a span's value.
6struct TrendChart: View {
7    let points: [TrendPoint]
8    let bucket: Calendar.Component
9    /// The span the chart covers, so periods with gaps keep their width.
10    let domain: ClosedRange<Date>?
11    /// Whether each point is drawn as its range, from low to high.
12    var showsRange = false
13    /// The value axis, such as 0...1 for a share; automatic when `nil`.
14    var valueDomain: ClosedRange<Double>?
15    let format: (Double) -> String
16
17    @State private var selection: Date?
18    private let calendar = Calendar.current
19
20    var body: some View {
21        Chart {
22            ForEach(points) { point in
23                if showsRange, let low = point.low, let high = point.high {
24                    BarMark(
25                        x: .value("Date", point.date, unit: bucket),
26                        yStart: .value("Lowest", low), yEnd: .value("Highest", high)
27                    )
28                    .foregroundStyle(Theme.accent.opacity(0.3))
29                    .cornerRadius(4)
30                    .accessibilityLabel(spanTitle(point.date))
31                    .accessibilityValue(
32                        "\(format(point.value)), \(format(low)) to \(format(high))")
33                    PointMark(x: .value("Date", point.date, unit: bucket), y: .value("Average", point.value))
34                        .foregroundStyle(Theme.accent)
35                        .symbolSize(24)
36                        .accessibilityHidden(true)
37                } else {
38                    BarMark(x: .value("Date", point.date, unit: bucket), y: .value("Value", point.value))
39                        .foregroundStyle(Theme.accent)
40                        .cornerRadius(4)
41                        .accessibilityLabel(spanTitle(point.date))
42                        .accessibilityValue(format(point.value))
43                }
44            }
45            if let selected {
46                RuleMark(x: .value("Date", selected.date, unit: bucket))
47                    .foregroundStyle(Theme.muted.opacity(0.5))
48                    .lineStyle(StrokeStyle(lineWidth: 1))
49                    .annotation(
50                        position: .top, spacing: 4,
51                        overflowResolution: .init(x: .fit(to: .chart), y: .disabled)
52                    ) {
53                        VStack(spacing: Theme.lineGap) {
54                            Text(spanTitle(selected.date))
55                                .font(.caption)
56                                .foregroundStyle(Theme.muted)
57                            Text(selectedValue(selected))
58                                .font(.footnote.weight(.semibold).monospacedDigit())
59                                .foregroundStyle(Theme.ink)
60                        }
61                        .padding(.horizontal, 8)
62                        .padding(.vertical, 4)
63                        .background(Theme.field, in: RoundedRectangle(cornerRadius: 6))
64                    }
65            }
66        }
67        .chartXScale(domain: xDomain)
68        .chartYScale(domain: yDomain)
69        .chartXSelection(value: $selection)
70        .chartXAxis {
71            AxisMarks(values: .automatic(desiredCount: 4)) { _ in
72                AxisTick(stroke: StrokeStyle(lineWidth: 1))
73                    .foregroundStyle(Theme.rule)
74                AxisValueLabel(format: axisFormat)
75                    .foregroundStyle(Theme.muted)
76            }
77        }
78        .chartYAxis {
79            AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { value in
80                AxisGridLine(stroke: StrokeStyle(lineWidth: 1))
81                    .foregroundStyle(Theme.rule)
82                AxisValueLabel {
83                    if let number = value.as(Double.self) {
84                        Text(format(number))
85                    }
86                }
87                .foregroundStyle(Theme.muted)
88            }
89        }
90        .frame(height: 200)
91        .padding(.top, 36)
92    }
93
94    private var xDomain: ClosedRange<Date> {
95        if let domain {
96            let end = calendar.dateInterval(of: bucket, for: domain.upperBound)?.end ?? domain.upperBound
97            return calendar.start(of: bucket, for: domain.lowerBound)...end
98        }
99        let dates = points.map(\.date)
100        let start = dates.min() ?? Date()
101        let last = dates.max() ?? start
102        return start...(calendar.dateInterval(of: bucket, for: last)?.end ?? last)
103    }
104
105    private var yDomain: ClosedRange<Double> {
106        if let valueDomain { return valueDomain }
107        // A range sits within its values; bars stand on zero.
108        if showsRange {
109            let low = points.map { $0.low ?? $0.value }.min() ?? 0
110            let high = points.map { $0.high ?? $0.value }.max() ?? 1
111            let margin = max((high - low) * 0.1, 1)
112            return (low - margin)...(high + margin)
113        }
114        return 0...max((points.map(\.value).max() ?? 1) * 1.1, 1)
115    }
116
117    private var selected: TrendPoint? {
118        guard let selection else { return nil }
119        let span = calendar.start(of: bucket, for: selection)
120        return points.first { $0.date == span }
121    }
122
123    private func selectedValue(_ point: TrendPoint) -> String {
124        guard showsRange, let low = point.low, let high = point.high else { return format(point.value) }
125        return String(
126            localized: "\(format(point.value)) (\(format(low))–\(format(high)))",
127            comment: "A chart's average for a span, with its lowest and highest")
128    }
129
130    private var axisFormat: Date.FormatStyle {
131        switch bucket {
132        case .month: .dateTime.month(.abbreviated).year(.twoDigits)
133        default: .dateTime.day().month(.abbreviated)
134        }
135    }
136
137    /// The span starting at `date`: a day, the week starting then, or a
138    /// month.
139    private func spanTitle(_ date: Date) -> String {
140        switch bucket {
141        case .weekOfYear:
142            String(
143                localized: "Week of \(date.formatted(.dateTime.day().month(.abbreviated)))",
144                comment: "The week a chart's bar covers")
145        case .month: date.formatted(.dateTime.month(.wide).year())
146        default: date.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))
147        }
148    }
149}