commit 95fbb3fe5b47d1b73144ce864bbd6284789a10f0
parent f3130594d74d3b0a9cee945a8f449264fdfc824d
Author: Michael Camilleri <[email protected]>
Date: Wed, 21 Oct 2026 00:31:42 +0900
Chart answers, steps and temperature over time
This commit adds trends to the Charts tab, its second step. A question's
detail screen now charts it over the period. Token and choice questions
chart one answer at a time, starting with the most given, and choosing
another in the list beneath switches the chart to it, so the chart needs
only the one colour.
A new Context section follows the questions, with Steps and Temperature
cards that open their own trends. A day's steps are the highest count
among its reports, since each is the count so far that day, taken in the
report's own time zone. Temperature charts each span's range with its
average marked, in the units the locale uses for weather.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 18 | +++++++++++++++++- |
| M | Reportage.xcodeproj/project.pbxproj | | | 12 | ++++++++++++ |
| M | Reportage/Services/Charts/AnswerSummary.swift | | | 95 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------- |
| A | Reportage/Services/Charts/ContextSummary.swift | | | 143 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/Charts/ChartsView.swift | | | 72 | +++++++++++++++++++++++++++++++++++++++++++++++++----------------------- |
| A | Reportage/Views/Charts/ContextCharts.swift | | | 170 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/Charts/QuestionChartView.swift | | | 81 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------- |
| A | Reportage/Views/Charts/TrendChart.swift | | | 149 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Tests/Unit/AnswerSummaryTests.swift | | | 58 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
9 files changed, 750 insertions(+), 48 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -969,7 +969,23 @@ 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. +better than an axis. Charts over time use Swift Charts. + +**Trends.** A question's detail screen charts it over the period: the share +answering yes, the average number, or how often one answer came up. Token +and choice questions chart one answer at a time, the most given to begin +with, and choosing another in the list below switches to it, so the chart +needs only one colour. Notes have no trend. Spans follow the period: days +for the past week or month, weeks for the past year, and months for all +time. Touching a chart shows a span's value. + +**Context.** After the questions, a Context section has Steps and +Temperature, each opening its trend. A day's steps are the highest count +among its reports, since each is the count so far that day, in the day of +the report's own time zone; spans longer than a day average their days. A +day without a report late in it undercounts, which the chart notes. +Temperature charts each span's range with its average marked, in the units +the locale uses for weather. Sleep isn't charted. ## Phases
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -13,6 +13,7 @@
06BD386D5CA144F8D5053A39 /* NotificationsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F832E0B277D5BF5BC3B6E5D1 /* NotificationsView.swift */; };
0F052B8A2C73437F57E927E7 /* ReportStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E55C093BA98D8700F406AE /* ReportStoreTests.swift */; };
123470F9E3205890526D3A89 /* EventLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFF717BC324925C231BD3378 /* EventLog.swift */; };
+ 141F97BD7B695424E7ED30D6 /* ContextCharts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 996F5818A958E305371F4BE3 /* ContextCharts.swift */; };
16CDDFE25EBB07C0EA9AC5AA /* DiagnosticsSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87545A7909A370C668314DFF /* DiagnosticsSection.swift */; };
16D2FB106A2C588BAAB3EB06 /* PromptSchedulerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2425CB4D9B12D422467F6FD7 /* PromptSchedulerTests.swift */; };
19FD732027A16A84552DFD0E /* HealthContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86069F79CD8FA24FC6C26650 /* HealthContext.swift */; };
@@ -68,6 +69,7 @@
9FD499B8FACD1BA034804590 /* QuestionListTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E6B536B922A8468136815CD /* QuestionListTests.swift */; };
9FEE3B78B770C6A3CF9C6610 /* QuestionsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F9A0A87A54F3E96E079F52D /* QuestionsView.swift */; };
A1FBFB9809DD3FF52BD7E5A7 /* DataSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */; };
+ A55E7B5E76EEF0C5F707D642 /* TrendChart.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD07F17AED0FDCF7B7D4C44B /* TrendChart.swift */; };
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 */; };
@@ -75,6 +77,7 @@
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 */; };
+ B5642835F1FD86CA4AE39408 /* ContextSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0950575E9B01E6885B1BDA09 /* ContextSummary.swift */; };
BD1AA0F75635BF9C68DFA12A /* NarrativeRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = E67FAC24A684AA62ED63441A /* NarrativeRule.swift */; };
BD8D81CBF8C3DE544BB7540C /* DefaultQuestions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94DB0CA378AEF82B3CB27B67 /* DefaultQuestions.swift */; };
BDEB83CDBA9E0B4DB7712491 /* LogPassiveReportIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90F9BD4EA70DCB46924CF9B8 /* LogPassiveReportIntent.swift */; };
@@ -140,6 +143,7 @@
/* Begin PBXFileReference section */
0734316A58943D5F2E26F718 /* ReportSummaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportSummaryTests.swift; sourceTree = "<group>"; };
+ 0950575E9B01E6885B1BDA09 /* ContextSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContextSummary.swift; sourceTree = "<group>"; };
0A246867F8FAC9D3FFABD61D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
0B35602A218BE4EE399835FD /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
0E6B536B922A8468136815CD /* QuestionListTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionListTests.swift; sourceTree = "<group>"; };
@@ -203,6 +207,7 @@
92BFA1E8F26662DCF828DD5C /* WelcomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WelcomeView.swift; sourceTree = "<group>"; };
94DB0CA378AEF82B3CB27B67 /* DefaultQuestions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefaultQuestions.swift; sourceTree = "<group>"; };
9856D1F8123B9CAD7D39071D /* PlaceAnswerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlaceAnswerView.swift; sourceTree = "<group>"; };
+ 996F5818A958E305371F4BE3 /* ContextCharts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContextCharts.swift; sourceTree = "<group>"; };
9F3237323A968FA629020DA9 /* ContextCapture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContextCapture.swift; sourceTree = "<group>"; };
A00E589A8387E7A1E348503C /* InlineCasing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InlineCasing.swift; sourceTree = "<group>"; };
A20C574BC234EDBD4056E2B7 /* TestHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestHelpers.swift; sourceTree = "<group>"; };
@@ -226,6 +231,7 @@
C3C7B68925A281EF806BB9B8 /* Theme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Theme.swift; sourceTree = "<group>"; };
CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DataSection.swift; sourceTree = "<group>"; };
CC1C5F0F722477CDA949F018 /* ReporterArchive.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterArchive.swift; sourceTree = "<group>"; };
+ CD07F17AED0FDCF7B7D4C44B /* TrendChart.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrendChart.swift; sourceTree = "<group>"; };
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>"; };
@@ -318,7 +324,9 @@
isa = PBXGroup;
children = (
D72771A17EAB0F8025CECB32 /* ChartsView.swift */,
+ 996F5818A958E305371F4BE3 /* ContextCharts.swift */,
F0A128C9CAF584114977A8D1 /* QuestionChartView.swift */,
+ CD07F17AED0FDCF7B7D4C44B /* TrendChart.swift */,
);
path = Charts;
sourceTree = "<group>";
@@ -402,6 +410,7 @@
isa = PBXGroup;
children = (
1ECAE94ED631259AB60F2DAE /* AnswerSummary.swift */,
+ 0950575E9B01E6885B1BDA09 /* ContextSummary.swift */,
);
path = Charts;
sourceTree = "<group>";
@@ -745,6 +754,8 @@
3BDDC4FD8CE13B29BCDE3ADC /* ChartsView.swift in Sources */,
DF632654B427EE32C44C6F78 /* Context.swift in Sources */,
D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */,
+ 141F97BD7B695424E7ED30D6 /* ContextCharts.swift in Sources */,
+ B5642835F1FD86CA4AE39408 /* ContextSummary.swift in Sources */,
A1FBFB9809DD3FF52BD7E5A7 /* DataSection.swift in Sources */,
BD8D81CBF8C3DE544BB7540C /* DefaultQuestions.swift in Sources */,
16CDDFE25EBB07C0EA9AC5AA /* DiagnosticsSection.swift in Sources */,
@@ -805,6 +816,7 @@
013407A07B79F11D51E23BD1 /* Theme.swift in Sources */,
25BC9F95DC40E31B1E4C6FBA /* Token.swift in Sources */,
D9A8839569734F5CEAC43A44 /* TokenAnswer.swift in Sources */,
+ A55E7B5E76EEF0C5F707D642 /* TrendChart.swift in Sources */,
540CA20A213B0446B6F71885 /* Vocabulary.swift in Sources */,
23A8E093AFF85144AEACF321 /* VocabularyView.swift in Sources */,
E2D35546E39153308E9880B1 /* WelcomeView.swift in Sources */,
diff --git a/Reportage/Services/Charts/AnswerSummary.swift b/Reportage/Services/Charts/AnswerSummary.swift
@@ -26,6 +26,35 @@ enum ChartPeriod: String, CaseIterable, Sendable {
case .all: nil
}
}
+
+ /// The span each point of a trend covers: days for a week or a month,
+ /// weeks for a year, and months for all time.
+ var bucket: Calendar.Component {
+ switch self {
+ case .week, .month: .day
+ case .year: .weekOfYear
+ case .all: .month
+ }
+ }
+}
+
+extension Calendar {
+ /// The start of the `component` that `date` falls in.
+ func start(of component: Calendar.Component, for date: Date) -> Date {
+ dateInterval(of: component, for: date)?.start ?? date
+ }
+}
+
+/// A value for one span of a trend, such as a day or a month, with its range
+/// where it has one.
+struct TrendPoint: Identifiable, Equatable, Sendable {
+ /// The start of the span.
+ var date: Date
+ var value: Double
+ var low: Double?
+ var high: Double?
+
+ var id: Date { date }
}
/// One answer to a question, with when its report was made.
@@ -62,6 +91,12 @@ struct QuestionSummary: Identifiable, Equatable, Sendable {
var numbers: NumberSummary?
/// For note questions: the notes, newest first.
var notes: [Note] = []
+ /// For yes/no questions, the share answering yes in each span; for
+ /// number questions, the average.
+ var trend: [TrendPoint] = []
+ /// For token and choice questions: how many reports gave each answer in
+ /// each span, by the tally's ID.
+ var tallyTrends: [String: [TrendPoint]] = [:]
var id: String { question.id }
@@ -81,33 +116,51 @@ enum AnswerSummary {
/// 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.
+ /// Trends are split into spans of `bucket` in `calendar`.
static func summarise(
- _ rows: [AnswerRecord], questions: [Question], lookup: SummaryLookup
+ _ rows: [AnswerRecord], questions: [Question], lookup: SummaryLookup,
+ bucket: Calendar.Component = .day, calendar: Calendar = .current
) -> [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)
+ return summary(of: question, rows: rows, lookup: lookup, bucket: bucket, calendar: calendar)
}
}
private static func summary(
- of question: Question, rows: [AnswerRecord], lookup: SummaryLookup
+ of question: Question, rows: [AnswerRecord], lookup: SummaryLookup,
+ bucket: Calendar.Component, calendar: Calendar
) -> QuestionSummary {
var summary = QuestionSummary(question: question, answered: rows.count)
var counts: [String: Int] = [:]
var numbers: [Double] = []
+ // By the start of each span: how many reports answered, and gave
+ // each answer, and the numbers given.
+ var answeredBySpan: [Date: Int] = [:]
+ var countsBySpan: [String: [Date: Int]] = [:]
+ var numbersBySpan: [Date: [Double]] = [:]
for row in rows {
+ let span = calendar.start(of: bucket, for: row.date)
+ answeredBySpan[span, default: 0] += 1
+ func count(_ ids: Set<String>) {
+ for id in ids {
+ counts[id, default: 0] += 1
+ countsBySpan[id, default: [:]][span, default: 0] += 1
+ }
+ }
switch row.value {
case .tokens(let ids):
- for id in Set(ids.map { lookup.mergedIDs[$0] ?? $0 }) { counts[id, default: 0] += 1 }
+ count(Set(ids.map { lookup.mergedIDs[$0] ?? $0 }))
case .place(let place):
- counts[lookup.mergedIDs[place.tokenID] ?? place.tokenID, default: 0] += 1
+ count([lookup.mergedIDs[place.tokenID] ?? place.tokenID])
case .options(let options):
- for option in Set(options) { counts[option, default: 0] += 1 }
+ count(Set(options))
case .number(let number):
- numbers.append(NSDecimalNumber(decimal: number).doubleValue)
+ let number = NSDecimalNumber(decimal: number).doubleValue
+ numbers.append(number)
+ numbersBySpan[span, default: []].append(number)
case .text(let text):
let text = text.trimmingCharacters(in: .whitespacesAndNewlines)
if !text.isEmpty { summary.notes.append(.init(date: row.date, text: text)) }
@@ -119,6 +172,26 @@ enum AnswerSummary {
}
summary.notes.sort { $0.date > $1.date }
+ switch question.kind {
+ case .yesNo:
+ let yes = countsBySpan[ResponseValue.yesOption] ?? [:]
+ summary.trend = answeredBySpan.map { span, answered in
+ TrendPoint(date: span, value: Double(yes[span] ?? 0) / Double(answered))
+ }
+ .sorted { $0.date < $1.date }
+ case .number:
+ summary.trend = numbersBySpan.map { span, numbers in
+ TrendPoint(
+ date: span, value: numbers.reduce(0, +) / Double(numbers.count),
+ low: numbers.min(), high: numbers.max())
+ }
+ .sorted { $0.date < $1.date }
+ default:
+ summary.tallyTrends = countsBySpan.mapValues { counts in
+ counts.map { TrendPoint(date: $0.key, value: Double($0.value)) }.sorted { $0.date < $1.date }
+ }
+ }
+
switch question.kind {
case .yesNo, .choice:
let fixed = question.kind == .yesNo ? [ResponseValue.yesOption, ResponseValue.noOption] : question.options
@@ -175,12 +248,4 @@ extension ReportStore {
}
}
}
-
- /// 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/Services/Charts/ContextSummary.swift b/Reportage/Services/Charts/ContextSummary.swift
@@ -0,0 +1,143 @@
+import CoreData
+import Foundation
+
+/// The context of one report the charts use.
+struct ContextRecord: Sendable {
+ var date: Date
+ var timeZone: TimeZone
+ /// Steps so far that day, from Health or else the motion sensors.
+ var steps: Int?
+ /// °C.
+ var temperature: Double?
+}
+
+/// Steps a day over a period.
+struct StepsSummary: Equatable, Sendable {
+ /// The average of each day's steps.
+ var mean: Double
+ /// How many days had a count.
+ var days: Int
+ /// Each span's average daily steps.
+ var trend: [TrendPoint]
+}
+
+/// The temperatures reports captured over a period, in °C.
+struct TemperatureSummary: Equatable, Sendable {
+ var mean: Double
+ var lowest: Double
+ var highest: Double
+ /// How many reports captured one.
+ var reports: Int
+ /// Each span's average, with its lowest and highest.
+ var trend: [TrendPoint]
+}
+
+struct ContextSummary: Equatable, Sendable {
+ var steps: StepsSummary?
+ var temperature: TemperatureSummary?
+
+ var isEmpty: Bool { steps == nil && temperature == nil }
+
+ /// Trends are split into spans of `bucket` in `calendar`. A day's steps
+ /// are the highest count its reports captured, since each is the count
+ /// so far that day, and its day is the one in the report's time zone.
+ static func summarise(
+ _ records: [ContextRecord], bucket: Calendar.Component = .day, calendar: Calendar = .current
+ ) -> ContextSummary {
+ var summary = ContextSummary()
+
+ var daily: [Date: Int] = [:]
+ for record in records {
+ guard let steps = record.steps, steps > 0 else { continue }
+ var zoned = calendar
+ zoned.timeZone = record.timeZone
+ // The report's day, as that day in `calendar`.
+ let components = zoned.dateComponents([.year, .month, .day], from: record.date)
+ guard let day = calendar.date(from: components) else { continue }
+ daily[day] = max(daily[day] ?? 0, steps)
+ }
+ if !daily.isEmpty {
+ let bySpan = Dictionary(grouping: daily, by: { calendar.start(of: bucket, for: $0.key) })
+ summary.steps = StepsSummary(
+ mean: Double(daily.values.reduce(0, +)) / Double(daily.count),
+ days: daily.count,
+ trend: bySpan.map { span, days in
+ TrendPoint(date: span, value: Double(days.map(\.value).reduce(0, +)) / Double(days.count))
+ }
+ .sorted { $0.date < $1.date })
+ }
+
+ let temperatures = records.compactMap { record in record.temperature.map { (record.date, $0) } }
+ if let lowest = temperatures.map(\.1).min(), let highest = temperatures.map(\.1).max() {
+ let bySpan = Dictionary(grouping: temperatures, by: { calendar.start(of: bucket, for: $0.0) })
+ summary.temperature = TemperatureSummary(
+ mean: temperatures.map(\.1).reduce(0, +) / Double(temperatures.count),
+ lowest: lowest, highest: highest, reports: temperatures.count,
+ trend: bySpan.map { span, values in
+ let values = values.map(\.1)
+ return TrendPoint(
+ date: span, value: values.reduce(0, +) / Double(values.count),
+ low: values.min(), high: values.max())
+ }
+ .sorted { $0.date < $1.date })
+ }
+ return summary
+ }
+}
+
+/// Everything the Charts tab shows for a period.
+struct ChartData: Equatable, Sendable {
+ var period: ChartPeriod
+ var summaries: [QuestionSummary] = []
+ var context = ContextSummary()
+ /// The span trends cover: from the start of the period, or of the
+ /// earliest report for all time, to now.
+ var domain: ClosedRange<Date>?
+}
+
+extension ReportStore {
+ /// The context of every report made since `start`, or ever when it's
+ /// `nil`.
+ func contexts(since start: Date?) async throws -> [ContextRecord] {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ let request = ReportEntity.fetchRequest()
+ if let start {
+ request.predicate = NSPredicate(format: "date >= %@", start as NSDate)
+ }
+ request.relationshipKeyPathsForPrefetching = ["health"]
+ return try context.fetch(request).compactMap { entity in
+ guard let date = entity.date else { return nil }
+ let captured = try entity.context.map { try ModelCoding.decode(Context.self, from: $0) }
+ let health = try entity.health?.record().health
+ return ContextRecord(
+ date: date,
+ timeZone: entity.timeZone.flatMap(TimeZone.init(identifier:)) ?? .current,
+ steps: health?.activity?.steps ?? captured?.motion?.steps,
+ temperature: captured?.weather?.temperature)
+ }
+ }
+ }
+
+ /// The question summaries and context trends for `period`. See
+ /// `AnswerSummary` and `ContextSummary`.
+ func chartData(for period: ChartPeriod, now: Date = Date(), calendar: Calendar = .current) async throws
+ -> ChartData
+ {
+ let start = period.start(endingAt: now, calendar: calendar)
+ async let lookup = summaryLookup()
+ async let questions = allQuestions()
+ async let rows = answers(since: start)
+ async let records = contexts(since: start)
+ let (answerRows, contextRecords) = try await (rows, records)
+
+ var data = ChartData(period: period)
+ data.summaries = try await AnswerSummary.summarise(
+ answerRows, questions: questions, lookup: lookup, bucket: period.bucket, calendar: calendar)
+ data.context = ContextSummary.summarise(contextRecords, bucket: period.bucket, calendar: calendar)
+ if let first = start ?? contextRecords.map(\.date).min(), first <= now {
+ data.domain = calendar.start(of: period.bucket, for: first)...now
+ }
+ return data
+ }
+}
diff --git a/Reportage/Views/Charts/ChartsView.swift b/Reportage/Views/Charts/ChartsView.swift
@@ -1,23 +1,31 @@
import OSLog
import SwiftUI
-/// The summaries the Charts tab shows, reloaded when the period changes or
-/// the tab is shown again.
+/// What 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 data = ChartData(period: .month)
private(set) var isLoaded = false
+ /// The period last asked for, so a slower load for an earlier one
+ /// doesn't replace it.
+ private var requested: ChartPeriod?
private let logger = Logger(subsystem: "net.inqk.reportage", category: "Charts")
+ var summaries: [QuestionSummary] { data.summaries }
+
func load(_ period: ChartPeriod, from store: ReportStore?) async {
guard let store else { return }
+ requested = period
do {
- summaries = try await store.questionSummaries(for: period)
+ let data = try await store.chartData(for: period)
+ guard requested == period else { return }
+ self.data = data
isLoaded = true
} catch {
- logger.error("Couldn't summarise answers: \(error)")
+ logger.error("Couldn't summarise reports: \(error)")
}
}
@@ -39,7 +47,7 @@ struct ChartsView: View {
ChartsTitle(period: $period)
ForEach(model.summaries) { summary in
NavigationLink {
- QuestionChartView(id: summary.id, period: period, model: model)
+ QuestionChartView(id: summary.id, model: model)
} label: {
SummaryCard(summary: summary)
}
@@ -48,6 +56,13 @@ struct ChartsView: View {
if model.isLoaded, model.summaries.isEmpty {
SettingsNote { Text("No questions were answered in this period.") }
}
+ if !model.data.context.isEmpty {
+ Section {
+ ContextCards(model: model)
+ } header: {
+ SettingsHeading("Context")
+ }
+ }
}
.listStyle(.plain)
.scrollContentBackground(.hidden)
@@ -146,32 +161,43 @@ private struct SummaryCard: View {
}
/// Each answer's name and count over a bar in proportion to the most given.
+/// With a selection, each answer can be chosen, and the others' bars fade.
struct TallyBars: View {
let tallies: [Tally]
let summary: QuestionSummary
+ var selection: Binding<String?>?
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))))"
- ))
+ let isChosen = selection.map { $0.wrappedValue == tally.id } ?? true
+ row(for: tally, most: most, isChosen: isChosen)
+ .contentShape(Rectangle())
+ .onTapGesture { selection?.wrappedValue = tally.id }
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(Text(tally.label))
+ .accessibilityValue(
+ Text(
+ "^[\(tally.count) report](inflect: true), \(summary.share(of: tally).formatted(.percent.precision(.fractionLength(0))))"
+ ))
+ .accessibilityAddTraits(selection == nil ? [] : isChosen ? [.isButton, .isSelected] : .isButton)
+ }
+ }
+ }
+
+ private func row(for tally: Tally, most: Int, isChosen: Bool) -> some View {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(alignment: .firstTextBaseline) {
+ Text(tally.label)
+ .font(Theme.serif(.body, weight: selection != nil && isChosen ? .semibold : .regular))
+ Spacer()
+ Text(tally.count.formatted())
+ .font(.footnote.monospacedDigit())
+ .foregroundStyle(Theme.muted)
}
+ Bar(fraction: Double(tally.count) / Double(most))
+ .opacity(isChosen ? 1 : 0.35)
}
}
}
diff --git a/Reportage/Views/Charts/ContextCharts.swift b/Reportage/Views/Charts/ContextCharts.swift
@@ -0,0 +1,170 @@
+import SwiftUI
+
+/// The context charts: steps and temperature.
+enum ContextChart: Hashable {
+ case steps
+ case temperature
+}
+
+/// A card for each kind of context captured in the period, each opening
+/// its trend.
+struct ContextCards: View {
+ let model: ChartsModel
+
+ var body: some View {
+ if let steps = model.data.context.steps {
+ NavigationLink {
+ ContextChartView(chart: .steps, model: model)
+ } label: {
+ ContextCard(title: "Steps", footnote: Text("^[\(steps.days) day](inflect: true)")) {
+ Text("\(steps.mean.formatted(.number.precision(.fractionLength(0)))) a day on average")
+ }
+ }
+ .settingsRow()
+ }
+ if let temperature = model.data.context.temperature {
+ NavigationLink {
+ ContextChartView(chart: .temperature, model: model)
+ } label: {
+ ContextCard(
+ title: "Temperature", footnote: Text("^[\(temperature.reports) report](inflect: true)")
+ ) {
+ Text(
+ "Average \(Degrees.format(temperature.mean)) · \(Degrees.format(temperature.lowest)) to \(Degrees.format(temperature.highest))"
+ )
+ }
+ }
+ .settingsRow()
+ }
+ }
+}
+
+/// A context card's title, its gist and a footnote, set like a question's.
+private struct ContextCard<Gist: View>: View {
+ let title: LocalizedStringKey
+ let footnote: Text
+ @ViewBuilder let gist: Gist
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: Theme.itemGap) {
+ Text(title)
+ .font(Theme.serif(.body, weight: .medium))
+ gist
+ .font(Theme.serif(.body))
+ footnote
+ .font(.footnote)
+ .foregroundStyle(Theme.muted)
+ }
+ .padding(.vertical, 4)
+ }
+}
+
+/// Steps or temperature over the period, with its figures.
+struct ContextChartView: View {
+ let chart: ContextChart
+ let model: ChartsModel
+
+ var body: some View {
+ List {
+ Section {
+ VStack(alignment: .leading, spacing: Theme.lineGap) {
+ Text(chart == .steps ? "Steps" : "Temperature")
+ .font(Theme.serif(.title3, weight: .medium))
+ subtitle
+ .font(.footnote)
+ .foregroundStyle(Theme.muted)
+ }
+ .settingsRow()
+ .listRowSeparator(.hidden)
+ }
+ switch chart {
+ case .steps:
+ if let steps = model.data.context.steps {
+ Section {
+ TrendChart(
+ points: steps.trend, bucket: model.data.period.bucket, domain: model.data.domain,
+ format: { $0.formatted(.number.notation(.compactName).precision(.significantDigits(1...3))) }
+ )
+ .settingsRow()
+ .listRowSeparator(.hidden)
+ SettingsNote {
+ Text(
+ "Each day's steps are the most counted by its reports, so a day without a report late in it may show fewer than were taken."
+ )
+ }
+ } header: {
+ SettingsHeading(model.data.period.bucket == .day ? "Each Day" : "Average a Day")
+ }
+ }
+ case .temperature:
+ if let temperature = model.data.context.temperature {
+ Section {
+ TrendChart(
+ points: temperature.trend.map(Degrees.converted), bucket: model.data.period.bucket,
+ domain: model.data.domain, showsRange: true,
+ format: { Degrees.formatConverted($0) }
+ )
+ .settingsRow()
+ .listRowSeparator(.hidden)
+ SettingsNote { Text("The range of temperatures reports captured, with the average marked.") }
+ } header: {
+ SettingsHeading("Range and Average")
+ }
+ Section {
+ Grid(alignment: .leading, horizontalSpacing: Theme.blockGap, verticalSpacing: Theme.itemGap) {
+ GridRow {
+ Stat(title: "Average", value: Degrees.format(temperature.mean))
+ Stat(title: "Lowest", value: Degrees.format(temperature.lowest))
+ Stat(title: "Highest", value: Degrees.format(temperature.highest))
+ }
+ }
+ .settingsRow()
+ }
+ }
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .background(Theme.paper)
+ .foregroundStyle(Theme.ink)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ private var subtitle: Text {
+ let period = model.data.period.title
+ switch chart {
+ case .steps:
+ let days = model.data.context.steps?.days ?? 0
+ return Text("\(period) · ^[\(days) day](inflect: true)")
+ case .temperature:
+ let reports = model.data.context.temperature?.reports ?? 0
+ return Text("\(period) · ^[\(reports) report](inflect: true)")
+ }
+ }
+}
+
+/// Temperatures, which are stored in °C, in the units the locale uses for
+/// weather.
+enum Degrees {
+ private static var unit: UnitTemperature { UnitTemperature(forLocale: .current, usage: .weather) }
+
+ /// `celsius` in the locale's units.
+ static func convert(_ celsius: Double) -> Double {
+ Measurement(value: celsius, unit: UnitTemperature.celsius).converted(to: unit).value
+ }
+
+ static func converted(_ point: TrendPoint) -> TrendPoint {
+ TrendPoint(
+ date: point.date, value: convert(point.value), low: point.low.map(convert), high: point.high.map(convert))
+ }
+
+ /// `celsius` in the locale's units, such as '18°'.
+ static func format(_ celsius: Double) -> String {
+ formatConverted(convert(celsius))
+ }
+
+ /// A temperature already in the locale's units.
+ static func formatConverted(_ value: Double) -> String {
+ "\(value.formatted(.number.precision(.fractionLength(0))))°"
+ }
+}
diff --git a/Reportage/Views/Charts/QuestionChartView.swift b/Reportage/Views/Charts/QuestionChartView.swift
@@ -1,11 +1,13 @@
import SwiftUI
-/// One question's answers over the period in full: every answer given, the
-/// spread of a number, or the notes written.
+/// One question's answers over the period in full: how they changed over
+/// it, every answer given, the spread of a number, or the notes written.
struct QuestionChartView: View {
let id: String
- let period: ChartPeriod
let model: ChartsModel
+ /// The answer whose trend is shown, for token and choice questions.
+ /// The most given when `nil`.
+ @State private var chosen: String?
var body: some View {
List {
@@ -14,15 +16,28 @@ struct QuestionChartView: View {
VStack(alignment: .leading, spacing: Theme.lineGap) {
Text(summary.question.prompt)
.font(Theme.serif(.title3, weight: .medium))
- Text("\(period.title) · ^[\(summary.answered) report](inflect: true)")
+ Text("\(model.data.period.title) · ^[\(summary.answered) report](inflect: true)")
.font(.footnote)
.foregroundStyle(Theme.muted)
}
.settingsRow()
.listRowSeparator(.hidden)
}
+ if let trend = trend(for: summary) {
+ Section {
+ trend
+ .settingsRow()
+ .listRowSeparator(.hidden)
+ } header: {
+ SettingsHeading(trendTitle(for: summary))
+ }
+ }
Section {
content(for: summary)
+ } header: {
+ if summary.question.kind != .note {
+ SettingsHeading("Answers")
+ }
}
} else {
SettingsNote { Text("This question wasn't answered in this period.") }
@@ -35,6 +50,41 @@ struct QuestionChartView: View {
.navigationBarTitleDisplayMode(.inline)
}
+ /// The tally whose trend is shown.
+ private func chosenTally(in summary: QuestionSummary) -> Tally? {
+ summary.tallies.first { $0.id == chosen } ?? summary.tallies.first
+ }
+
+ private func trend(for summary: QuestionSummary) -> TrendChart? {
+ let bucket = model.data.period.bucket
+ let domain = model.data.domain
+ switch summary.question.kind {
+ case .yesNo:
+ return TrendChart(
+ points: summary.trend, bucket: bucket, domain: domain, valueDomain: 0...1,
+ format: { $0.formatted(.percent.precision(.fractionLength(0))) })
+ case .number:
+ return TrendChart(
+ points: summary.trend, bucket: bucket, domain: domain,
+ format: { $0.formatted(.number.precision(.fractionLength(0...1))) })
+ case .note:
+ return nil
+ default:
+ guard let tally = chosenTally(in: summary) else { return nil }
+ return TrendChart(
+ points: summary.tallyTrends[tally.id] ?? [], bucket: bucket, domain: domain,
+ format: { $0.formatted(.number.precision(.fractionLength(0))) })
+ }
+ }
+
+ private func trendTitle(for summary: QuestionSummary) -> LocalizedStringKey {
+ switch summary.question.kind {
+ case .yesNo: "Share Answering Yes"
+ case .number: "Average"
+ default: "'\(chosenTally(in: summary)?.label ?? "")' Over Time"
+ }
+ }
+
@ViewBuilder private func content(for summary: QuestionSummary) -> some View {
switch summary.question.kind {
case .yesNo:
@@ -64,22 +114,35 @@ struct QuestionChartView: View {
.settingsRow()
}
default:
- TallyBars(tallies: summary.tallies, summary: summary)
- .settingsRow()
+ TallyBars(
+ tallies: summary.tallies, summary: summary,
+ selection: Binding(get: { chosenTally(in: summary)?.id }, set: { chosen = $0 })
+ )
+ .settingsRow()
+ SettingsNote { Text("Choose an answer to see it over time.") }
}
}
}
/// A figure under a small spaced-capitals label.
-private struct Stat: View {
+struct Stat: View {
let title: LocalizedStringKey
- let value: Double
+ let value: String
+
+ init(title: LocalizedStringKey, value: String) {
+ self.title = title
+ self.value = value
+ }
+
+ init(title: LocalizedStringKey, value: Double) {
+ self.init(title: title, value: value.formatted(.number.precision(.fractionLength(0...1))))
+ }
var body: some View {
VStack(alignment: .leading, spacing: Theme.lineGap) {
Text(title)
.eyebrow()
- Text(value.formatted(.number.precision(.fractionLength(0...1))))
+ Text(value)
.font(Theme.serif(.title, weight: .medium))
.monospacedDigit()
}
diff --git a/Reportage/Views/Charts/TrendChart.swift b/Reportage/Views/Charts/TrendChart.swift
@@ -0,0 +1,149 @@
+import Charts
+import SwiftUI
+
+/// A value over the period, one bar for each span, or for each span its
+/// range with its average marked. Touching the chart shows a span's value.
+struct TrendChart: View {
+ let points: [TrendPoint]
+ let bucket: Calendar.Component
+ /// The span the chart covers, so periods with gaps keep their width.
+ let domain: ClosedRange<Date>?
+ /// Whether each point is drawn as its range, from low to high.
+ var showsRange = false
+ /// The value axis, such as 0...1 for a share; automatic when `nil`.
+ var valueDomain: ClosedRange<Double>?
+ let format: (Double) -> String
+
+ @State private var selection: Date?
+ private let calendar = Calendar.current
+
+ var body: some View {
+ Chart {
+ ForEach(points) { point in
+ if showsRange, let low = point.low, let high = point.high {
+ BarMark(
+ x: .value("Date", point.date, unit: bucket),
+ yStart: .value("Lowest", low), yEnd: .value("Highest", high)
+ )
+ .foregroundStyle(Theme.accent.opacity(0.3))
+ .cornerRadius(4)
+ .accessibilityLabel(spanTitle(point.date))
+ .accessibilityValue(
+ "\(format(point.value)), \(format(low)) to \(format(high))")
+ PointMark(x: .value("Date", point.date, unit: bucket), y: .value("Average", point.value))
+ .foregroundStyle(Theme.accent)
+ .symbolSize(24)
+ .accessibilityHidden(true)
+ } else {
+ BarMark(x: .value("Date", point.date, unit: bucket), y: .value("Value", point.value))
+ .foregroundStyle(Theme.accent)
+ .cornerRadius(4)
+ .accessibilityLabel(spanTitle(point.date))
+ .accessibilityValue(format(point.value))
+ }
+ }
+ if let selected {
+ RuleMark(x: .value("Date", selected.date, unit: bucket))
+ .foregroundStyle(Theme.muted.opacity(0.5))
+ .lineStyle(StrokeStyle(lineWidth: 1))
+ .annotation(
+ position: .top, spacing: 4,
+ overflowResolution: .init(x: .fit(to: .chart), y: .disabled)
+ ) {
+ VStack(spacing: Theme.lineGap) {
+ Text(spanTitle(selected.date))
+ .font(.caption)
+ .foregroundStyle(Theme.muted)
+ Text(selectedValue(selected))
+ .font(.footnote.weight(.semibold).monospacedDigit())
+ .foregroundStyle(Theme.ink)
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 4)
+ .background(Theme.field, in: RoundedRectangle(cornerRadius: 6))
+ }
+ }
+ }
+ .chartXScale(domain: xDomain)
+ .chartYScale(domain: yDomain)
+ .chartXSelection(value: $selection)
+ .chartXAxis {
+ AxisMarks(values: .automatic(desiredCount: 4)) { _ in
+ AxisTick(stroke: StrokeStyle(lineWidth: 1))
+ .foregroundStyle(Theme.rule)
+ AxisValueLabel(format: axisFormat)
+ .foregroundStyle(Theme.muted)
+ }
+ }
+ .chartYAxis {
+ AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { value in
+ AxisGridLine(stroke: StrokeStyle(lineWidth: 1))
+ .foregroundStyle(Theme.rule)
+ AxisValueLabel {
+ if let number = value.as(Double.self) {
+ Text(format(number))
+ }
+ }
+ .foregroundStyle(Theme.muted)
+ }
+ }
+ .frame(height: 200)
+ .padding(.top, 36)
+ }
+
+ private var xDomain: ClosedRange<Date> {
+ if let domain {
+ let end = calendar.dateInterval(of: bucket, for: domain.upperBound)?.end ?? domain.upperBound
+ return calendar.start(of: bucket, for: domain.lowerBound)...end
+ }
+ let dates = points.map(\.date)
+ let start = dates.min() ?? Date()
+ let last = dates.max() ?? start
+ return start...(calendar.dateInterval(of: bucket, for: last)?.end ?? last)
+ }
+
+ private var yDomain: ClosedRange<Double> {
+ if let valueDomain { return valueDomain }
+ // A range sits within its values; bars stand on zero.
+ if showsRange {
+ let low = points.map { $0.low ?? $0.value }.min() ?? 0
+ let high = points.map { $0.high ?? $0.value }.max() ?? 1
+ let margin = max((high - low) * 0.1, 1)
+ return (low - margin)...(high + margin)
+ }
+ return 0...max((points.map(\.value).max() ?? 1) * 1.1, 1)
+ }
+
+ private var selected: TrendPoint? {
+ guard let selection else { return nil }
+ let span = calendar.start(of: bucket, for: selection)
+ return points.first { $0.date == span }
+ }
+
+ private func selectedValue(_ point: TrendPoint) -> String {
+ guard showsRange, let low = point.low, let high = point.high else { return format(point.value) }
+ return String(
+ localized: "\(format(point.value)) (\(format(low))–\(format(high)))",
+ comment: "A chart's average for a span, with its lowest and highest")
+ }
+
+ private var axisFormat: Date.FormatStyle {
+ switch bucket {
+ case .month: .dateTime.month(.abbreviated).year(.twoDigits)
+ default: .dateTime.day().month(.abbreviated)
+ }
+ }
+
+ /// The span starting at `date`: a day, the week starting then, or a
+ /// month.
+ private func spanTitle(_ date: Date) -> String {
+ switch bucket {
+ case .weekOfYear:
+ String(
+ localized: "Week of \(date.formatted(.dateTime.day().month(.abbreviated)))",
+ comment: "The week a chart's bar covers")
+ case .month: date.formatted(.dateTime.month(.wide).year())
+ default: date.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))
+ }
+ }
+}
diff --git a/Tests/Unit/AnswerSummaryTests.swift b/Tests/Unit/AnswerSummaryTests.swift
@@ -90,6 +90,58 @@ struct AnswerSummaryTests {
#expect(summaries[1].notes.map(\.text) == ["Second", "First"])
}
+ private static var gmt: Calendar {
+ var calendar = Calendar(identifier: .gregorian)
+ calendar.timeZone = .gmt
+ return calendar
+ }
+
+ @Test("Trends give each span's share answering yes, average number, and count of each answer")
+ func trends() throws {
+ let day = { (hour: Int) in Date(timeIntervalSince1970: TimeInterval(hour) * 3600) }
+ let rows = [
+ Self.row("working", .options(["Yes"]), hour: 1), Self.row("working", .options(["No"]), hour: 2),
+ Self.row("working", .options(["Yes"]), hour: 25),
+ Self.row("coffee", .number(1), hour: 1), Self.row("coffee", .number(3), hour: 2),
+ Self.row("people", .tokens(["lee", "sammy"]), hour: 1), Self.row("people", .tokens(["kai"]), hour: 26),
+ Self.row("people", .tokens(["sammy"]), hour: 27),
+ ]
+ let questions = [
+ Self.question("working", .yesNo, order: 0), Self.question("coffee", .number, order: 1),
+ Self.question("people", .people, order: 2),
+ ]
+ let summaries = AnswerSummary.summarise(
+ rows, questions: questions, lookup: Self.lookup, bucket: .day, calendar: Self.gmt)
+ #expect(summaries[0].trend == [TrendPoint(date: day(0), value: 0.5), TrendPoint(date: day(24), value: 1)])
+ #expect(summaries[1].trend == [TrendPoint(date: day(0), value: 2, low: 1, high: 3)])
+ #expect(summaries[2].tallyTrends["lee"] == [TrendPoint(date: day(0), value: 1), TrendPoint(date: day(24), value: 1)])
+ #expect(summaries[2].tallyTrends["kai"] == [TrendPoint(date: day(24), value: 1)])
+ #expect(summaries[2].tallyTrends["sammy"] == nil)
+ }
+
+ @Test("A day's steps are its highest count in its own zone, averaged over each span")
+ func steps() throws {
+ let tokyo = try #require(TimeZone(identifier: "Asia/Tokyo"))
+ // 2001-09-09 01:46:40 UTC is 10:46 in Tokyo; 16:00 UTC is 01:00 the next day there.
+ let base = Date(timeIntervalSince1970: 1_000_000_000)
+ let records = [
+ ContextRecord(date: base, timeZone: tokyo, steps: 1000),
+ ContextRecord(date: base.addingTimeInterval(3600), timeZone: tokyo, steps: 4000),
+ ContextRecord(date: base.addingTimeInterval(15 * 3600), timeZone: tokyo, steps: 100),
+ ContextRecord(date: base.addingTimeInterval(16 * 3600), timeZone: tokyo, steps: 0),
+ ContextRecord(date: base, timeZone: tokyo, temperature: 10),
+ ContextRecord(date: base.addingTimeInterval(3600), timeZone: tokyo, temperature: 20),
+ ]
+ let summary = ContextSummary.summarise(records, bucket: .month, calendar: Self.gmt)
+ let steps = try #require(summary.steps)
+ #expect(steps.days == 2)
+ #expect(steps.mean == 2050)
+ #expect(steps.trend.map(\.value) == [2050])
+ let temperature = try #require(summary.temperature)
+ #expect(temperature.mean == 15)
+ #expect(temperature.trend == [TrendPoint(date: Self.gmt.start(of: .month, for: base), value: 15, low: 10, high: 20)])
+ }
+
@Test("Periods end now and reach back a week, a month or a year")
func periods() {
var calendar = Calendar(identifier: .gregorian)
@@ -118,5 +170,11 @@ struct AnswerSummaryTests {
#expect(all.count == 2)
let recent = try await store.answers(since: Date(timeIntervalSince1970: 2 * 3600))
#expect(recent.map(\.value) == [.number(5)])
+
+ // All time starts at the earliest report's span.
+ let now = Date(timeIntervalSince1970: 10 * 3600)
+ let data = try await store.chartData(for: .all, now: now, calendar: Self.gmt)
+ #expect(data.domain == Date(timeIntervalSince1970: 0)...now)
+ #expect(data.summaries.isEmpty)
}
}