← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Views/Charts/ChartsView.swift (10900B)

1import OSLog
2import SwiftUI
3
4/// What the Charts tab shows, reloaded when the period changes or the tab
5/// is shown again.
6@MainActor
7@Observable
8final class ChartsModel {
9    private(set) var data = ChartData(period: .month)
10    private(set) var isLoaded = false
11    /// The period last asked for, so a slower load for an earlier one
12    /// doesn't replace it.
13    private var requested: ChartPeriod?
14
15    private let logger = Logger(subsystem: "net.inqk.reportage", category: "Charts")
16
17    var summaries: [QuestionSummary] { data.summaries }
18
19    func load(_ period: ChartPeriod, from store: ReportStore?) async {
20        guard let store else { return }
21        requested = period
22        do {
23            let data = try await store.chartData(for: period)
24            guard requested == period else { return }
25            self.data = data
26            isLoaded = true
27        } catch {
28            logger.error("Couldn't summarise reports: \(error)")
29        }
30    }
31
32    func summary(id: String) -> QuestionSummary? {
33        summaries.first { $0.id == id }
34    }
35}
36
37/// What each question's answers came to over a period, one card per
38/// question, each opening the question in full.
39struct ChartsView: View {
40    @Environment(\.reportStore) private var store
41    @AppStorage("chartPeriod") private var period = ChartPeriod.month
42    @State private var model = ChartsModel()
43
44    var body: some View {
45        NavigationStack {
46            List {
47                ChartsTitle(period: $period)
48                Section {
49                    ForEach(model.summaries) { summary in
50                        NavigationLink {
51                            QuestionChartView(id: summary.id, model: model)
52                        } label: {
53                            SummaryCard(summary: summary)
54                        }
55                        .settingsRow()
56                    }
57                    if model.isLoaded, model.summaries.isEmpty {
58                        SettingsNote { Text("No questions were answered in this period.") }
59                    }
60                } header: {
61                    SettingsHeading("Questions")
62                }
63                if !model.data.context.isEmpty {
64                    Section {
65                        ContextCards(model: model)
66                    } header: {
67                        SettingsHeading("Context")
68                    }
69                }
70            }
71            .listStyle(.plain)
72            .scrollContentBackground(.hidden)
73            .tabBarClearance()
74            .background(Theme.paper)
75            .foregroundStyle(Theme.ink)
76            .toolbar(.hidden, for: .navigationBar)
77        }
78        // Shown again, the tab picks up reports filed or edited since.
79        .onAppear { Task { await model.load(period, from: store) } }
80        .onChange(of: period) { Task { await model.load(period, from: store) } }
81        .task {
82            for await _ in NotificationCenter.default.notifications(named: .summaryLookupChanged) {
83                await model.load(period, from: store)
84            }
85        }
86    }
87}
88
89/// The screen's title, set like the timeline's, with the period beside it.
90private struct ChartsTitle: View {
91    @Binding var period: ChartPeriod
92
93    var body: some View {
94        HStack(alignment: .firstTextBaseline) {
95            Text("Charts")
96                .screenTitle()
97            Spacer()
98            PeriodMenu(period: $period)
99        }
100        .frame(minHeight: 44)
101        .listRowInsets(EdgeInsets(top: 8, leading: Theme.margin, bottom: 20, trailing: Theme.margin))
102        .listRowBackground(Theme.paper)
103        .listRowSeparatorTint(Theme.ink)
104        .listRowSeparator(.hidden, edges: .top)
105    }
106}
107
108/// Chooses the period the charts cover. A menu rather than a picker, which
109/// a list row would show with its label at the leading edge, beside the
110/// title.
111private struct PeriodMenu: View {
112    @Binding var period: ChartPeriod
113
114    var body: some View {
115        Menu {
116            Picker("Period", selection: $period) {
117                ForEach(ChartPeriod.allCases, id: \.self) { period in
118                    Text(period.title).tag(period)
119                }
120            }
121        } label: {
122            HStack(spacing: 4) {
123                Text(period.title)
124                Image(systemName: "chevron.up.chevron.down")
125                    .imageScale(.small)
126            }
127            .font(.body)
128            .foregroundStyle(Theme.accent)
129        }
130        .accessibilityLabel("Period")
131        .accessibilityValue(period.title)
132    }
133}
134
135/// A question's prompt and the gist of its answers: the top few, the share
136/// answering yes, or the average.
137private struct SummaryCard: View {
138    let summary: QuestionSummary
139
140    /// How many answers a card lists before the rest are counted.
141    private static let shown = 3
142
143    var body: some View {
144        VStack(alignment: .leading, spacing: Theme.itemGap) {
145            Text(summary.question.prompt)
146                .font(Theme.serif(.body, weight: .medium))
147            switch summary.question.kind {
148            case .yesNo:
149                ProportionBar(summary: summary)
150            case .number:
151                if let numbers = summary.numbers {
152                    Text("Average \(numbers.mean.formatted(.number.precision(.fractionLength(0...1))))")
153                        .font(Theme.serif(.body))
154                }
155            case .note:
156                EmptyView()
157            default:
158                TallyBars(tallies: Array(summary.tallies.prefix(Self.shown)), summary: summary)
159            }
160            footnote
161                .font(.footnote)
162                .foregroundStyle(Theme.muted)
163        }
164        .padding(.vertical, 4)
165    }
166
167    /// How many reports answered, or notes were written, and how many
168    /// answers the card leaves out. Built as `Text` so the counts inflect.
169    private var footnote: Text {
170        let answered =
171            summary.question.kind == .note
172            ? Text("^[\(summary.notes.count) note](inflect: true)", comment: "Notes written, on a chart")
173            : Text("^[\(summary.answered) report](inflect: true)", comment: "Reports answering, on a chart")
174        let more = summary.tallies.count - Self.shown
175        guard ![.yesNo, .number, .note].contains(summary.question.kind), more > 0 else { return answered }
176        return Text("\(answered) · \(more) more", comment: "Reports answering, and answers not listed on a chart card")
177    }
178}
179
180/// Each answer's name and count over a bar in proportion to the most given.
181/// With a selection, each answer can be chosen, and the others' bars fade.
182struct TallyBars: View {
183    let tallies: [Tally]
184    let summary: QuestionSummary
185    var selection: Binding<String?>?
186
187    var body: some View {
188        let most = tallies.map(\.count).max() ?? 1
189        VStack(alignment: .leading, spacing: Theme.itemGap) {
190            ForEach(tallies) { tally in
191                let isChosen = selection.map { $0.wrappedValue == tally.id } ?? true
192                row(for: tally, most: most, isChosen: isChosen)
193                    .contentShape(Rectangle())
194                    .onTapGesture { selection?.wrappedValue = tally.id }
195                    .accessibilityElement(children: .ignore)
196                    .accessibilityLabel(Text(tally.label))
197                    .accessibilityValue(
198                        Text(
199                            "^[\(tally.count) report](inflect: true), \(summary.share(of: tally).formatted(.percent.precision(.fractionLength(0))))"
200                        ))
201                    .accessibilityAddTraits(selection == nil ? [] : isChosen ? [.isButton, .isSelected] : .isButton)
202            }
203        }
204    }
205
206    private func row(for tally: Tally, most: Int, isChosen: Bool) -> some View {
207        VStack(alignment: .leading, spacing: 4) {
208            HStack(alignment: .firstTextBaseline) {
209                Text(tally.label)
210                    .font(Theme.serif(.body, weight: selection != nil && isChosen ? .semibold : .regular))
211                Spacer()
212                Text(tally.count.formatted())
213                    .font(.footnote.monospacedDigit())
214                    .foregroundStyle(Theme.muted)
215            }
216            Bar(fraction: Double(tally.count) / Double(most))
217                .opacity(isChosen ? 1 : 0.35)
218        }
219    }
220}
221
222/// A thin bar, rounded at its end, filling `fraction` of the width.
223private struct Bar: View {
224    let fraction: Double
225
226    var body: some View {
227        GeometryReader { geometry in
228            UnevenRoundedRectangle(bottomTrailingRadius: 4, topTrailingRadius: 4)
229                .fill(Theme.accent)
230                .frame(width: max(4, geometry.size.width * fraction))
231        }
232        .frame(height: 8)
233    }
234}
235
236/// The shares answering yes and no, as one bar split between them.
237struct ProportionBar: View {
238    let summary: QuestionSummary
239
240    var body: some View {
241        let yes = summary.tallies.first { $0.id == ResponseValue.yesOption }
242        let no = summary.tallies.first { $0.id == ResponseValue.noOption }
243        let share = yes.map(summary.share(of:)) ?? 0
244        VStack(alignment: .leading, spacing: 4) {
245            HStack(alignment: .firstTextBaseline) {
246                label(yes, fallback: String(localized: "Yes", comment: "Answer to a yes/no question"))
247                Spacer()
248                label(no, fallback: String(localized: "No", comment: "Answer to a yes/no question"))
249            }
250            GeometryReader { geometry in
251                let gap: CGFloat = share > 0 && share < 1 ? 2 : 0
252                let width = max(0, geometry.size.width - gap)
253                HStack(spacing: gap) {
254                    if share > 0 {
255                        UnevenRoundedRectangle(
256                            topLeadingRadius: 4, bottomLeadingRadius: 4,
257                            bottomTrailingRadius: share == 1 ? 4 : 0, topTrailingRadius: share == 1 ? 4 : 0
258                        )
259                        .fill(Theme.accent)
260                        .frame(width: width * share)
261                    }
262                    if share < 1 {
263                        UnevenRoundedRectangle(
264                            topLeadingRadius: share == 0 ? 4 : 0, bottomLeadingRadius: share == 0 ? 4 : 0,
265                            bottomTrailingRadius: 4, topTrailingRadius: 4
266                        )
267                        .fill(Theme.rule)
268                    }
269                }
270            }
271            .frame(height: 8)
272        }
273        .accessibilityElement(children: .combine)
274    }
275
276    private func label(_ tally: Tally?, fallback: String) -> some View {
277        let share = tally.map(summary.share(of:)) ?? 0
278        return Text("\(tally?.label ?? fallback) \(Text(share.formatted(.percent.precision(.fractionLength(0)))).foregroundStyle(Theme.muted))")
279            .font(Theme.serif(.body))
280    }
281}