commit 82d12e1a25dbfcf6375d192a9c185a5610e3cac4
parent 6db5c7e3445d5e121f4422fa884ff78a458f605a
Author: Michael Camilleri <[email protected]>
Date: Sat, 17 Oct 2026 13:06:44 +0900
Add a detail view for reports
Tapping a report in the timeline went straight to the survey, so the
only way to look at a report was to start editing it, and most of what
was recorded with it — the address, the weather, the location fix, the
device state — was never shown anywhere.
This commit opens a detail view instead. It shows the report's day, time
in its own zone and kind, a map of where it was made, every answer under
the prompt it was asked with ('Skipped' for questions left unanswered),
and then every value recorded with it in titled sections: Time, Place,
Location, Weather, Device, Motion, Sound, Photos and Record. Activities
and people appear as pills on a faint wash of the accent, one per token.
Measurements follow the user's locale, invalid readings such as a
negative speed are left out, and sections with nothing recorded are
omitted. The map can be panned and zoomed, and once moved, a button
returns it to the report's spot. Addresses are now looked up in the
user's first language and, where it differs, the place's own language,
worked out from the country of the first result.
'Edit' (or 'Answer', for an instant report) opens the survey, and the
view updates as soon as it is saved. 'Delete Report' asks first, then
removes the report and its responses but keeps the tokens they used.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 33 | ++++++++++++++++++++++++++------- |
| M | Reportage.xcodeproj/project.pbxproj | | | 20 | ++++++++++++++++++++ |
| M | Reportage/Services/Narrative/EntryDraft.swift | | | 3 | ++- |
| M | Reportage/Views/Home/HomeView.swift | | | 46 | +++++++++++++++++++++++++++------------------- |
| A | Reportage/Views/Report/ReportDetailView.swift | | | 382 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | Reportage/Views/Report/ReportDetails.swift | | | 363 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/ReportKind+Title.swift | | | 13 | +++++++++++++ |
| M | Shared/Capture/ContextCapture.swift | | | 38 | ++++++++++++++++++++++++++++++-------- |
| M | Shared/Persistence/ReportStore.swift | | | 11 | +++++++++++ |
| M | Tests/Unit/ContextCaptureTests.swift | | | 10 | ++++++++++ |
| A | Tests/Unit/ReportDetailsTests.swift | | | 138 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Tests/Unit/ReportStoreTests.swift | | | 18 | ++++++++++++++++++ |
12 files changed, 1040 insertions(+), 35 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -98,6 +98,22 @@ The look is called Almanac: ink on paper, like a printed journal.
device's time zone: grouping by each report's own zone would put reports out
of order around midnight after a change of zone, which a sectioned fetch
can't show.
+- **Report detail:** tapping a report in the timeline pushes its detail view:
+ the day, the time in the report's own zone and its kind, a map of where it
+ was made (with a circle for the fix's accuracy), every
+ answer with the prompt it was asked under ('Skipped' for questions left
+ unanswered), then every value recorded with it, in titled
+ sections (Time, Place, Location, Weather, Device, Motion, Sound, Photos,
+ Record) of label and value rows; the address in the place's own language
+ is labelled 'Endonymic Address'. The map can be panned and zoomed, but not
+ rotated; once moved, a button in its corner brings it back to the
+ report's spot. It has no zoom buttons, as maps on iPhone don't. The entry isn't repeated here. Activities
+ and people are shown as pills, one per token, since an answer can have
+ several: the name in the serif on a faint wash of the accent, quieter than
+ the survey's ink-filled tokens, which can be tapped where these can't. Measurements are shown in the user's
+ locale's units. Edit (or Answer, for an instant report) opens the survey,
+ and Delete Report deletes it after asking. Deleting removes the report and
+ its responses but keeps its tokens; sync will need to carry deletions.
- **Survey:** a flat header (Cancel, the kind and time, '3 / 6' and a progress
bar with a segment per question) instead of the glass toolbar, a serif
prompt, ink-outlined answer buttons, chips for chosen tokens and an
@@ -541,9 +557,9 @@ a fix with 'Always' needs checking on a device.
A passive report records "this moment" with its context and nothing else. It
appears in the timeline like any other report, labelled 'Instant', rather than
in a list of unfinished reports: some users will want to keep such reports as
-they are, and shouldn't feel pressed to fill them in. Tapping one fills it in,
-answering the survey as of the report's original `date` with the context it
-was logged with. Only the answers and its completion are saved, so a context
+they are, and shouldn't feel pressed to fill them in. Its detail view offers
+**Answer**, which fills it in, answering the survey as of the report's
+original `date` with the context it was logged with. Only the answers and its completion are saved, so a context
capture still under way isn't overwritten.
A passive report is saved as soon as it's logged, so it's in the timeline at
@@ -553,7 +569,8 @@ opening the survey. The badge counts passive reports; it shows only
once notifications are allowed, which Phase 3 asks for, and could become a
setting.
-Any finished report can be edited the same way, by tapping it. The survey
+Any finished report can be edited the same way, with **Edit** in its detail
+view. The survey
shows the questions the report answered, in its order and as they were asked,
including archived ones, rather than today's survey: adding new questions to
an old report would rewrite history. Answers using archived or merged tokens
@@ -613,9 +630,11 @@ fields where they still exist, plus the language, the region code, the city
with its region and the full and short addresses. In a Simulator test the
whole capture took 0.2 s. Reverse
geocoding uses MapKit's `MKReverseGeocodingRequest` (`CLGeocoder` is deprecated
-in iOS 26), once per language the user knows (for now, the first two of the
-device's preferred languages), using `preferredLocale`, so the
-placemark can be shown by the same rule as place names. Reporter's archive
+in iOS 26), using `preferredLocale`: once in the user's first language, and
+again in the place's local language when that differs (worked out from the
+first result's country: `ja` for Japan, `zh-Hant` for Taiwan), so the
+placemark can be shown by the same rule as place names. Reports made before
+this have their second address in the device's second preferred language. Reporter's archive
mixes Japanese and English placemarks depending on the device language at the
time. Apple throttles geocoding, so two requests per report is fine but
re-geocoding the archive would have to run slowly in the background.
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -18,6 +18,7 @@
2EE68329C383FA1C5295ACA9 /* PlaceAnswerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9856D1F8123B9CAD7D39071D /* PlaceAnswerView.swift */; };
3175E324135E1CF5A73683D1 /* ReporterTimeZones.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7196D553D769071DB876B606 /* ReporterTimeZones.swift */; };
3244B8439B5E4F79FF84C156 /* JSONSlicer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 643C730A99F0B7BA8C1F8A8E /* JSONSlicer.swift */; };
+ 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 */; };
3FBE5C53D33EF78752BEACE0 /* ReporterImportVerifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3ED0CAE575381DCB86FB8EE9 /* ReporterImportVerifier.swift */; };
@@ -44,6 +45,7 @@
964408E4D25713F627048C77 /* ModelCodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */; };
97BC8348B7F48AF0473691FC /* ReportStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28AD66BC8ED4AEABF6640108 /* ReportStore.swift */; };
9EF3CB3707CD6B5AFFD3B767 /* ReporterArchive.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1C5F0F722477CDA949F018 /* ReporterArchive.swift */; };
+ A740B635075EB81AA70ED815 /* ReportDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F498961A14F24AE6CC37453C /* ReportDetailView.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 */; };
@@ -70,6 +72,7 @@
EFF44121C9ECBFBCAC1D7730 /* ReportageModel.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = A49FBFD55992A79B9A6492C4 /* ReportageModel.xcdatamodeld */; };
F38A1CCFAF016AB982EAB791 /* Question.swift in Sources */ = {isa = PBXBuildFile; fileRef = B007E6BACAA214C7332EF77C /* Question.swift */; };
F6F2DD23C77A981D76BE0480 /* NarrativePolisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF426915E941538164D91B18 /* NarrativePolisher.swift */; };
+ FBE598AB29E0297BC232ED75 /* ReportDetailsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEB5080BDA34F703DDC08ADB /* ReportDetailsTests.swift */; };
FD41318BC8EEAF3208CD59B7 /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A70B6E5B7C07D2CE13E9E771 /* RootView.swift */; };
/* End PBXBuildFile section */
@@ -143,7 +146,9 @@
B7998F9826B899741323C0C7 /* SurveyView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyView.swift; sourceTree = "<group>"; };
BBBE80E95676BAEB53CE80E0 /* PlaceDirectory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlaceDirectory.swift; sourceTree = "<group>"; };
BC27A2AF600780976CFA295C /* PromptScheduleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptScheduleTests.swift; sourceTree = "<group>"; };
+ BEB5080BDA34F703DDC08ADB /* ReportDetailsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportDetailsTests.swift; sourceTree = "<group>"; };
BF998798373C9CCAD65999B3 /* TokenAnswer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TokenAnswer.swift; sourceTree = "<group>"; };
+ C269C1BE83C1A5E08AC087E3 /* ReportDetails.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportDetails.swift; sourceTree = "<group>"; };
C3C7B68925A281EF806BB9B8 /* Theme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Theme.swift; sourceTree = "<group>"; };
CC1C5F0F722477CDA949F018 /* ReporterArchive.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterArchive.swift; sourceTree = "<group>"; };
CD433A98973E8B13E42230A1 /* ReportageExporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExporter.swift; sourceTree = "<group>"; };
@@ -152,6 +157,7 @@
DB87A3E922FA7AE98B93DF1E /* PromptSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSettings.swift; sourceTree = "<group>"; };
E21F898FF60FC3A6AFCA06E9 /* Reportage Unit Tests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = "Reportage Unit Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExport.swift; sourceTree = "<group>"; };
+ F498961A14F24AE6CC37453C /* ReportDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportDetailView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXGroup section */
@@ -196,6 +202,15 @@
path = Theme;
sourceTree = "<group>";
};
+ 2AA377CB45537E6D2364ABF2 /* Report */ = {
+ isa = PBXGroup;
+ children = (
+ C269C1BE83C1A5E08AC087E3 /* ReportDetails.swift */,
+ F498961A14F24AE6CC37453C /* ReportDetailView.swift */,
+ );
+ path = Report;
+ sourceTree = "<group>";
+ };
4C708676FBAD641AD92F8CA0 /* Reportage */ = {
isa = PBXGroup;
children = (
@@ -283,6 +298,7 @@
BC27A2AF600780976CFA295C /* PromptScheduleTests.swift */,
3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */,
7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */,
+ BEB5080BDA34F703DDC08ADB /* ReportDetailsTests.swift */,
487F88C880B5DE69964C6A37 /* ReporterArchiveTests.swift */,
917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */,
7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */,
@@ -363,6 +379,7 @@
5591E042089D038B59B26E9F /* ReportKind+Title.swift */,
A70B6E5B7C07D2CE13E9E771 /* RootView.swift */,
01DE4634BAAD579B60FBA5ED /* Home */,
+ 2AA377CB45537E6D2364ABF2 /* Report */,
B74082E720FBA1EF05FE11E4 /* Settings */,
23711442404F0476532D0FC2 /* Survey */,
28F1EEFBA9AE0C97C4ACEF89 /* Theme */,
@@ -492,6 +509,7 @@
35D02EAE3D95DB5CCEE8A82E /* PromptScheduleTests.swift in Sources */,
16D2FB106A2C588BAAB3EB06 /* PromptSchedulerTests.swift in Sources */,
4A0DEFB7E69A9FC5EAAD99D4 /* RealExportVerificationTests.swift in Sources */,
+ FBE598AB29E0297BC232ED75 /* ReportDetailsTests.swift in Sources */,
0F052B8A2C73437F57E927E7 /* ReportStoreTests.swift in Sources */,
D3FF67FB406DCCB78DF9D61A /* ReportSummaryTests.swift in Sources */,
B510BB2C1C11D72DFE15E3C7 /* ReportageExportTests.swift in Sources */,
@@ -534,6 +552,8 @@
F38A1CCFAF016AB982EAB791 /* Question.swift in Sources */,
85A36A88AB170F0EAC0DAC03 /* QuestionPage.swift in Sources */,
06415D2A2EDA6E92ECAC96FA /* Report.swift in Sources */,
+ A740B635075EB81AA70ED815 /* ReportDetailView.swift in Sources */,
+ 34C3A453ABC838F73DC3E294 /* ReportDetails.swift in Sources */,
D7F95FB1236974113EBE93FA /* ReportKind+Title.swift in Sources */,
97BC8348B7F48AF0473691FC /* ReportStore.swift in Sources */,
7ACDA81EC3D7811F891CA029 /* ReportSummary.swift in Sources */,
diff --git a/Reportage/Services/Narrative/EntryDraft.swift b/Reportage/Services/Narrative/EntryDraft.swift
@@ -154,7 +154,8 @@ enum EntryBuilder {
AnswerDetail(questionID: response.questionID, prompt: response.prompt, answer: answer)
}
- private static func describe(_ value: ResponseValue, lookup: SummaryLookup) -> String {
+ /// An answer as text, with token IDs replaced by their names.
+ static func describe(_ value: ResponseValue, lookup: SummaryLookup) -> String {
switch value {
case .options(let options): displayOptions(options)
case .tokens(let ids): joined(ids.compactMap { lookup.tokenTexts[$0] })
diff --git a/Reportage/Views/Home/HomeView.swift b/Reportage/Views/Home/HomeView.swift
@@ -9,18 +9,25 @@ struct HomeView: View {
@Environment(PromptInbox.self) private var inbox: PromptInbox?
@State private var survey: SurveyRequest?
@State private var describer = ReportDescriber()
+ /// The reports opened from the timeline.
+ @State private var path: [ReportRoute] = []
private let logger = Logger(subsystem: "net.inqk.reportage", category: "Home")
var body: some View {
- NavigationStack {
+ NavigationStack(path: $path) {
ReportList(
describer: describer,
onStart: { kind in survey = SurveyRequest(kind: kind) },
onQuickLog: quickLog,
- onEdit: { id, kind in survey = .edit(id, kind: kind) }
+ onOpen: { id in path.append(ReportRoute(id: id)) }
)
.toolbar(.hidden, for: .navigationBar)
+ .navigationDestination(for: ReportRoute.self) { route in
+ ReportDetailView(id: route.id, describer: describer) { id, kind in
+ survey = .edit(id, kind: kind)
+ }
+ }
}
.sheet(item: $survey, onDismiss: reload) { request in
SurveySheet(request: request)
@@ -90,6 +97,17 @@ final class ReportDescriber {
}
extension ReportEntity {
+ /// The entry to show: the stored narrative if it was made from the
+ /// current draft, otherwise the draft itself. A narrative from an older
+ /// polishing pass is still shown until it's rewritten.
+ func displayedEntry(for draft: EntryDraft?) -> String? {
+ guard let draft else { return nil }
+ if narrativeDraft == draft.text, let narrative {
+ return narrative
+ }
+ return draft.text
+ }
+
/// The calendar day of the report in the device's time zone, for grouping
/// the list. Grouping by each report's own zone would put reports out of
/// order around midnight when the user changes zones, which a sectioned
@@ -107,8 +125,8 @@ struct ReportList: View {
let describer: ReportDescriber
let onStart: (ReportKind) -> Void
let onQuickLog: () -> Void
- /// Opens the survey for an existing report, to fill it in or edit it.
- let onEdit: (UUID, ReportKind) -> Void
+ /// Opens a report's details.
+ let onOpen: (UUID) -> Void
@SectionedFetchRequest(fetchRequest: ReportList.request, sectionIdentifier: \ReportEntity.dayKey)
private var days: SectionedFetchResults<String, ReportEntity>
@@ -152,22 +170,19 @@ struct ReportList: View {
.background(Theme.paper)
}
- /// A report can be tapped to fill it in, if it's an instant report, or
- /// to edit its answers.
+ /// A report is tapped to see it in full, where it can be edited or
+ /// answered.
@ViewBuilder
private func row(for report: ReportEntity) -> some View {
if let id = report.id {
Button {
- onEdit(id, report.kind.flatMap(ReportKind.init) ?? .manual)
+ onOpen(id)
} label: {
ReportRow(report: report, describer: describer)
.contentShape(.rect)
}
.buttonStyle(.plain)
- .accessibilityHint(
- report.state == ReportState.passive.rawValue
- ? Text("Answers the survey for this moment")
- : Text("Edits this report's answers"))
+ .accessibilityHint(Text("Shows this report in full"))
} else {
ReportRow(report: report, describer: describer)
}
@@ -320,15 +335,8 @@ struct ReportRow: View {
/// Whether the report was logged for later and has no answers yet.
private var isLogged: Bool { report.state == ReportState.passive.rawValue }
- /// The stored narrative if it was made from the current draft, otherwise
- /// the draft itself. A narrative from an older polishing pass is still
- /// shown until it's rewritten.
private func entry(for draft: EntryDraft?) -> String? {
- guard let draft else { return nil }
- if report.narrativeDraft == draft.text, let narrative = report.narrative {
- return narrative
- }
- return draft.text
+ report.displayedEntry(for: draft)
}
private func isCurrent(_ draft: EntryDraft) -> Bool {
diff --git a/Reportage/Views/Report/ReportDetailView.swift b/Reportage/Views/Report/ReportDetailView.swift
@@ -0,0 +1,382 @@
+import CoreData
+import MapKit
+import SwiftUI
+
+/// Where the timeline goes when a report is tapped.
+struct ReportRoute: Hashable {
+ let id: UUID
+}
+
+/// One report in full: when it was, where it was on a map, every answer,
+/// and everything recorded with it. It can be edited (or, for an
+/// instant report, answered) and deleted from here.
+struct ReportDetailView: View {
+ let describer: ReportDescriber
+ /// Opens the survey for the report, to edit or answer it.
+ let onEdit: (UUID, ReportKind) -> Void
+
+ @Environment(\.reportStore) private var store
+ @Environment(\.dismiss) private var dismiss
+ @FetchRequest private var reports: FetchedResults<ReportEntity>
+
+ init(id: UUID, describer: ReportDescriber, onEdit: @escaping (UUID, ReportKind) -> Void) {
+ self.describer = describer
+ self.onEdit = onEdit
+ let request = ReportEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
+ request.sortDescriptors = []
+ request.fetchLimit = 1
+ request.relationshipKeyPathsForPrefetching = ["responses"]
+ _reports = FetchRequest(fetchRequest: request)
+ }
+
+ var body: some View {
+ // Fetched rather than passed in, so an edit shows here at once and a
+ // deleted report leaves nothing behind.
+ Group {
+ if let entity = reports.first, let report = try? entity.report() {
+ ReportDetailContent(
+ entity: entity, report: report, describer: describer,
+ onEdit: { onEdit(report.id, report.kind) },
+ onDelete: { delete(report.id) })
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
+ .background(Theme.paper)
+ .toolbar(.visible, for: .navigationBar)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ /// Goes back to the timeline, then deletes, so this screen never shows
+ /// an empty report.
+ private func delete(_ id: UUID) {
+ guard let store else { return }
+ dismiss()
+ Task {
+ try? await store.delete(id: id)
+ await AppBadge.update(from: store)
+ }
+ }
+}
+
+/// The detail view's contents for one report, scrolling, with its Edit and
+/// Delete actions.
+struct ReportDetailContent: View {
+ @ObservedObject var entity: ReportEntity
+ let report: Report
+ let describer: ReportDescriber
+ let onEdit: () -> Void
+ let onDelete: () -> Void
+
+ @State private var isConfirmingDelete = false
+
+ var body: some View {
+ let isInstant = report.state == .passive
+ ScrollView {
+ ReportDetailPage(
+ entity: entity, report: report, describer: describer,
+ onDelete: { isConfirmingDelete = true })
+ }
+ .toolbar {
+ ToolbarItem(placement: .primaryAction) {
+ Button(isInstant ? "Answer" : "Edit", action: onEdit)
+ .accessibilityHint(
+ isInstant
+ ? Text("Answers the survey for this moment")
+ : Text("Edits this report's answers"))
+ }
+ }
+ .confirmationDialog("Delete this report?", isPresented: $isConfirmingDelete, titleVisibility: .visible) {
+ Button("Delete Report", role: .destructive, action: onDelete)
+ } message: {
+ Text("This can't be undone.")
+ }
+ }
+}
+
+/// Everything on the detail page, top to bottom.
+struct ReportDetailPage: View {
+ @ObservedObject var entity: ReportEntity
+ let report: Report
+ let describer: ReportDescriber
+ let onDelete: () -> Void
+
+ var body: some View {
+ let details = ReportDetails(report: report, lookup: describer.lookup)
+ let isInstant = report.state == .passive
+ VStack(alignment: .leading, spacing: Theme.blockGap) {
+ ReportDetailHeader(report: report, isInstant: isInstant)
+ if let location = report.context.location {
+ ReportMap(location: location)
+ }
+ if isInstant, details.answers.isEmpty {
+ Text("Not answered yet.", comment: "Shown on an instant report that has no answers")
+ .font(Theme.serif(.body).italic())
+ .foregroundStyle(Theme.muted)
+ }
+ if !details.answers.isEmpty {
+ DetailSection(title: String(localized: "Answers")) {
+ ForEach(Array(details.answers.enumerated()), id: \.offset) { _, answer in
+ AnswerRow(answer: answer)
+ }
+ }
+ }
+ ForEach(Array(details.sections.enumerated()), id: \.offset) { _, section in
+ DetailSection(title: section.title) {
+ ForEach(Array(section.rows.enumerated()), id: \.offset) { _, row in
+ ValueRow(row: row)
+ }
+ }
+ }
+ Button("Delete Report", role: .destructive, action: onDelete)
+ .font(.body.weight(.semibold))
+ .frame(maxWidth: .infinity, minHeight: 44)
+ .padding(.top, Theme.blockGap)
+ }
+ .padding(.horizontal, Theme.margin)
+ .padding(.vertical, Theme.pageTop)
+ }
+}
+
+/// The report's day, its time in the zone it was made in, and its kind.
+private struct ReportDetailHeader: View {
+ let report: Report
+ let isInstant: Bool
+
+ var body: some View {
+ let zone = TimeZone(identifier: report.timeZone) ?? .current
+ VStack(alignment: .leading, spacing: Theme.lineGap) {
+ Text(report.date, format: .dateTime.weekday(.wide).day().month(.wide).year().timeZone(zone))
+ .eyebrow()
+ Text(report.date, format: Date.FormatStyle(date: .omitted, time: .shortened, timeZone: zone))
+ .font(Theme.serif(.largeTitle, weight: .medium))
+ .monospacedDigit()
+ .foregroundStyle(Theme.ink)
+ ReportKindLabel(kind: report.kind, isLogged: isInstant)
+ }
+ .accessibilityElement(children: .combine)
+ }
+}
+
+extension Date.FormatStyle {
+ fileprivate func timeZone(_ zone: TimeZone) -> Self {
+ var style = self
+ style.timeZone = zone
+ return style
+ }
+}
+
+/// Where the report was made, with a circle for the fix's accuracy. It can
+/// be panned and zoomed, but not rotated or tilted, so north stays up; once
+/// it's been moved, a button brings it back to the report's spot.
+private struct ReportMap: View {
+ let location: LocationContext
+
+ @State private var position: MapCameraPosition
+
+ init(location: LocationContext) {
+ self.location = location
+ _position = State(initialValue: Self.home(for: location))
+ }
+
+ /// Centred on where the report was made.
+ private static func home(for location: LocationContext) -> MapCameraPosition {
+ .camera(MapCamera(centerCoordinate: location.centre, distance: 1500))
+ }
+
+ var body: some View {
+ let centre = location.centre
+ Map(position: $position, interactionModes: [.pan, .zoom]) {
+ if let accuracy = location.horizontalAccuracy, accuracy > 0 {
+ MapCircle(center: centre, radius: accuracy)
+ .foregroundStyle(Theme.mark.opacity(0.15))
+ }
+ Annotation("", coordinate: centre) {
+ Circle()
+ .fill(Theme.mark)
+ .frame(width: 12, height: 12)
+ .overlay(Circle().strokeBorder(Theme.paper, lineWidth: 2))
+ }
+ }
+ .accessibilityHidden(true)
+ .frame(height: 200)
+ .clipShape(.rect(cornerRadius: 6))
+ .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(Theme.rule))
+ .overlay(alignment: .bottomTrailing) {
+ // Only once the map has been moved: until then it's already
+ // showing the report's spot.
+ if position.positionedByUser {
+ Button {
+ withAnimation { position = Self.home(for: location) }
+ } label: {
+ Image(systemName: "scope")
+ .font(.body.weight(.medium))
+ .foregroundStyle(Theme.ink)
+ .frame(width: 36, height: 36)
+ .background(Theme.paper, in: .circle)
+ .overlay(Circle().strokeBorder(Theme.rule))
+ .contentShape(.circle)
+ }
+ .buttonStyle(.plain)
+ .padding(8)
+ .accessibilityLabel(Text("Show Where This Was Reported"))
+ .transition(.opacity)
+ }
+ }
+ .animation(.default, value: position.positionedByUser)
+ }
+}
+
+extension LocationContext {
+ fileprivate var centre: CLLocationCoordinate2D {
+ CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
+ }
+}
+
+/// A heading in small spaced capitals over rows divided by hairlines.
+private struct DetailSection<Content: View>: View {
+ let title: String
+ @ViewBuilder let content: Content
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ Text(title)
+ .eyebrow()
+ .accessibilityAddTraits(.isHeader)
+ .padding(.top, Theme.headingTop)
+ .padding(.bottom, 4)
+ Group(subviews: content) { rows in
+ ForEach(Array(rows.enumerated()), id: \.offset) { index, row in
+ if index > 0 {
+ Rectangle().fill(Theme.rule).frame(height: 1)
+ }
+ row.padding(.vertical, 10)
+ }
+ }
+ }
+ }
+}
+
+/// A question as it was asked, and its answer in the serif.
+private struct AnswerRow: View {
+ let answer: ReportDetails.Answer
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: Theme.lineGap) {
+ Text(answer.prompt)
+ .font(.subheadline)
+ .foregroundStyle(Theme.muted)
+ switch answer.value {
+ case .text(let text):
+ Text(text)
+ .font(Theme.serif(.body))
+ .foregroundStyle(Theme.ink)
+ case .tokens(let names):
+ FlowLayout(spacing: Theme.chipGap) {
+ ForEach(Array(names.enumerated()), id: \.offset) { _, name in
+ TokenPill(name: name)
+ }
+ }
+ .padding(.top, 4)
+ case .skipped:
+ Text("Skipped", comment: "A question shown in a survey but not answered")
+ .font(Theme.serif(.body).italic())
+ .foregroundStyle(Theme.muted)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .accessibilityElement(children: .combine)
+ }
+}
+
+/// One token of an answer: an activity or a person, on a faint wash of the
+/// accent. Quieter than the survey's ink-filled tokens, which can be tapped
+/// and these can't.
+private struct TokenPill: View {
+ let name: String
+
+ var body: some View {
+ Text(name)
+ .font(Theme.serif(.body))
+ .foregroundStyle(Theme.ink)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 3)
+ .background(Theme.accent.opacity(0.1), in: .capsule)
+ }
+}
+
+/// Lays its subviews out in rows, left to right, starting a new row when the
+/// next won't fit.
+struct FlowLayout: Layout {
+ var spacing: CGFloat
+
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
+ let rows = rows(for: subviews, width: proposal.width ?? .infinity)
+ let width = rows.map(\.width).max() ?? 0
+ let height = rows.map(\.height).reduce(0, +) + spacing * CGFloat(max(rows.count - 1, 0))
+ return CGSize(width: width, height: height)
+ }
+
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
+ var y = bounds.minY
+ for row in rows(for: subviews, width: bounds.width) {
+ var x = bounds.minX
+ for index in row.indices {
+ let size = subviews[index].sizeThatFits(ProposedViewSize(width: bounds.width, height: nil))
+ subviews[index].place(
+ at: CGPoint(x: x, y: y + (row.height - size.height) / 2),
+ proposal: ProposedViewSize(size))
+ x += size.width + spacing
+ }
+ y += row.height + spacing
+ }
+ }
+
+ private struct Row {
+ var indices: [Int] = []
+ var width: CGFloat = 0
+ var height: CGFloat = 0
+ }
+
+ private func rows(for subviews: Subviews, width: CGFloat) -> [Row] {
+ var rows: [Row] = []
+ var row = Row()
+ // A subview is offered at most the whole width, so a long one wraps
+ // within its own row rather than overflowing.
+ for index in subviews.indices {
+ let size = subviews[index].sizeThatFits(ProposedViewSize(width: width, height: nil))
+ let needed = row.indices.isEmpty ? size.width : row.width + spacing + size.width
+ if needed > width, !row.indices.isEmpty {
+ rows.append(row)
+ row = Row()
+ }
+ row.width = row.indices.isEmpty ? size.width : row.width + spacing + size.width
+ row.height = max(row.height, size.height)
+ row.indices.append(index)
+ }
+ if !row.indices.isEmpty { rows.append(row) }
+ return rows
+ }
+}
+
+/// A label and its value, side by side. The label keeps to one line and a
+/// long value wraps.
+private struct ValueRow: View {
+ let row: ReportDetails.Row
+
+ var body: some View {
+ HStack(alignment: .firstTextBaseline, spacing: Theme.itemGap) {
+ Text(row.label)
+ .foregroundStyle(Theme.muted)
+ .fixedSize()
+ Spacer(minLength: Theme.itemGap)
+ Text(row.value)
+ .foregroundStyle(Theme.ink)
+ .multilineTextAlignment(.trailing)
+ .fixedSize(horizontal: false, vertical: true)
+ .textSelection(.enabled)
+ }
+ .font(.subheadline)
+ .accessibilityElement(children: .combine)
+ }
+}
diff --git a/Reportage/Views/Report/ReportDetails.swift b/Reportage/Views/Report/ReportDetails.swift
@@ -0,0 +1,363 @@
+import Foundation
+
+/// Everything recorded about a report, as text for the detail view: its
+/// answers, then its context and record in titled sections. Sections with
+/// nothing recorded are left out, as are rows with no value.
+@MainActor
+struct ReportDetails: Equatable {
+ struct Answer: Equatable {
+ enum Value: Equatable {
+ case text(String)
+ /// The names of the tokens chosen for an activities or people
+ /// question, which can have several, in the order chosen.
+ case tokens([String])
+ case skipped
+ }
+
+ var prompt: String
+ var value: Value
+ }
+
+ struct Row: Equatable {
+ var label: String
+ var value: String
+ }
+
+ struct Section: Equatable {
+ var title: String
+ var rows: [Row]
+ }
+
+ var answers: [Answer]
+ var sections: [Section]
+
+ init(report: Report, lookup: SummaryLookup, locale: Locale = .current) {
+ let format = Formatter(zone: TimeZone(identifier: report.timeZone) ?? .current, locale: locale)
+ answers = report.responses.map { response in
+ let value: Answer.Value =
+ switch response.value {
+ case nil: .skipped
+ case .tokens(let ids): .tokens(ids.compactMap { lookup.tokenTexts[$0] })
+ case let value?: .text(EntryBuilder.describe(value, lookup: lookup))
+ }
+ return Answer(prompt: response.prompt, value: value)
+ }
+ let context = report.context
+ sections = [
+ Self.time(report, format),
+ context.location?.placemark.map { Self.place($0, others: context.location?.localisedPlacemarks ?? [], format) },
+ context.location.map { Self.location($0, format) },
+ context.weather.map { Self.weather($0, format) },
+ context.device.map { Self.device($0, format) },
+ context.motion.map { Self.motion($0, format) },
+ context.audio.map { Self.audio($0, format) },
+ context.photos.map { Self.photos($0, format) },
+ Self.record(report, format),
+ ]
+ .compactMap { $0 }
+ .filter { !$0.rows.isEmpty }
+ }
+
+ // MARK: Sections
+
+ private static func time(_ report: Report, _ f: Formatter) -> Section {
+ var rows = [
+ row("Reported", f.dateTime(report.date)),
+ row("Time Zone", f.zoneName(report.timeZone)),
+ row("Source", String(localized: report.trigger.title)),
+ ]
+ if let promptedAt = report.promptedAt {
+ rows.append(row("Prompted", f.dateTime(promptedAt)))
+ if report.date > promptedAt {
+ rows.append(row("Reported After", f.duration(report.date.timeIntervalSince(promptedAt))))
+ }
+ }
+ if report.state == .passive {
+ rows.append(row("Answered", String(localized: "Not yet", comment: "An instant report with no answers")))
+ } else if let completedAt = report.completedAt {
+ rows.append(row("Answered", f.dateTime(completedAt)))
+ }
+ return Section(title: String(localized: "Time"), rows: rows.compactMap { $0 })
+ }
+
+ private static func place(_ placemark: Placemark, others: [Placemark], _ f: Formatter) -> Section {
+ var rows = [
+ row("Name", placemark.name),
+ row("Address", address(placemark)),
+ row("Neighbourhood", placemark.subLocality),
+ row("City", placemark.locality),
+ row("District", placemark.subAdministrativeArea),
+ row("Region", placemark.administrativeArea),
+ row("Postcode", placemark.postalCode),
+ row("Country", placemark.country),
+ row("Water", placemark.inlandWater ?? placemark.ocean),
+ ]
+ for other in others {
+ // Reports from before addresses were fetched in the local
+ // language have them in the user's second language instead.
+ let isLocal =
+ other.language != nil
+ && other.language == placemark.countryCode.flatMap(ContextCapture.localLanguage(ofRegion:))
+ let language = other.language.flatMap { f.locale.localizedString(forIdentifier: $0) }
+ let label =
+ if isLocal {
+ String(localized: "Endonymic Address", comment: "The address in the place's own language")
+ } else {
+ language.map { String(localized: "Address in \($0)", comment: "An address in another language") }
+ ?? String(localized: "Other Address")
+ }
+ rows.append(Row(label: label, value: address(other) ?? other.displayLocality ?? "").nonEmpty)
+ }
+ return Section(title: String(localized: "Place"), rows: rows.compactMap { $0 })
+ }
+
+ private static func location(_ location: LocationContext, _ f: Formatter) -> Section {
+ let rows = [
+ row("Coordinates", f.coordinate(location.coordinate)),
+ row("Accuracy", location.horizontalAccuracy.flatMap(f.metres).map { "±\($0)" }),
+ row("Altitude", location.altitude.flatMap { altitude in
+ f.metres(altitude, allowingNegative: true).map { value in
+ location.verticalAccuracy.flatMap(f.metres).map { "\(value) ±\($0)" } ?? value
+ }
+ }),
+ row("Speed", location.speed.flatMap(f.speed)),
+ row("Course", location.course.flatMap { $0 >= 0 ? f.bearing($0) : nil }),
+ row("Fix Taken", location.timestamp.map(f.dateTime)),
+ ]
+ return Section(title: String(localized: "Location"), rows: rows.compactMap { $0 })
+ }
+
+ private static func weather(_ weather: WeatherContext, _ f: Formatter) -> Section {
+ let wind = weather.windSpeed.map { speed in
+ let value = f.wind(speed)
+ return weather.windDirection.map { "\(value) \(String(localized: "from", comment: "Wind from a direction")) \(f.bearing($0))" } ?? value
+ }
+ var source: String
+ switch weather.source {
+ case .wunderground: source = "Weather Underground"
+ case .darkSky: source = "Dark Sky"
+ case .weatherKit: source = "Apple Weather"
+ }
+ if weather.backfilled == true {
+ source = String(localized: "\(source), filled in later", comment: "Weather fetched after the report was made")
+ }
+ let rows = [
+ row("Conditions", weather.condition),
+ row("Temperature", weather.temperature.map(f.temperature)),
+ row("Feels Like", weather.feelsLike.map(f.temperature)),
+ row("Dew Point", weather.dewPoint.map(f.temperature)),
+ row("Humidity", weather.humidity.map(f.percent)),
+ row("Pressure", weather.pressure.map(f.pressure)),
+ row("Wind", wind),
+ row("Gusts", weather.windGust.map(f.wind)),
+ row("Visibility", weather.visibility.map(f.visibility)),
+ row("UV Index", weather.uvIndex.map { $0.formatted(.number.precision(.fractionLength(0...1))) }),
+ row("Cloud Cover", weather.cloudCover.map(f.percent)),
+ row("Chance of Rain", weather.precipitationChance.map(f.percent)),
+ row("Rain Today", weather.precipitationToday.map(f.rainfall)),
+ row("Source", source),
+ ]
+ return Section(title: String(localized: "Weather"), rows: rows.compactMap { $0 })
+ }
+
+ private static func device(_ device: DeviceContext, _ f: Formatter) -> Section {
+ let state: String? = device.batteryState.map { state in
+ switch state {
+ case .unplugged: String(localized: "Not charging")
+ case .charging: String(localized: "Charging")
+ case .full: String(localized: "Full")
+ }
+ }
+ let connection: String? = device.connectivity.map { connectivity in
+ switch connectivity {
+ case .wifi: String(localized: "Wi-Fi")
+ case .cellular: String(localized: "Cellular")
+ case .none: String(localized: "None", comment: "No network connection")
+ }
+ }
+ let rows = [
+ row("Battery", device.batteryLevel.map(f.percent)),
+ row("Battery State", state),
+ row("Connection", connection),
+ ]
+ return Section(title: String(localized: "Device"), rows: rows.compactMap { $0 })
+ }
+
+ private static func motion(_ motion: MotionContext, _ f: Formatter) -> Section {
+ let rows = [
+ row("Steps Today", motion.steps.map { $0.formatted() }),
+ row("Floors Climbed", motion.floorsAscended.map { $0.formatted() }),
+ row("Floors Descended", motion.floorsDescended.map { $0.formatted() }),
+ row("Air Pressure", motion.pressure.map { f.pressure($0 * 10) }),
+ row("Relative Altitude", motion.relativeAltitude.flatMap { f.metres($0, allowingNegative: true) }),
+ ]
+ return Section(title: String(localized: "Motion"), rows: rows.compactMap { $0 })
+ }
+
+ private static func audio(_ audio: AudioContext, _ f: Formatter) -> Section {
+ let source: String =
+ switch audio.source {
+ case .microphone: String(localized: "Microphone")
+ case .healthEnvironmental: String(localized: "Health")
+ }
+ let rows = [
+ row("Average Level", audio.average.map(f.decibels)),
+ row("Peak Level", audio.peak.map(f.decibels)),
+ row("Source", source),
+ ]
+ return Section(title: String(localized: "Sound"), rows: rows.compactMap { $0 })
+ }
+
+ private static func photos(_ photos: PhotosContext, _ f: Formatter) -> Section {
+ var rows = [row("Taken Since Last Report", photos.count.formatted())]
+ for (index, photo) in photos.photos.enumerated() {
+ var parts: [String] = []
+ if let width = photo.pixelWidth, let height = photo.pixelHeight {
+ parts.append("\(width) × \(height)")
+ }
+ let camera = [photo.make, photo.model].compactMap { $0 }.joined(separator: " ")
+ if !camera.isEmpty { parts.append(camera) }
+ if let coordinate = photo.coordinate { parts.append(f.coordinate(coordinate)) }
+ let label = photo.date.map(f.time) ?? String(localized: "Photo \(index + 1)")
+ rows.append(Row(label: label, value: parts.joined(separator: " · ")).nonEmpty)
+ }
+ return Section(title: String(localized: "Photos"), rows: rows.compactMap { $0 })
+ }
+
+ private static func record(_ report: Report, _ f: Formatter) -> Section {
+ let rows = [
+ row("Last Changed", f.dateTime(report.modifiedAt)),
+ row("Reporter Original", report.legacy == nil ? nil : String(localized: "Kept", comment: "The original Reporter data is stored")),
+ row("ID", report.id.uuidString),
+ ]
+ return Section(title: String(localized: "Record"), rows: rows.compactMap { $0 })
+ }
+
+ // MARK: Helpers
+
+ private static func row(_ label: String.LocalizationValue, _ value: String?) -> Row? {
+ guard let value, !value.isEmpty else { return nil }
+ return Row(label: String(localized: label), value: value)
+ }
+
+ /// The full address, or the street parts that make one up.
+ private static func address(_ placemark: Placemark) -> String? {
+ if let full = placemark.fullAddress, !full.isEmpty { return full }
+ let street = [placemark.subThoroughfare, placemark.thoroughfare].compactMap { $0 }.joined(separator: " ")
+ let parts = [street, placemark.locality, placemark.administrativeArea, placemark.postalCode]
+ .compactMap { $0 }.filter { !$0.isEmpty }
+ return parts.isEmpty ? nil : parts.joined(separator: ", ")
+ }
+}
+
+extension ReportDetails.Row {
+ fileprivate var nonEmpty: Self? { value.isEmpty ? nil : self }
+}
+
+/// Formats a report's values in its own time zone and the user's locale.
+/// Measurements are stored metric and shown in the locale's units.
+private struct Formatter {
+ let zone: TimeZone
+ let locale: Locale
+
+ func dateTime(_ date: Date) -> String {
+ date.formatted(
+ Date.FormatStyle(date: .abbreviated, time: .standard, locale: locale, timeZone: zone))
+ }
+
+ func time(_ date: Date) -> String {
+ date.formatted(Date.FormatStyle(date: .omitted, time: .shortened, locale: locale, timeZone: zone))
+ }
+
+ /// The zone's name, with its identifier, such as 'Japan Standard Time
+ /// (Asia/Tokyo)'.
+ func zoneName(_ identifier: String) -> String {
+ guard let zone = TimeZone(identifier: identifier),
+ let name = zone.localizedName(for: .standard, locale: locale)
+ else { return identifier }
+ return "\(name) (\(identifier))"
+ }
+
+ func duration(_ interval: TimeInterval) -> String {
+ Duration.seconds(interval.rounded()).formatted(
+ .units(allowed: [.days, .hours, .minutes, .seconds], width: .abbreviated, maximumUnitCount: 2)
+ .locale(locale))
+ }
+
+ func coordinate(_ coordinate: Coordinate) -> String {
+ let style = FloatingPointFormatStyle<Double>(locale: locale).precision(.fractionLength(5))
+ return "\(coordinate.latitude.formatted(style)), \(coordinate.longitude.formatted(style))"
+ }
+
+ /// A length in metres, or `nil` for a negative (invalid) one unless
+ /// negatives are meaningful.
+ func metres(_ value: Double) -> String? {
+ metres(value, allowingNegative: false)
+ }
+
+ func metres(_ value: Double, allowingNegative: Bool) -> String? {
+ guard allowingNegative || value >= 0 else { return nil }
+ return measurement(Measurement(value: value, unit: UnitLength.meters), usage: .asProvided)
+ }
+
+ /// Metres per second, shown per hour. Negative speeds are invalid.
+ func speed(_ value: Double) -> String? {
+ guard value >= 0 else { return nil }
+ let perHour = Measurement(value: value, unit: UnitSpeed.metersPerSecond).converted(to: .kilometersPerHour)
+ return measurement(perHour, usage: .general)
+ }
+
+ func wind(_ value: Double) -> String {
+ measurement(Measurement(value: value, unit: UnitSpeed.kilometersPerHour), usage: .wind)
+ }
+
+ func temperature(_ value: Double) -> String {
+ measurement(Measurement(value: value, unit: UnitTemperature.celsius), usage: .weather)
+ }
+
+ func pressure(_ hectopascals: Double) -> String {
+ measurement(Measurement(value: hectopascals, unit: UnitPressure.hectopascals), usage: .barometric)
+ }
+
+ func visibility(_ kilometres: Double) -> String {
+ measurement(Measurement(value: kilometres, unit: UnitLength.kilometers), usage: .road)
+ }
+
+ func rainfall(_ millimetres: Double) -> String {
+ measurement(Measurement(value: millimetres, unit: UnitLength.millimeters), usage: .rainfall)
+ }
+
+ func percent(_ fraction: Double) -> String {
+ fraction.formatted(.percent.precision(.fractionLength(0)).locale(locale))
+ }
+
+ func decibels(_ value: Double) -> String {
+ "\(value.formatted(.number.precision(.fractionLength(0...1)).locale(locale))) dB"
+ }
+
+ /// Degrees clockwise from north, with the nearest of eight compass
+ /// points, such as 'NE (45°)'.
+ func bearing(_ degrees: Double) -> String {
+ let points = [
+ String(localized: "N", comment: "Compass point: north"),
+ String(localized: "NE", comment: "Compass point: north-east"),
+ String(localized: "E", comment: "Compass point: east"),
+ String(localized: "SE", comment: "Compass point: south-east"),
+ String(localized: "S", comment: "Compass point: south"),
+ String(localized: "SW", comment: "Compass point: south-west"),
+ String(localized: "W", comment: "Compass point: west"),
+ String(localized: "NW", comment: "Compass point: north-west"),
+ ]
+ let normalised = (degrees.truncatingRemainder(dividingBy: 360) + 360).truncatingRemainder(dividingBy: 360)
+ let point = points[Int((normalised / 45).rounded()) % 8]
+ return "\(point) (\(Int(normalised.rounded()))°)"
+ }
+
+ private func measurement<U: Dimension>(_ value: Measurement<U>, usage: MeasurementFormatUnitUsage<U>) -> String {
+ value.formatted(
+ .measurement(
+ width: .abbreviated, usage: usage,
+ numberFormatStyle: .number.precision(.fractionLength(0...1)).locale(locale)
+ ).locale(locale))
+ }
+}
diff --git a/Reportage/Views/ReportKind+Title.swift b/Reportage/Views/ReportKind+Title.swift
@@ -20,3 +20,16 @@ extension ReportKind {
}
}
}
+
+extension ReportTrigger {
+ /// Where a report came from, for the report's details.
+ var title: LocalizedStringResource {
+ switch self {
+ case .notification: "Prompt"
+ case .app: "In-App"
+ case .watch: "Apple Watch"
+ case .intent: "Shortcut"
+ case .imported: "Imported"
+ }
+ }
+}
diff --git a/Shared/Capture/ContextCapture.swift b/Shared/Capture/ContextCapture.swift
@@ -121,16 +121,38 @@ struct ContextCapture: Sendable {
}
}
- /// The fix's address in each of the user's first two languages.
+ /// The fix's address in the user's first language and, where the
+ /// place's own language differs, in that language too. Together they let
+ /// an address be shown in the local language when the user knows it,
+ /// and in their first language otherwise, as place names are.
private static func placemarks(for location: CLLocation) async -> [Placemark] {
- var placemarks: [Placemark] = []
- for language in preferredLanguages(limit: 2) {
- guard let request = MKReverseGeocodingRequest(location: location) else { break }
- request.preferredLocale = Locale(identifier: language)
- guard let item = try? await request.mapItems.first else { continue }
- placemarks.append(Placemark(item, language: language))
+ guard let first = preferredLanguages(limit: 1).first,
+ let placemark = await placemark(for: location, language: first)
+ else { return [] }
+ guard let local = placemark.countryCode.flatMap(localLanguage(ofRegion:)),
+ Locale.Language(identifier: local).languageCode != Locale.Language(identifier: first).languageCode,
+ let localPlacemark = await self.placemark(for: location, language: local)
+ else { return [placemark] }
+ return [placemark, localPlacemark]
+ }
+
+ private static func placemark(for location: CLLocation, language: String) async -> Placemark? {
+ guard let request = MKReverseGeocodingRequest(location: location) else { return nil }
+ request.preferredLocale = Locale(identifier: language)
+ guard let item = try? await request.mapItems.first else { return nil }
+ return Placemark(item, language: language)
+ }
+
+ /// The main language of a region, such as `ja` for `JP`. Chinese keeps
+ /// its script, which tells Traditional (`zh-Hant` in Taiwan and Hong
+ /// Kong) from Simplified.
+ static func localLanguage(ofRegion code: String) -> String? {
+ let likely = Locale.Language(identifier: Locale.Language(identifier: "und-\(code)").maximalIdentifier)
+ guard let language = likely.languageCode?.identifier, language != "und" else { return nil }
+ if language == "zh", let script = likely.script?.identifier {
+ return "zh-\(script)"
}
- return placemarks
+ return language
}
/// Distinct language codes from the user's preferred languages, in order.
diff --git a/Shared/Persistence/ReportStore.swift b/Shared/Persistence/ReportStore.swift
@@ -151,6 +151,17 @@ struct ReportStore: Sendable {
}
}
+ /// Deletes a report and its responses. The tokens its answers used are
+ /// kept: other reports may use them, and they're never deleted.
+ func delete(id: UUID) async throws {
+ let context = persistence.newBackgroundContext()
+ try await context.perform {
+ guard let entity = try Self.entity(id: id, in: context) else { return }
+ context.delete(entity)
+ try context.save()
+ }
+ }
+
private static func entity(id: UUID, in context: NSManagedObjectContext) throws -> ReportEntity? {
let request = ReportEntity.fetchRequest()
request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
diff --git a/Tests/Unit/ContextCaptureTests.swift b/Tests/Unit/ContextCaptureTests.swift
@@ -51,6 +51,16 @@ struct ContextCaptureTests {
#expect(Set(languages).count == languages.count)
}
+ @Test("A region's local language is its main one, with the script for Chinese")
+ func localLanguage() {
+ #expect(ContextCapture.localLanguage(ofRegion: "JP") == "ja")
+ #expect(ContextCapture.localLanguage(ofRegion: "AU") == "en")
+ #expect(ContextCapture.localLanguage(ofRegion: "VN") == "vi")
+ #expect(ContextCapture.localLanguage(ofRegion: "TW") == "zh-Hant")
+ #expect(ContextCapture.localLanguage(ofRegion: "HK") == "zh-Hant")
+ #expect(ContextCapture.localLanguage(ofRegion: "CN") == "zh-Hans")
+ }
+
@Test("A timeout gives up with nil, and a quick result comes through")
func timeout() async {
let slow = await withTimeout(.milliseconds(50)) { () async -> Int? in
diff --git a/Tests/Unit/ReportDetailsTests.swift b/Tests/Unit/ReportDetailsTests.swift
@@ -0,0 +1,138 @@
+import Foundation
+import Testing
+
+@testable import Reportage
+
+@MainActor
+@Suite("ReportDetails")
+struct ReportDetailsTests {
+
+ private static let locale = Locale(identifier: "en_AU")
+ private static let date = Date(timeIntervalSince1970: 1_792_200_000)
+
+ private static func report(
+ state: ReportState = .complete, context: Context = Context(), responses: [Response] = []
+ ) -> Report {
+ Report(
+ id: UUID(uuidString: "00000000-0000-4000-8000-000000000001")!,
+ date: date,
+ timeZone: "Asia/Tokyo",
+ kind: .random,
+ trigger: .notification,
+ state: state,
+ promptedAt: state == .complete ? date.addingTimeInterval(-125) : nil,
+ completedAt: state == .complete ? date.addingTimeInterval(60) : nil,
+ context: context,
+ responses: responses,
+ modifiedAt: date
+ )
+ }
+
+ private static func details(_ report: Report, lookup: SummaryLookup = SummaryLookup()) -> ReportDetails {
+ ReportDetails(report: report, lookup: lookup, locale: locale)
+ }
+
+ private static func value(_ label: String, in section: String, of details: ReportDetails) -> String? {
+ details.sections.first { $0.title == section }?.rows.first { $0.label == label }?.value
+ }
+
+ @Test("Answers keep their prompts and order, name tokens, and mark skipped questions")
+ func answers() {
+ var lookup = SummaryLookup()
+ lookup.tokenTexts = ["T1": "Reading", "T2": "Drinking coffee", "P1": "Library"]
+ let details = Self.details(
+ Self.report(responses: [
+ Response(questionID: "a", prompt: "Are you working?", value: .options([ResponseValue.noOption])),
+ Response(questionID: "b", prompt: "What are you doing?", value: .tokens(["T2", "T1"])),
+ Response(questionID: "c", prompt: "Where are you?", value: .place(PlaceAnswer(tokenID: "P1"))),
+ Response(questionID: "d", prompt: "Anything to add?", value: nil),
+ ]),
+ lookup: lookup)
+
+ #expect(details.answers.map(\.prompt) == [
+ "Are you working?", "What are you doing?", "Where are you?", "Anything to add?",
+ ])
+ #expect(details.answers.map(\.value) == [
+ .text("No"), .tokens(["Drinking coffee", "Reading"]), .text("Library"), .skipped,
+ ])
+ }
+
+ @Test("Times are shown in the report's own zone, with how long the prompt took")
+ func time() throws {
+ let details = Self.details(Self.report())
+ let reported = try #require(Self.value("Reported", in: "Time", of: details))
+ // 1_792_200_000 is 01:20 UTC, 10:20 in Tokyo.
+ #expect(reported.contains("10:20"))
+ #expect(Self.value("Time Zone", in: "Time", of: details)?.contains("Asia/Tokyo") == true)
+ #expect(Self.value("Source", in: "Time", of: details) == "Prompt")
+ let after = try #require(Self.value("Reported After", in: "Time", of: details))
+ #expect(after.hasPrefix("2 min") && after.contains("5 sec"))
+ #expect(Self.value("Answered", in: "Time", of: details) != nil)
+ }
+
+ @Test("An instant report says it hasn't been answered")
+ func instant() {
+ let details = Self.details(Self.report(state: .passive))
+ #expect(Self.value("Answered", in: "Time", of: details) == "Not yet")
+ #expect(Self.value("Prompted", in: "Time", of: details) == nil)
+ }
+
+ @Test("Sections with nothing recorded are left out")
+ func emptySections() {
+ let titles = Self.details(Self.report()).sections.map(\.title)
+ #expect(titles == ["Time", "Record"])
+ }
+
+ @Test("Every recorded context value appears, and invalid readings don't")
+ func context() {
+ var location = LocationContext(coordinate: Coordinate(latitude: 35.6812, longitude: 139.7671))
+ location.horizontalAccuracy = 12
+ location.altitude = 40
+ location.verticalAccuracy = -1
+ location.speed = -1
+ location.course = 90
+ location.placemark = Placemark(
+ locality: "Chiyoda", country: "Japan", language: "en", countryCode: "JP",
+ fullAddress: "1 Marunouchi, Chiyoda, Tokyo")
+ location.localisedPlacemarks = [
+ Placemark(language: "ja", countryCode: "JP", fullAddress: "東京都千代田区丸の内1丁目"),
+ // From a report made before local addresses: the user's second language.
+ Placemark(language: "fr", countryCode: "JP", fullAddress: "1 Marunouchi, Chiyoda, Tokyo, Japon"),
+ ]
+ var weather = WeatherContext(source: .darkSky)
+ weather.condition = "Cloudy"
+ weather.temperature = 18
+ weather.humidity = 0.65
+ weather.windSpeed = 10
+ weather.windDirection = 45
+ weather.backfilled = true
+ let context = Context(
+ location: location, weather: weather,
+ audio: AudioContext(source: .microphone, average: 42.5),
+ motion: MotionContext(steps: 1234),
+ device: DeviceContext(batteryLevel: 0.5, batteryState: .charging, connectivity: .wifi),
+ photos: PhotosContext(count: 2))
+ let details = Self.details(Self.report(context: context))
+
+ #expect(details.sections.map(\.title) == [
+ "Time", "Place", "Location", "Weather", "Device", "Motion", "Sound", "Photos", "Record",
+ ])
+ #expect(Self.value("Address", in: "Place", of: details) == "1 Marunouchi, Chiyoda, Tokyo")
+ #expect(Self.value("Endonymic Address", in: "Place", of: details) == "東京都千代田区丸の内1丁目")
+ #expect(Self.value("Address in French", in: "Place", of: details) == "1 Marunouchi, Chiyoda, Tokyo, Japon")
+ #expect(Self.value("Coordinates", in: "Location", of: details) == "35.68120, 139.76710")
+ #expect(Self.value("Accuracy", in: "Location", of: details) == "±12 m")
+ // An invalid vertical accuracy leaves the altitude without one.
+ #expect(Self.value("Altitude", in: "Location", of: details) == "40 m")
+ #expect(Self.value("Speed", in: "Location", of: details) == nil)
+ #expect(Self.value("Course", in: "Location", of: details) == "E (90°)")
+ #expect(Self.value("Humidity", in: "Weather", of: details) == "65%")
+ #expect(Self.value("Wind", in: "Weather", of: details)?.hasSuffix("from NE (45°)") == true)
+ #expect(Self.value("Source", in: "Weather", of: details) == "Dark Sky, filled in later")
+ #expect(Self.value("Battery", in: "Device", of: details) == "50%")
+ #expect(Self.value("Connection", in: "Device", of: details) == "Wi-Fi")
+ #expect(Self.value("Steps Today", in: "Motion", of: details) == "1,234")
+ #expect(Self.value("Average Level", in: "Sound", of: details) == "42.5 dB")
+ #expect(Self.value("Taken Since Last Report", in: "Photos", of: details) == "2")
+ }
+}
diff --git a/Tests/Unit/ReportStoreTests.swift b/Tests/Unit/ReportStoreTests.swift
@@ -179,6 +179,24 @@ struct ReportStoreTests {
#expect(try await store.vocabulary(for: ["L"])["L"]?.first?.locality == nil)
}
+ @Test("Deleting a report removes it and its responses, but keeps its tokens")
+ func delete() async throws {
+ let kept = Self.report(1, responses: [Response(questionID: "Q", prompt: "P", value: .tokens(["T1"]))])
+ let deleted = Self.report(2, responses: [Response(questionID: "Q", prompt: "P", value: .tokens(["T1"]))])
+ try await store.insert(kept, newTokens: [Self.token("T1", "Reading")])
+ try await store.insert(deleted)
+
+ try await store.delete(id: deleted.id)
+
+ #expect(try await store.report(id: deleted.id) == nil)
+ #expect(try await store.report(id: kept.id)?.responses == kept.responses)
+ let context = persistence.newBackgroundContext()
+ let counts = try await context.perform {
+ (try context.count(for: ResponseEntity.fetchRequest()), try context.count(for: TokenEntity.fetchRequest()))
+ }
+ #expect(counts == (1, 1))
+ }
+
@Test("A report logged for later appears at once, then gains its context")
func passiveLog() async throws {
var captured = Context()