← All repositories

reportage

A life-logging app for iPhone

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


commit 07520aed55b8cae4874d2e91fbf386829b051789
parent 1b79bf25a6a007beb28e875bd88ad40955f3b170
Author: Michael Camilleri <[email protected]>
Date:   Wed, 21 Oct 2026 01:40:58 +0900

Map the places chosen on the Charts tab

This commit adds a Places card to the Context section of the Charts tab.
The card shows the period's places on a small map and the one chosen
most often, and opens a full map with a circle for each place given as a
location answer, sized by area to how many reports chose it. Tapping a
circle names the place and its count.

A place merged into another counts as the one it went into, and each is
shown at its own coordinate or else at the centre of where its answers
were given. Places with neither are counted in a footnote rather than
dropped silently. Report locations aren't plotted, since for all time
they would run to thousands of marks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Diffstat

MNotes/Design.md | 12++++++++++--
MReportage.xcodeproj/project.pbxproj | 4++++
MReportage/Services/Charts/ContextSummary.swift | 80++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
MReportage/Views/Charts/ContextCharts.swift | 25++++++++++++++++++++++---
AReportage/Views/Charts/PlacesMap.swift | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MTests/Unit/AnswerSummaryTests.swift | 30++++++++++++++++++++++++++++++
MTests/Unit/ReportStoreTests.swift | 2+-

7 files changed, 241 insertions(+), 13 deletions(-)

diff --git a/Notes/Design.md b/Notes/Design.md

@@ -979,8 +979,16 @@ 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
+**Context.** After the questions, a Context section has Places, Steps and
+Temperature. Places shows the period's places on a small map and opens a
+full one: a circle for each place given as a location answer, from any
+location question, sized by how many reports chose it (by area, so the
+square root of the count), and tapping one names it. A merged place counts
+as the one it went into. Each is shown at its own coordinate or else at
+the centre of where its answers were given; places with neither are
+counted and noted. Report locations aren't plotted: for all time they
+would run to thousands of marks. Steps and Temperature each open a
+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.

diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj

@@ -39,6 +39,7 @@
 		4A0DEFB7E69A9FC5EAAD99D4 /* RealExportVerificationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */; };
 		540CA20A213B0446B6F71885 /* Vocabulary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74FF461F6E8A0241C18357B2 /* Vocabulary.swift */; };
 		633A94E029055EA5D50D00AC /* PlaceRanking.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76FFC5FE874467974DD6BFA0 /* PlaceRanking.swift */; };
+		6727BF60A53A3A18FD37B51F /* PlacesMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF6B203386F36F63252BAA9B /* PlacesMap.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 */; };
@@ -218,6 +219,7 @@
 		A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventLogTests.swift; sourceTree = "<group>"; };
 		A9C326FBA3249ED86912FBF5 /* PromptNotification.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptNotification.swift; sourceTree = "<group>"; };
 		AE6C0A180E8285C11565723B /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
+		AF6B203386F36F63252BAA9B /* PlacesMap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlacesMap.swift; sourceTree = "<group>"; };
 		B007E6BACAA214C7332EF77C /* Question.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Question.swift; sourceTree = "<group>"; };
 		B03734F91822E7F161432075 /* Report.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Report.swift; sourceTree = "<group>"; };
 		B7998F9826B899741323C0C7 /* SurveyView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyView.swift; sourceTree = "<group>"; };
@@ -325,6 +327,7 @@
 			children = (
 				D72771A17EAB0F8025CECB32 /* ChartsView.swift */,
 				996F5818A958E305371F4BE3 /* ContextCharts.swift */,
+				AF6B203386F36F63252BAA9B /* PlacesMap.swift */,
 				F0A128C9CAF584114977A8D1 /* QuestionChartView.swift */,
 				CD07F17AED0FDCF7B7D4C44B /* TrendChart.swift */,
 			);
@@ -783,6 +786,7 @@
 				7A6543B7C48EC93D468EBBD8 /* PlacePhrase.swift in Sources */,
 				D74CE3807E9593D470DADAA8 /* PlacePicker.swift in Sources */,
 				633A94E029055EA5D50D00AC /* PlaceRanking.swift in Sources */,
+				6727BF60A53A3A18FD37B51F /* PlacesMap.swift in Sources */,
 				7488B9EE97D419E2B6B9FCEA /* PromptNotification.swift in Sources */,
 				7676E79864C7C26CB9EA4B10 /* PromptSchedule.swift in Sources */,
 				690A6B50550B9CE4B954CC0C /* PromptScheduler.swift in Sources */,

diff --git a/Reportage/Services/Charts/ContextSummary.swift b/Reportage/Services/Charts/ContextSummary.swift

@@ -32,11 +32,68 @@ struct TemperatureSummary: Equatable, Sendable {
     var trend: [TrendPoint]
 }
 
+/// A place given as a location answer, with how many reports chose it.
+struct MapPlace: Identifiable, Equatable, Sendable {
+    /// The token's ID, after merges.
+    var id: String
+    var name: String
+    var coordinate: Coordinate
+    var count: Int
+}
+
+/// The places location answers chose over a period.
+struct PlacesSummary: Equatable, Sendable {
+    /// Most chosen first.
+    var places: [MapPlace]
+    /// How many places chosen have no coordinate to show them at.
+    var unplaced: Int
+
+    /// The places chosen in `rows`, from any location question. A place
+    /// merged into another counts as that place. Each is shown at its own
+    /// coordinate, from `tokenCoordinates`, or else at the centre of where
+    /// its answers were given.
+    static func summarise(
+        _ rows: [AnswerRecord], lookup: SummaryLookup, tokenCoordinates: [String: Coordinate]
+    ) -> PlacesSummary? {
+        var counts: [String: Int] = [:]
+        var sums: [String: (latitude: Double, longitude: Double, count: Int)] = [:]
+        for row in rows {
+            guard case .place(let answer) = row.value else { continue }
+            let id = lookup.mergedIDs[answer.tokenID] ?? answer.tokenID
+            counts[id, default: 0] += 1
+            if let coordinate = answer.coordinate {
+                let sum = sums[id] ?? (0, 0, 0)
+                sums[id] = (sum.latitude + coordinate.latitude, sum.longitude + coordinate.longitude, sum.count + 1)
+            }
+        }
+        guard !counts.isEmpty else { return nil }
+        var places: [MapPlace] = []
+        var unplaced = 0
+        for (id, count) in counts {
+            let centre = sums[id].map {
+                Coordinate(latitude: $0.latitude / Double($0.count), longitude: $0.longitude / Double($0.count))
+            }
+            guard let name = lookup.tokenTexts[id], let coordinate = tokenCoordinates[id] ?? centre else {
+                unplaced += 1
+                continue
+            }
+            places.append(MapPlace(id: id, name: name, coordinate: coordinate, count: count))
+        }
+        places.sort { lhs, rhs in
+            lhs.count != rhs.count
+                ? lhs.count > rhs.count
+                : lhs.name.localizedStandardCompare(rhs.name) == .orderedAscending
+        }
+        return PlacesSummary(places: places, unplaced: unplaced)
+    }
+}
+
 struct ContextSummary: Equatable, Sendable {
     var steps: StepsSummary?
     var temperature: TemperatureSummary?
+    var places: PlacesSummary?
 
-    var isEmpty: Bool { steps == nil && temperature == nil }
+    var isEmpty: Bool { steps == nil && temperature == nil && places == 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
@@ -125,16 +182,25 @@ extension ReportStore {
         -> 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)
+        async let lookupResult = summaryLookup()
+        async let questionsResult = allQuestions()
+        async let rowsResult = answers(since: start)
+        async let recordsResult = contexts(since: start)
+        let (lookup, questions, answerRows, contextRecords) = try await (
+            lookupResult, questionsResult, rowsResult, recordsResult
+        )
 
         var data = ChartData(period: period)
-        data.summaries = try await AnswerSummary.summarise(
+        data.summaries = AnswerSummary.summarise(
             answerRows, questions: questions, lookup: lookup, bucket: period.bucket, calendar: calendar)
         data.context = ContextSummary.summarise(contextRecords, bucket: period.bucket, calendar: calendar)
+        let placeIDs = Set(
+            answerRows.compactMap { row -> String? in
+                guard case .place(let answer) = row.value else { return nil }
+                return lookup.mergedIDs[answer.tokenID] ?? answer.tokenID
+            })
+        let coordinates = try await tokenEntries(ids: Array(placeIDs)).compactMapValues(\.coordinate)
+        data.context.places = PlacesSummary.summarise(answerRows, lookup: lookup, tokenCoordinates: coordinates)
         if let first = start ?? contextRecords.map(\.date).min(), first <= now {
             data.domain = calendar.start(of: period.bucket, for: first)...now
         }

diff --git a/Reportage/Views/Charts/ContextCharts.swift b/Reportage/Views/Charts/ContextCharts.swift

@@ -1,17 +1,36 @@
 import SwiftUI
 
-/// The context charts: steps and temperature.
+/// The context charts with trends: 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.
+/// A card for each kind of context captured in the period: the places
+/// chosen, opening their map, and steps and temperature, opening their
+/// trends.
 struct ContextCards: View {
     let model: ChartsModel
 
     var body: some View {
+        if let places = model.data.context.places, let top = places.places.first {
+            NavigationLink {
+                PlacesMapView(model: model)
+            } label: {
+                ContextCard(title: "Places", footnote: Text("^[\(places.places.count) place](inflect: true)")) {
+                    VStack(alignment: .leading, spacing: Theme.itemGap) {
+                        PlacesMap(places: places.places, interactive: false)
+                            .frame(height: 160)
+                            .clipShape(.rect(cornerRadius: 6))
+                            .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(Theme.rule))
+                            .allowsHitTesting(false)
+                            .accessibilityHidden(true)
+                        Text("Most often \(top.name)")
+                    }
+                }
+            }
+            .settingsRow()
+        }
         if let steps = model.data.context.steps {
             NavigationLink {
                 ContextChartView(chart: .steps, model: model)

diff --git a/Reportage/Views/Charts/PlacesMap.swift b/Reportage/Views/Charts/PlacesMap.swift

@@ -0,0 +1,101 @@
+import MapKit
+import SwiftUI
+
+/// The places chosen in a period, each a circle sized by how many reports
+/// chose it, framed to show them all.
+struct PlacesMap: View {
+    let places: [MapPlace]
+    var interactive = true
+    var selection: Binding<String?>?
+
+    @State private var position = MapCameraPosition.automatic
+
+    var body: some View {
+        let most = places.map(\.count).max() ?? 1
+        Map(
+            position: $position,
+            interactionModes: interactive ? [.pan, .zoom] : [],
+            selection: selection ?? .constant(nil)
+        ) {
+            // Most chosen first, so smaller circles are drawn over larger ones.
+            ForEach(places) { place in
+                Annotation(place.name, coordinate: place.centre, anchor: .center) {
+                    PlaceMark(
+                        diameter: Self.diameter(of: place, most: most),
+                        isSelected: selection?.wrappedValue == place.id)
+                }
+                .annotationTitles(.hidden)
+                .tag(place.id)
+            }
+        }
+        .mapStyle(.standard(emphasis: .muted, pointsOfInterest: .excludingAll))
+        .onChange(of: places.map(\.id)) { position = .automatic }
+    }
+
+    /// Circles grow with the square root of the count, so their areas
+    /// compare as the counts do.
+    static func diameter(of place: MapPlace, most: Int) -> CGFloat {
+        10 + 26 * sqrt(CGFloat(place.count) / CGFloat(max(most, 1)))
+    }
+}
+
+/// A place's circle, ringed in paper so overlapping ones stay apart.
+private struct PlaceMark: View {
+    let diameter: CGFloat
+    let isSelected: Bool
+
+    var body: some View {
+        Circle()
+            .fill(Theme.accent.opacity(isSelected ? 1 : 0.75))
+            .frame(width: diameter, height: diameter)
+            .overlay(Circle().strokeBorder(isSelected ? Theme.ink : Theme.paper, lineWidth: 2))
+    }
+}
+
+/// The map of places, with the place chosen on it named beneath.
+struct PlacesMapView: View {
+    let model: ChartsModel
+    @State private var selection: String?
+
+    var body: some View {
+        let summary = model.data.context.places
+        VStack(spacing: 0) {
+            PlacesMap(places: summary?.places ?? [], selection: $selection)
+            VStack(alignment: .leading, spacing: Theme.lineGap) {
+                if let place = summary?.places.first(where: { $0.id == selection }) {
+                    Text(place.name)
+                        .font(Theme.serif(.title3, weight: .medium))
+                    Text("^[\(place.count) report](inflect: true)")
+                        .font(.footnote)
+                        .foregroundStyle(Theme.muted)
+                } else {
+                    Text(model.data.period.title)
+                        .font(Theme.serif(.title3, weight: .medium))
+                    footnote(for: summary)
+                        .font(.footnote)
+                        .foregroundStyle(Theme.muted)
+                }
+            }
+            .frame(maxWidth: .infinity, alignment: .leading)
+            .padding(.horizontal, Theme.margin)
+            .padding(.vertical, Theme.itemGap)
+            .background(Theme.paper)
+            .overlay(alignment: .top) { Rectangle().fill(Theme.rule).frame(height: 1) }
+        }
+        .foregroundStyle(Theme.ink)
+        .navigationTitle("Places")
+        .navigationBarTitleDisplayMode(.inline)
+    }
+
+    private func footnote(for summary: PlacesSummary?) -> Text {
+        let shown = Text("^[\(summary?.places.count ?? 0) place](inflect: true). Tap one to see it.")
+        guard let unplaced = summary?.unplaced, unplaced > 0 else { return shown }
+        return Text("\(shown) ^[\(unplaced) place](inflect: true) without a location can't be shown.")
+    }
+}
+
+extension MapPlace {
+    fileprivate var centre: CLLocationCoordinate2D {
+        CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
+    }
+}

diff --git a/Tests/Unit/AnswerSummaryTests.swift b/Tests/Unit/AnswerSummaryTests.swift

@@ -142,6 +142,36 @@ struct AnswerSummaryTests {
         #expect(temperature.trend == [TrendPoint(date: Self.gmt.start(of: .month, for: base), value: 15, low: 10, high: 20)])
     }
 
+    @Test("Places are counted after merges and shown at their own coordinate or their answers' centre")
+    func places() throws {
+        func place(_ id: String, _ latitude: Double? = nil) -> AnswerRecord {
+            Self.row(
+                "place",
+                .place(PlaceAnswer(tokenID: id, coordinate: latitude.map { Coordinate(latitude: $0, longitude: 0) })))
+        }
+        var lookup = Self.lookup
+        lookup.tokenTexts["office"] = "Office"
+        lookup.tokenTexts["old-office"] = "Office"
+        lookup.mergedIDs["old-office"] = "office"
+        lookup.tokenTexts["nowhere"] = "Nowhere"
+        let rows = [
+            place("home", 1), place("home", 3), place("home"),
+            place("office"), place("old-office", 50),
+            place("nowhere"),
+            Self.row("people", .tokens(["kai"])),
+        ]
+        let summary = try #require(
+            PlacesSummary.summarise(
+                rows, lookup: lookup, tokenCoordinates: ["office": Coordinate(latitude: 10, longitude: 10)]))
+        #expect(
+            summary.places == [
+                MapPlace(id: "home", name: "Home", coordinate: Coordinate(latitude: 2, longitude: 0), count: 3),
+                MapPlace(id: "office", name: "Office", coordinate: Coordinate(latitude: 10, longitude: 10), count: 2),
+            ])
+        #expect(summary.unplaced == 1)
+        #expect(PlacesSummary.summarise([], lookup: lookup, tokenCoordinates: [:]) == nil)
+    }
+
     @Test("Periods end now and reach back a week, a month or a year")
     func periods() {
         var calendar = Calendar(identifier: .gregorian)

diff --git a/Tests/Unit/ReportStoreTests.swift b/Tests/Unit/ReportStoreTests.swift

@@ -134,7 +134,7 @@ struct ReportStoreTests {
         #expect(entries[0].useCount == 2)
         #expect(entries[0].merged == [MergedToken(id: "B", text: "Sam", useCount: 2), MergedToken(id: "O", text: "Sammy", useCount: 0)])
         #expect(entries[0].matches("sammy"))
-        #expect(try await store.tokens(for: ["Q"]).map(\.id) == ["A", "C"])
+        #expect(try await store.tokens(for: ["Q"]).map(\.id).sorted() == ["A", "C"])
         #expect(try await store.summaryLookup().mergedIDs == ["B": "A", "O": "A"])
 
         try await store.merge("B", into: nil)