commit f3130594d74d3b0a9cee945a8f449264fdfc824d
parent f3695c6a2bab9d3ed92c25fc448bb6e074c352b5
Author: Michael Camilleri <[email protected]>
Date: Wed, 21 Oct 2026 00:11:08 +0900
Add a Charts tab with per-question summaries
This commit adds a Charts tab between Timeline and Settings. It shows a
card for each question answered in the chosen period — the past week,
month or year, or all time — giving the gist of its answers: the top
three activities, people, places or choices as bars with counts, the
share answering yes, the average of a number, or the count of notes.
Tapping a card opens the question in full, with every answer, the lowest
and highest number or the notes.
Periods trail back from now rather than following the calendar, so
early in a month the charts aren't nearly empty, and the period chosen
is remembered. Answers are counted once per report, with a merged token
counted as the token it went into, and shares are of the reports that
answered the question. Yes/no and choice answers keep the question's
order so they don't trade places as the period changes.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 32 | +++++++++++++++++++++++++++----- |
| M | Reportage.xcodeproj/project.pbxproj | | | 32 | ++++++++++++++++++++++++++++++++ |
| A | Reportage/Services/Charts/AnswerSummary.swift | | | 186 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | Reportage/Views/Charts/ChartsView.swift | | | 238 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | Reportage/Views/Charts/QuestionChartView.swift | | | 88 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/RootView.swift | | | 7 | +++++-- |
| A | Tests/Unit/AnswerSummaryTests.swift | | | 122 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
7 files changed, 698 insertions(+), 7 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -49,8 +49,6 @@ how the Reporter archive maps in.
- Backfilling the Reporter archive: the weather gap from April 2023, Health
from 2014, and location answers skipped since Reporter lost venue lookup.
See [Backfills](#open-questions).
-- In-app visualisations. Export comes first and charts come later. The data
- model should not get in the way of Swift Charts later on.
- iPad and Mac apps.
- Answering surveys inline in the notification.
@@ -96,8 +94,7 @@ The look is called Almanac: ink on paper, like a printed journal.
is a wordmark: italic, with its full stop in a brighter auburn (rust) than
the accent, since a mark that small has to stand out by colour alone. All
sizes are Dynamic Type styles.
-- **Tabs:** Timeline and Settings, with Visualisations joining them in
- Phase 6. The timeline keeps its serif 'Reportage' title, beside the quick
+- **Tabs:** Timeline, Charts and Settings. The timeline keeps its serif 'Reportage' title, beside the quick
log and new report buttons. A tapped prompt switches to the timeline to
open its survey.
- **Home screen:** reports grouped under day headings, newest first. Each
@@ -951,6 +948,29 @@ default); when included, each is the original JSON text as a string.
report, question and token and seeds the default questions again, leaving
the app as a fresh install has it. Prompt settings are kept.
+## Charts
+
+The Charts tab covers a period ending now: the past week, month or year, or
+all time. These trail back from today rather than following the calendar,
+so the start of a month isn't nearly empty. The period chosen is
+remembered.
+
+The tab shows one card per question answered in the period: unarchived
+questions in survey order, then archived ones. A card gives the gist: the
+top three answers for token and choice questions, the share answering yes,
+the average of a number, or the count of notes. Tapping it opens the
+question in full, with every answer, the lowest, average and highest number,
+or the notes, newest first.
+
+Answers are counted per report, so a report that gave two answers to a
+question counts once for each, and a token merged into another counts as
+that token, once. Shares are of the reports that answered the question, not
+of every report. Yes/no and choice answers keep the question's order, so an
+answer keeps its place as the period changes; tokens are most used first.
+
+Bars are drawn by hand: a ranked list with a bar under each name reads
+better than an axis. Swift Charts is for the charts over time that follow.
+
## Phases
1. **Foundation.** Project scaffold, Core Data model, Reporter importer with
@@ -966,7 +986,9 @@ the app as a fresh install has it. Prompt settings are kept.
5. **Derived context.** Health. Live weather is part of capture (see
[Weather](#weather)). Backfills are deferred (see
[Open Questions](#open-questions)).
-6. **Visualisations.**
+6. **Visualisations.** The Charts tab, in steps: per-question summaries,
+ then trends over time, a map of places, and a calendar and time of day.
+ See [Charts](#charts).
7. **Synced schema.** Settle the [open questions](#open-questions) that change
synced data before the record formats are fixed: missed prompts, keeping
past prompt settings, adding, removing and rewording
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -32,6 +32,7 @@
34C3A453ABC838F73DC3E294 /* ReportDetails.swift in Sources */ = {isa = PBXBuildFile; fileRef = C269C1BE83C1A5E08AC087E3 /* ReportDetails.swift */; };
35D02EAE3D95DB5CCEE8A82E /* PromptScheduleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC27A2AF600780976CFA295C /* PromptScheduleTests.swift */; };
36A35625365E87B39CB88194 /* ReporterImporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48D44876FDE4293FA0460595 /* ReporterImporter.swift */; };
+ 3BDDC4FD8CE13B29BCDE3ADC /* ChartsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D72771A17EAB0F8025CECB32 /* ChartsView.swift */; };
3FBE5C53D33EF78752BEACE0 /* ReporterImportVerifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3ED0CAE575381DCB86FB8EE9 /* ReporterImportVerifier.swift */; };
406D536D7764B3FEB140CAA0 /* EntityMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BE7248E73E2859EFF232170 /* EntityMapping.swift */; };
4A0DEFB7E69A9FC5EAAD99D4 /* RealExportVerificationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */; };
@@ -39,6 +40,7 @@
633A94E029055EA5D50D00AC /* PlaceRanking.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76FFC5FE874467974DD6BFA0 /* PlaceRanking.swift */; };
68DDAB8BB2E679EB7EC1E9C1 /* ReporterImportPlan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 798E1DE82BD53EC5BEBA76B7 /* ReporterImportPlan.swift */; };
690A6B50550B9CE4B954CC0C /* PromptScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C4665B55B0307E899595C1D /* PromptScheduler.swift */; };
+ 696B8F7586F680B1F5C41382 /* AnswerSummaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A4B10FFBEDE5D6E23B1B2B4 /* AnswerSummaryTests.swift */; };
6B71941AAD84B87358A969A0 /* LogPassiveReportIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90F9BD4EA70DCB46924CF9B8 /* LogPassiveReportIntent.swift */; };
6E21E729F89178EBD019980E /* InlineCasing.swift in Sources */ = {isa = PBXBuildFile; fileRef = A00E589A8387E7A1E348503C /* InlineCasing.swift */; };
6E6EAFD0C182B2482F6B6FBD /* HealthFill.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5CC1EB95C82F2D9B0982650 /* HealthFill.swift */; };
@@ -69,6 +71,7 @@
A740B635075EB81AA70ED815 /* ReportDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F498961A14F24AE6CC37453C /* ReportDetailView.swift */; };
A7C988B20CD1C937A2E776D0 /* EventLogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */; };
A93CC28A9DE5B39F41526AC5 /* SleepSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F8F059CE98371610A663BE7 /* SleepSummary.swift */; };
+ ACB648C0A1D54054E21C730E /* QuestionChartView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0A128C9CAF584114977A8D1 /* QuestionChartView.swift */; };
B00AC94E13BC9C602179953E /* SurveyModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E382405EE9DBEC8EE616C1D /* SurveyModelTests.swift */; };
B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 633FE6CD8111A433CA9BE7EC /* AppDelegate.swift */; };
B510BB2C1C11D72DFE15E3C7 /* ReportageExportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */; };
@@ -92,6 +95,7 @@
DF632654B427EE32C44C6F78 /* Context.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F200EBD30BC12D2313E6C6F /* Context.swift */; };
E0137FEEBF13F5D14C07656F /* ReportageExport.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */; };
E2D35546E39153308E9880B1 /* WelcomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92BFA1E8F26662DCF828DD5C /* WelcomeView.swift */; };
+ E3C74ABCE348FFF05890690E /* AnswerSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1ECAE94ED631259AB60F2DAE /* AnswerSummary.swift */; };
E64BB44903A15E99126E73E5 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */; };
E68EF6274FD2F6D54D49F5BD /* ReporterImporterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */; };
E8C13757BF3E2C8384F104A1 /* AppleWeather.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC2D996880DB9C269F0203D5 /* AppleWeather.swift */; };
@@ -145,6 +149,7 @@
1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlacePickerTests.swift; sourceTree = "<group>"; };
1BBAB5AD6266B8F6E3507AE3 /* ReportSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportSummary.swift; sourceTree = "<group>"; };
1C4665B55B0307E899595C1D /* PromptScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptScheduler.swift; sourceTree = "<group>"; };
+ 1ECAE94ED631259AB60F2DAE /* AnswerSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnswerSummary.swift; sourceTree = "<group>"; };
1F200EBD30BC12D2313E6C6F /* Context.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Context.swift; sourceTree = "<group>"; };
2425CB4D9B12D422467F6FD7 /* PromptSchedulerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSchedulerTests.swift; sourceTree = "<group>"; };
24A77AE6DE479403D1D4C9CF /* QuestionPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionPage.swift; sourceTree = "<group>"; };
@@ -153,6 +158,7 @@
30FFB17809ADA84F1036E2A7 /* LegacyBlob.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LegacyBlob.swift; sourceTree = "<group>"; };
36C7E4E96538BB14AD6956CA /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = "<group>"; };
383FF2C73A8FBAA2AB13D653 /* ReportageApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageApp.swift; sourceTree = "<group>"; };
+ 3A4B10FFBEDE5D6E23B1B2B4 /* AnswerSummaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnswerSummaryTests.swift; sourceTree = "<group>"; };
3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RealExportVerificationTests.swift; sourceTree = "<group>"; };
3ED0CAE575381DCB86FB8EE9 /* ReporterImportVerifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportVerifier.swift; sourceTree = "<group>"; };
46FB42E5DB43201A13D6D141 /* PassiveLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PassiveLog.swift; sourceTree = "<group>"; };
@@ -223,6 +229,7 @@
CD433A98973E8B13E42230A1 /* ReportageExporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExporter.swift; sourceTree = "<group>"; };
D03D0770BA2E26D7E4A7DECC /* ReportageModel.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = ReportageModel.xcdatamodel; sourceTree = "<group>"; };
D4AFF3D49ED9E8AC69390925 /* JSONSlicerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONSlicerTests.swift; sourceTree = "<group>"; };
+ D72771A17EAB0F8025CECB32 /* ChartsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChartsView.swift; sourceTree = "<group>"; };
DB87A3E922FA7AE98B93DF1E /* PromptSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSettings.swift; sourceTree = "<group>"; };
E1F55B30D0B5E711A28CD0B1 /* HealthCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthCache.swift; sourceTree = "<group>"; };
E21F898FF60FC3A6AFCA06E9 /* Reportage Unit Tests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = "Reportage Unit Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -232,6 +239,7 @@
E8E474C9A749960D3B6A8619 /* NarrativeBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NarrativeBuilder.swift; sourceTree = "<group>"; };
EC0EF3DA62941ED76148D5BF /* BackgroundLocation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackgroundLocation.swift; sourceTree = "<group>"; };
EC2D996880DB9C269F0203D5 /* AppleWeather.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleWeather.swift; sourceTree = "<group>"; };
+ F0A128C9CAF584114977A8D1 /* QuestionChartView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionChartView.swift; sourceTree = "<group>"; };
F498961A14F24AE6CC37453C /* ReportDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportDetailView.swift; sourceTree = "<group>"; };
F832E0B277D5BF5BC3B6E5D1 /* NotificationsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationsView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -306,6 +314,15 @@
path = Health;
sourceTree = "<group>";
};
+ 40C7D2F3410CAC897AFD7083 /* Charts */ = {
+ isa = PBXGroup;
+ children = (
+ D72771A17EAB0F8025CECB32 /* ChartsView.swift */,
+ F0A128C9CAF584114977A8D1 /* QuestionChartView.swift */,
+ );
+ path = Charts;
+ sourceTree = "<group>";
+ };
4C708676FBAD641AD92F8CA0 /* Reportage */ = {
isa = PBXGroup;
children = (
@@ -370,6 +387,7 @@
EC0EF3DA62941ED76148D5BF /* BackgroundLocation.swift */,
7CE9EDC8448889EB9D4D358E /* FirstLaunch.swift */,
729C291798F29C69029E7DB7 /* InstantReportLogger.swift */,
+ 61C73904D4B05965F0E05370 /* Charts */,
AD85758A0521ED681067B90F /* Export */,
3DA89C2E098DB18D7FD0CC0A /* Health */,
96D6D46E008E39350B203328 /* Narrative */,
@@ -380,6 +398,14 @@
path = Services;
sourceTree = "<group>";
};
+ 61C73904D4B05965F0E05370 /* Charts */ = {
+ isa = PBXGroup;
+ children = (
+ 1ECAE94ED631259AB60F2DAE /* AnswerSummary.swift */,
+ );
+ path = Charts;
+ sourceTree = "<group>";
+ };
6939F7C2C95274DF2BB62D20 /* Shared */ = {
isa = PBXGroup;
children = (
@@ -403,6 +429,7 @@
78F7B34F781A8894EDCB8C74 /* Unit */ = {
isa = PBXGroup;
children = (
+ 3A4B10FFBEDE5D6E23B1B2B4 /* AnswerSummaryTests.swift */,
A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */,
A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */,
695CB01E79016592A3823541 /* HealthTests.swift */,
@@ -506,6 +533,7 @@
5591E042089D038B59B26E9F /* ReportKind+Title.swift */,
A70B6E5B7C07D2CE13E9E771 /* RootView.swift */,
92BFA1E8F26662DCF828DD5C /* WelcomeView.swift */,
+ 40C7D2F3410CAC897AFD7083 /* Charts */,
01DE4634BAAD579B60FBA5ED /* Home */,
2AA377CB45537E6D2364ABF2 /* Report */,
B74082E720FBA1EF05FE11E4 /* Settings */,
@@ -680,6 +708,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ 696B8F7586F680B1F5C41382 /* AnswerSummaryTests.swift in Sources */,
CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */,
A7C988B20CD1C937A2E776D0 /* EventLogTests.swift in Sources */,
905D1185CF8B3426ECB91AFD /* HealthTests.swift in Sources */,
@@ -709,9 +738,11 @@
buildActionMask = 2147483647;
files = (
9F26886E122721BB3F2AFE7F /* AboutView.swift in Sources */,
+ E3C74ABCE348FFF05890690E /* AnswerSummary.swift in Sources */,
B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */,
E8C13757BF3E2C8384F104A1 /* AppleWeather.swift in Sources */,
811704907EE199CC627F0CE5 /* BackgroundLocation.swift in Sources */,
+ 3BDDC4FD8CE13B29BCDE3ADC /* ChartsView.swift in Sources */,
DF632654B427EE32C44C6F78 /* Context.swift in Sources */,
D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */,
A1FBFB9809DD3FF52BD7E5A7 /* DataSection.swift in Sources */,
@@ -746,6 +777,7 @@
690A6B50550B9CE4B954CC0C /* PromptScheduler.swift in Sources */,
C87E1C0465FE7B2917F92846 /* PromptSettings.swift in Sources */,
F38A1CCFAF016AB982EAB791 /* Question.swift in Sources */,
+ ACB648C0A1D54054E21C730E /* QuestionChartView.swift in Sources */,
93B2DAAF451BBE42A539CB94 /* QuestionEditor.swift in Sources */,
85A36A88AB170F0EAC0DAC03 /* QuestionPage.swift in Sources */,
9FEE3B78B770C6A3CF9C6610 /* QuestionsView.swift in Sources */,
diff --git a/Reportage/Services/Charts/AnswerSummary.swift b/Reportage/Services/Charts/AnswerSummary.swift
@@ -0,0 +1,186 @@
+import CoreData
+import Foundation
+
+/// The span of reports the charts cover, ending now.
+enum ChartPeriod: String, CaseIterable, Sendable {
+ case week
+ case month
+ case year
+ case all
+
+ var title: String {
+ switch self {
+ case .week: String(localized: "Past Week", comment: "A chart period")
+ case .month: String(localized: "Past Month", comment: "A chart period")
+ case .year: String(localized: "Past Year", comment: "A chart period")
+ case .all: String(localized: "All Time", comment: "A chart period")
+ }
+ }
+
+ /// When the period starts, or `nil` for all time.
+ func start(endingAt now: Date, calendar: Calendar = .current) -> Date? {
+ switch self {
+ case .week: calendar.date(byAdding: .day, value: -7, to: now)
+ case .month: calendar.date(byAdding: .month, value: -1, to: now)
+ case .year: calendar.date(byAdding: .year, value: -1, to: now)
+ case .all: nil
+ }
+ }
+}
+
+/// One answer to a question, with when its report was made.
+struct AnswerRecord: Sendable {
+ var questionID: String
+ var date: Date
+ var value: ResponseValue
+}
+
+/// How often one answer was given: a token, a choice, or yes or no.
+struct Tally: Identifiable, Equatable, Sendable {
+ /// The token's ID, after merges, or the option.
+ var id: String
+ var label: String
+ var count: Int
+}
+
+/// The spread of a number question's answers.
+struct NumberSummary: Equatable, Sendable {
+ var mean: Double
+ var lowest: Double
+ var highest: Double
+}
+
+/// What a question's answers came to over a period.
+struct QuestionSummary: Identifiable, Equatable, Sendable {
+ var question: Question
+ /// How many reports answered the question.
+ var answered: Int
+ /// For token, choice and yes/no questions: each answer and how many
+ /// reports gave it. Yes/no and choice answers keep the question's order;
+ /// tokens are most used first.
+ var tallies: [Tally] = []
+ var numbers: NumberSummary?
+ /// For note questions: the notes, newest first.
+ var notes: [Note] = []
+
+ var id: String { question.id }
+
+ struct Note: Equatable, Sendable {
+ var date: Date
+ var text: String
+ }
+
+ /// The share of the reports answering the question that gave `tally`.
+ func share(of tally: Tally) -> Double {
+ answered == 0 ? 0 : Double(tally.count) / Double(answered)
+ }
+}
+
+enum AnswerSummary {
+ /// Summaries of the questions answered in `rows`: unarchived questions
+ /// in survey order, then archived ones. Questions without answers are
+ /// left out. A token merged into another counts as that token, and once
+ /// per answer.
+ static func summarise(
+ _ rows: [AnswerRecord], questions: [Question], lookup: SummaryLookup
+ ) -> [QuestionSummary] {
+ let byQuestion = Dictionary(grouping: rows, by: \.questionID)
+ let ordered = questions.filter { $0.archivedAt == nil } + questions.filter { $0.archivedAt != nil }
+ return ordered.compactMap { question in
+ guard let rows = byQuestion[question.id], !rows.isEmpty else { return nil }
+ return summary(of: question, rows: rows, lookup: lookup)
+ }
+ }
+
+ private static func summary(
+ of question: Question, rows: [AnswerRecord], lookup: SummaryLookup
+ ) -> QuestionSummary {
+ var summary = QuestionSummary(question: question, answered: rows.count)
+ var counts: [String: Int] = [:]
+ var numbers: [Double] = []
+ for row in rows {
+ switch row.value {
+ case .tokens(let ids):
+ for id in Set(ids.map { lookup.mergedIDs[$0] ?? $0 }) { counts[id, default: 0] += 1 }
+ case .place(let place):
+ counts[lookup.mergedIDs[place.tokenID] ?? place.tokenID, default: 0] += 1
+ case .options(let options):
+ for option in Set(options) { counts[option, default: 0] += 1 }
+ case .number(let number):
+ numbers.append(NSDecimalNumber(decimal: number).doubleValue)
+ case .text(let text):
+ let text = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !text.isEmpty { summary.notes.append(.init(date: row.date, text: text)) }
+ }
+ }
+ if let lowest = numbers.min(), let highest = numbers.max() {
+ summary.numbers = NumberSummary(
+ mean: numbers.reduce(0, +) / Double(numbers.count), lowest: lowest, highest: highest)
+ }
+ summary.notes.sort { $0.date > $1.date }
+
+ switch question.kind {
+ case .yesNo, .choice:
+ let fixed = question.kind == .yesNo ? [ResponseValue.yesOption, ResponseValue.noOption] : question.options
+ // Answers since renamed or removed from the options follow them.
+ let others = counts.keys.filter { !fixed.contains($0) }.sorted { counts[$0]! > counts[$1]! }
+ summary.tallies = (fixed + others).compactMap { option in
+ counts[option].map { Tally(id: option, label: label(of: option), count: $0) }
+ }
+ default:
+ summary.tallies = counts.compactMap { id, count in
+ lookup.tokenTexts[id].map { Tally(id: id, label: $0, count: count) }
+ }
+ .sorted { lhs, rhs in
+ lhs.count != rhs.count
+ ? lhs.count > rhs.count
+ : lhs.label.localizedStandardCompare(rhs.label) == .orderedAscending
+ }
+ }
+ return summary
+ }
+
+ private static func label(of option: String) -> String {
+ switch option {
+ case ResponseValue.yesOption: String(localized: "Yes", comment: "Answer to a yes/no question")
+ case ResponseValue.noOption: String(localized: "No", comment: "Answer to a yes/no question")
+ default: option
+ }
+ }
+}
+
+extension ReportStore {
+ /// Every answer given since `start`, or ever when it's `nil`. Skipped
+ /// questions are left out.
+ func answers(since start: Date?) async throws -> [AnswerRecord] {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ let request = NSFetchRequest<NSDictionary>(entityName: "ResponseEntity")
+ request.resultType = .dictionaryResultType
+ request.predicate =
+ if let start {
+ NSPredicate(format: "value != nil AND report.date >= %@", start as NSDate)
+ } else {
+ NSPredicate(format: "value != nil")
+ }
+ request.propertiesToFetch = ["questionID", "value", "report.date"]
+ return try context.fetch(request).compactMap { row in
+ guard let questionID = row["questionID"] as? String,
+ let data = row["value"] as? Data,
+ let date = row["report.date"] as? Date
+ else { return nil }
+ return AnswerRecord(
+ questionID: questionID, date: date,
+ value: try ModelCoding.decode(ResponseValue.self, from: data))
+ }
+ }
+ }
+
+ /// Summaries of the questions answered in `period`. See `AnswerSummary`.
+ func questionSummaries(for period: ChartPeriod, now: Date = Date()) async throws -> [QuestionSummary] {
+ async let lookup = summaryLookup()
+ async let questions = allQuestions()
+ async let rows = answers(since: period.start(endingAt: now))
+ return try await AnswerSummary.summarise(rows, questions: questions, lookup: lookup)
+ }
+}
diff --git a/Reportage/Views/Charts/ChartsView.swift b/Reportage/Views/Charts/ChartsView.swift
@@ -0,0 +1,238 @@
+import OSLog
+import SwiftUI
+
+/// The summaries the Charts tab shows, reloaded when the period changes or
+/// the tab is shown again.
+@MainActor
+@Observable
+final class ChartsModel {
+ private(set) var summaries: [QuestionSummary] = []
+ private(set) var isLoaded = false
+
+ private let logger = Logger(subsystem: "net.inqk.reportage", category: "Charts")
+
+ func load(_ period: ChartPeriod, from store: ReportStore?) async {
+ guard let store else { return }
+ do {
+ summaries = try await store.questionSummaries(for: period)
+ isLoaded = true
+ } catch {
+ logger.error("Couldn't summarise answers: \(error)")
+ }
+ }
+
+ func summary(id: String) -> QuestionSummary? {
+ summaries.first { $0.id == id }
+ }
+}
+
+/// What each question's answers came to over a period, one card per
+/// question, each opening the question in full.
+struct ChartsView: View {
+ @Environment(\.reportStore) private var store
+ @AppStorage("chartPeriod") private var period = ChartPeriod.month
+ @State private var model = ChartsModel()
+
+ var body: some View {
+ NavigationStack {
+ List {
+ ChartsTitle(period: $period)
+ ForEach(model.summaries) { summary in
+ NavigationLink {
+ QuestionChartView(id: summary.id, period: period, model: model)
+ } label: {
+ SummaryCard(summary: summary)
+ }
+ .settingsRow()
+ }
+ if model.isLoaded, model.summaries.isEmpty {
+ SettingsNote { Text("No questions were answered in this period.") }
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .background(Theme.paper)
+ .foregroundStyle(Theme.ink)
+ .toolbar(.hidden, for: .navigationBar)
+ }
+ // Shown again, the tab picks up reports filed or edited since.
+ .onAppear { Task { await model.load(period, from: store) } }
+ .onChange(of: period) { Task { await model.load(period, from: store) } }
+ .task {
+ for await _ in NotificationCenter.default.notifications(named: .summaryLookupChanged) {
+ await model.load(period, from: store)
+ }
+ }
+ }
+}
+
+/// The screen's title, set like the timeline's, with the period beside it.
+private struct ChartsTitle: View {
+ @Binding var period: ChartPeriod
+
+ var body: some View {
+ HStack(alignment: .firstTextBaseline) {
+ Text("Charts")
+ .screenTitle()
+ Spacer()
+ PeriodMenu(period: $period)
+ }
+ .frame(minHeight: 44)
+ .listRowInsets(EdgeInsets(top: 8, leading: Theme.margin, bottom: 20, trailing: Theme.margin))
+ .listRowBackground(Theme.paper)
+ .listRowSeparatorTint(Theme.ink)
+ .listRowSeparator(.hidden, edges: .top)
+ }
+}
+
+/// Chooses the period the charts cover.
+private struct PeriodMenu: View {
+ @Binding var period: ChartPeriod
+
+ var body: some View {
+ Picker("Period", selection: $period) {
+ ForEach(ChartPeriod.allCases, id: \.self) { period in
+ Text(period.title).tag(period)
+ }
+ }
+ .pickerStyle(.menu)
+ .tint(Theme.accent)
+ }
+}
+
+/// A question's prompt and the gist of its answers: the top few, the share
+/// answering yes, or the average.
+private struct SummaryCard: View {
+ let summary: QuestionSummary
+
+ /// How many answers a card lists before the rest are counted.
+ private static let shown = 3
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: Theme.itemGap) {
+ Text(summary.question.prompt)
+ .font(Theme.serif(.body, weight: .medium))
+ switch summary.question.kind {
+ case .yesNo:
+ ProportionBar(summary: summary)
+ case .number:
+ if let numbers = summary.numbers {
+ Text("Average \(numbers.mean.formatted(.number.precision(.fractionLength(0...1))))")
+ .font(Theme.serif(.body))
+ }
+ case .note:
+ EmptyView()
+ default:
+ TallyBars(tallies: Array(summary.tallies.prefix(Self.shown)), summary: summary)
+ }
+ footnote
+ .font(.footnote)
+ .foregroundStyle(Theme.muted)
+ }
+ .padding(.vertical, 4)
+ }
+
+ /// How many reports answered, or notes were written, and how many
+ /// answers the card leaves out. Built as `Text` so the counts inflect.
+ private var footnote: Text {
+ let answered =
+ summary.question.kind == .note
+ ? Text("^[\(summary.notes.count) note](inflect: true)", comment: "Notes written, on a chart")
+ : Text("^[\(summary.answered) report](inflect: true)", comment: "Reports answering, on a chart")
+ let more = summary.tallies.count - Self.shown
+ guard ![.yesNo, .number, .note].contains(summary.question.kind), more > 0 else { return answered }
+ return Text("\(answered) · \(more) more", comment: "Reports answering, and answers not listed on a chart card")
+ }
+}
+
+/// Each answer's name and count over a bar in proportion to the most given.
+struct TallyBars: View {
+ let tallies: [Tally]
+ let summary: QuestionSummary
+
+ var body: some View {
+ let most = tallies.map(\.count).max() ?? 1
+ VStack(alignment: .leading, spacing: Theme.itemGap) {
+ ForEach(tallies) { tally in
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(alignment: .firstTextBaseline) {
+ Text(tally.label)
+ .font(Theme.serif(.body))
+ Spacer()
+ Text(tally.count.formatted())
+ .font(.footnote.monospacedDigit())
+ .foregroundStyle(Theme.muted)
+ }
+ Bar(fraction: Double(tally.count) / Double(most))
+ }
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(Text(tally.label))
+ .accessibilityValue(
+ Text(
+ "^[\(tally.count) report](inflect: true), \(summary.share(of: tally).formatted(.percent.precision(.fractionLength(0))))"
+ ))
+ }
+ }
+ }
+}
+
+/// A thin bar, rounded at its end, filling `fraction` of the width.
+private struct Bar: View {
+ let fraction: Double
+
+ var body: some View {
+ GeometryReader { geometry in
+ UnevenRoundedRectangle(bottomTrailingRadius: 4, topTrailingRadius: 4)
+ .fill(Theme.accent)
+ .frame(width: max(4, geometry.size.width * fraction))
+ }
+ .frame(height: 8)
+ }
+}
+
+/// The shares answering yes and no, as one bar split between them.
+struct ProportionBar: View {
+ let summary: QuestionSummary
+
+ var body: some View {
+ let yes = summary.tallies.first { $0.id == ResponseValue.yesOption }
+ let no = summary.tallies.first { $0.id == ResponseValue.noOption }
+ let share = yes.map(summary.share(of:)) ?? 0
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(alignment: .firstTextBaseline) {
+ label(yes, fallback: String(localized: "Yes", comment: "Answer to a yes/no question"))
+ Spacer()
+ label(no, fallback: String(localized: "No", comment: "Answer to a yes/no question"))
+ }
+ GeometryReader { geometry in
+ let gap: CGFloat = share > 0 && share < 1 ? 2 : 0
+ let width = max(0, geometry.size.width - gap)
+ HStack(spacing: gap) {
+ if share > 0 {
+ UnevenRoundedRectangle(
+ topLeadingRadius: 4, bottomLeadingRadius: 4,
+ bottomTrailingRadius: share == 1 ? 4 : 0, topTrailingRadius: share == 1 ? 4 : 0
+ )
+ .fill(Theme.accent)
+ .frame(width: width * share)
+ }
+ if share < 1 {
+ UnevenRoundedRectangle(
+ topLeadingRadius: share == 0 ? 4 : 0, bottomLeadingRadius: share == 0 ? 4 : 0,
+ bottomTrailingRadius: 4, topTrailingRadius: 4
+ )
+ .fill(Theme.rule)
+ }
+ }
+ }
+ .frame(height: 8)
+ }
+ .accessibilityElement(children: .combine)
+ }
+
+ private func label(_ tally: Tally?, fallback: String) -> some View {
+ let share = tally.map(summary.share(of:)) ?? 0
+ return Text("\(tally?.label ?? fallback) \(Text(share.formatted(.percent.precision(.fractionLength(0)))).foregroundStyle(Theme.muted))")
+ .font(Theme.serif(.body))
+ }
+}
diff --git a/Reportage/Views/Charts/QuestionChartView.swift b/Reportage/Views/Charts/QuestionChartView.swift
@@ -0,0 +1,88 @@
+import SwiftUI
+
+/// One question's answers over the period in full: every answer given, the
+/// spread of a number, or the notes written.
+struct QuestionChartView: View {
+ let id: String
+ let period: ChartPeriod
+ let model: ChartsModel
+
+ var body: some View {
+ List {
+ if let summary = model.summary(id: id) {
+ Section {
+ VStack(alignment: .leading, spacing: Theme.lineGap) {
+ Text(summary.question.prompt)
+ .font(Theme.serif(.title3, weight: .medium))
+ Text("\(period.title) · ^[\(summary.answered) report](inflect: true)")
+ .font(.footnote)
+ .foregroundStyle(Theme.muted)
+ }
+ .settingsRow()
+ .listRowSeparator(.hidden)
+ }
+ Section {
+ content(for: summary)
+ }
+ } else {
+ SettingsNote { Text("This question wasn't answered in this period.") }
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .background(Theme.paper)
+ .foregroundStyle(Theme.ink)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ @ViewBuilder private func content(for summary: QuestionSummary) -> some View {
+ switch summary.question.kind {
+ case .yesNo:
+ ProportionBar(summary: summary)
+ .settingsRow()
+ TallyBars(tallies: summary.tallies, summary: summary)
+ .settingsRow()
+ case .number:
+ if let numbers = summary.numbers {
+ Grid(alignment: .leading, horizontalSpacing: Theme.blockGap, verticalSpacing: Theme.itemGap) {
+ GridRow {
+ Stat(title: "Average", value: numbers.mean)
+ Stat(title: "Lowest", value: numbers.lowest)
+ Stat(title: "Highest", value: numbers.highest)
+ }
+ }
+ .settingsRow()
+ }
+ case .note:
+ ForEach(Array(summary.notes.enumerated()), id: \.offset) { _, note in
+ VStack(alignment: .leading, spacing: Theme.lineGap) {
+ Text(note.date.formatted(date: .abbreviated, time: .shortened))
+ .eyebrow()
+ Text(note.text)
+ .font(Theme.serif(.body))
+ }
+ .settingsRow()
+ }
+ default:
+ TallyBars(tallies: summary.tallies, summary: summary)
+ .settingsRow()
+ }
+ }
+}
+
+/// A figure under a small spaced-capitals label.
+private struct Stat: View {
+ let title: LocalizedStringKey
+ let value: Double
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: Theme.lineGap) {
+ Text(title)
+ .eyebrow()
+ Text(value.formatted(.number.precision(.fractionLength(0...1))))
+ .font(Theme.serif(.title, weight: .medium))
+ .monospacedDigit()
+ }
+ .accessibilityElement(children: .combine)
+ }
+}
diff --git a/Reportage/Views/RootView.swift b/Reportage/Views/RootView.swift
@@ -1,7 +1,6 @@
import SwiftUI
-/// The app's tabs: the timeline and Settings. Visualisations join them in
-/// the Visualisations phase.
+/// The app's tabs: the timeline, charts and Settings.
struct RootView: View {
@Environment(PromptInbox.self) private var inbox: PromptInbox?
@State private var tab = RootTab.timeline
@@ -12,6 +11,9 @@ struct RootView: View {
Tab("Timeline", systemImage: "calendar", value: RootTab.timeline) {
HomeView()
}
+ Tab("Charts", systemImage: "chart.bar", value: RootTab.charts) {
+ ChartsView()
+ }
Tab("Settings", systemImage: "gearshape", value: RootTab.settings) {
SettingsView()
}
@@ -29,5 +31,6 @@ struct RootView: View {
enum RootTab: Hashable {
case timeline
+ case charts
case settings
}
diff --git a/Tests/Unit/AnswerSummaryTests.swift b/Tests/Unit/AnswerSummaryTests.swift
@@ -0,0 +1,122 @@
+import Foundation
+import Testing
+
+@testable import Reportage
+
+@Suite("AnswerSummary")
+struct AnswerSummaryTests {
+
+ private static func question(
+ _ id: String, _ kind: QuestionKind, order: Int, options: [String] = [], archived: Bool = false
+ ) -> Question {
+ Question(
+ id: id, prompt: "Prompt \(id)?", kind: kind, options: options, askOn: .random, order: order,
+ archivedAt: archived ? Date(timeIntervalSince1970: 0) : nil, modifiedAt: Date(timeIntervalSince1970: 0))
+ }
+
+ private static func row(_ questionID: String, _ value: ResponseValue, hour: Int = 0) -> AnswerRecord {
+ AnswerRecord(questionID: questionID, date: Date(timeIntervalSince1970: TimeInterval(hour) * 3600), value: value)
+ }
+
+ private static let lookup = SummaryLookup(
+ tokenTexts: ["lee": "Sam Lee", "sammy": "Sam Lee", "kai": "Kai", "home": "Home", "cafe": "Café"],
+ mergedIDs: ["sammy": "lee"])
+
+ @Test("Questions answered are summarised in survey order, archived last, and unanswered ones left out")
+ func order() {
+ let questions = [
+ Self.question("old", .number, order: 0, archived: true),
+ Self.question("people", .people, order: 2),
+ Self.question("working", .yesNo, order: 1),
+ Self.question("unanswered", .note, order: 3),
+ ].sorted { $0.order < $1.order }
+ let rows = [
+ Self.row("people", .tokens(["kai"])), Self.row("working", .options(["Yes"])),
+ Self.row("old", .number(2)),
+ ]
+ let summaries = AnswerSummary.summarise(rows, questions: questions, lookup: Self.lookup)
+ #expect(summaries.map(\.id) == ["working", "people", "old"])
+ }
+
+ @Test("Tokens count once per answer after merges, most used first")
+ func tokens() throws {
+ let rows = [
+ Self.row("people", .tokens(["lee", "sammy"])),
+ Self.row("people", .tokens(["kai"])),
+ Self.row("people", .tokens(["sammy", "kai"])),
+ Self.row("people", .tokens(["lee"])),
+ Self.row("place", .place(PlaceAnswer(tokenID: "cafe"))),
+ Self.row("place", .place(PlaceAnswer(tokenID: "home"))),
+ ]
+ let questions = [Self.question("people", .people, order: 0), Self.question("place", .location, order: 1)]
+ let summaries = AnswerSummary.summarise(rows, questions: questions, lookup: Self.lookup)
+ let people = try #require(summaries.first)
+ #expect(people.answered == 4)
+ #expect(people.tallies == [Tally(id: "lee", label: "Sam Lee", count: 3), Tally(id: "kai", label: "Kai", count: 2)])
+ #expect(people.share(of: people.tallies[0]) == 0.75)
+ // A tie is broken by name.
+ #expect(summaries[1].tallies.map(\.label) == ["Café", "Home"])
+ }
+
+ @Test("Yes/no and choice answers keep the question's order, with others after")
+ func options() throws {
+ let rows = [
+ Self.row("working", .options(["No"])), Self.row("working", .options(["No"])),
+ Self.row("working", .options(["Yes"])),
+ Self.row("mood", .options(["Okay"])), Self.row("mood", .options(["Retired"])),
+ Self.row("mood", .options(["Great", "Great"])),
+ ]
+ let questions = [
+ Self.question("working", .yesNo, order: 0),
+ Self.question("mood", .choice, order: 1, options: ["Great", "Okay", "Poor"]),
+ ]
+ let summaries = AnswerSummary.summarise(rows, questions: questions, lookup: Self.lookup)
+ #expect(summaries[0].tallies.map(\.id) == ["Yes", "No"])
+ #expect(summaries[0].tallies.map(\.count) == [1, 2])
+ #expect(summaries[1].tallies.map(\.label) == ["Great", "Okay", "Retired"])
+ #expect(summaries[1].tallies.map(\.count) == [1, 1, 1])
+ }
+
+ @Test("Numbers are averaged, and notes listed newest first without blank ones")
+ func numbersAndNotes() throws {
+ let rows = [
+ Self.row("coffee", .number(1)), Self.row("coffee", .number(2)), Self.row("coffee", .number(4.5)),
+ Self.row("note", .text("First"), hour: 1), Self.row("note", .text(" "), hour: 2),
+ Self.row("note", .text(" Second "), hour: 3),
+ ]
+ let questions = [Self.question("coffee", .number, order: 0), Self.question("note", .note, order: 1)]
+ let summaries = AnswerSummary.summarise(rows, questions: questions, lookup: Self.lookup)
+ #expect(summaries[0].numbers == NumberSummary(mean: 2.5, lowest: 1, highest: 4.5))
+ #expect(summaries[1].notes.map(\.text) == ["Second", "First"])
+ }
+
+ @Test("Periods end now and reach back a week, a month or a year")
+ func periods() {
+ var calendar = Calendar(identifier: .gregorian)
+ calendar.timeZone = .gmt
+ let now = Date(timeIntervalSince1970: 1_000_000_000)
+ #expect(ChartPeriod.week.start(endingAt: now, calendar: calendar) == now.addingTimeInterval(-7 * 86400))
+ #expect(ChartPeriod.all.start(endingAt: now, calendar: calendar) == nil)
+ let year = calendar.date(byAdding: .year, value: -1, to: now)
+ #expect(ChartPeriod.year.start(endingAt: now, calendar: calendar) == year)
+ }
+
+ @Test("The store's answers leave out skipped questions and reports before the period")
+ func storeAnswers() async throws {
+ let store = ReportStore(persistence: makeTestPersistence())
+ func report(_ hour: Int, _ value: ResponseValue?) -> Report {
+ Report(
+ id: UUID(), date: Date(timeIntervalSince1970: TimeInterval(hour) * 3600), timeZone: "Asia/Tokyo",
+ kind: .manual, trigger: .app, state: .complete,
+ responses: [Response(questionID: "Q", prompt: "P", value: value)],
+ modifiedAt: Date(timeIntervalSince1970: 0))
+ }
+ try await store.insert(report(1, .number(1)))
+ try await store.insert(report(5, .number(5)))
+ try await store.insert(report(6, nil))
+ let all = try await store.answers(since: nil)
+ #expect(all.count == 2)
+ let recent = try await store.answers(since: Date(timeIntervalSince1970: 2 * 3600))
+ #expect(recent.map(\.value) == [.number(5)])
+ }
+}