commit f71c611e7c9bcae9ced80ea8bb8bee95c2ae77e7
parent 26cdc875bd2b3245e922f0e551e1fb8c4696e70f
Author: Michael Camilleri <[email protected]>
Date: Sat, 17 Oct 2026 05:35:17 +0900
Give user-defined places a region
Typing the name of an existing place always chose that place, regardless
of wher the user was located. So if a user entered 'Home' typed after a
move would stretch the old place over two addresses. Its single
coordinate would then sit between them, far enough from both that it
dropped out of the places listed nearby.
This commit treats a place as its name and a location. A place covers
500 metres around its coordinate, the same distance as places listed
nearby, so typing a name inside that region chooses the nearest place
with it, and typing it further away adds a new place with the same name.
A place without a coordinate, or a report without a location, still
matches by name alone. Reporter's saved places worked the same way: each
in the archive had a single coordinate, and over 99% of reports were
within 500 metres of the saved place they answered.
When places share a name, the place picker shows beneath each one the
locality of the last report that used it, worked out when the survey
loads. Entries still use the place's name alone. The locality rule
moves to Placemark so the timeline's context line uses the same one.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 11 | +++++++++++ |
| M | Reportage/Services/Places/PlaceRanking.swift | | | 7 | +++++++ |
| M | Reportage/Views/Home/ReportSummary.swift | | | 7 | +------ |
| M | Reportage/Views/Survey/PlacePicker.swift | | | 58 | +++++++++++++++++++++++++++++++++++++++++++++++----------- |
| M | Shared/Models/Context.swift | | | 9 | +++++++++ |
| M | Shared/Persistence/Vocabulary.swift | | | 43 | ++++++++++++++++++++++++++++++++++++++----- |
| M | Tests/Unit/PlacePickerTests.swift | | | 49 | +++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Tests/Unit/ReportStoreTests.swift | | | 25 | +++++++++++++++++++++++++ |
8 files changed, 187 insertions(+), 22 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -288,6 +288,17 @@ In the survey (`PlacePicker`): the app's language), coordinate and MapKit ID. Adding a typed name makes one at the report's location. Either is saved only if it's still the answer when the survey closes. +- **Regions.** A place is its name and a location: it covers 500 m around its + coordinate, the same as the near distance. Typing a place's name inside that + region chooses the place; typing it further away adds a new place with the + same name, so 'Home' after a move is a new place rather than one stretched + over two addresses. Reporter's saved places worked this way: each of the + archive's 14 had a single coordinate, and over 99% of reports were within + 500 m of the saved place they answered. A place without a coordinate has no + region, and is matched by name alone, as everything is without a location. +- **Telling places apart.** Places sharing a name show, beneath the name, the + locality of the last report that used them. This is shown only in the + picker: entries use the place's name alone. - **The map** shows the report's location, and pins the chosen place, centred on it and zoomed out far enough to keep the location in view. It makes way for the keyboard while searching.
diff --git a/Reportage/Services/Places/PlaceRanking.swift b/Reportage/Services/Places/PlaceRanking.swift
@@ -12,6 +12,13 @@ enum PlaceRanking {
/// offered: the user is probably at one of them. Places further away
/// are found by searching.
static let nearDistance: Double = 500
+ /// A place covers this distance around its coordinate, in metres. Typing
+ /// a place's name further away than this adds a new place with that
+ /// name, as Reporter's saved places each had one location. It matches
+ /// `nearDistance`, so a place listed as near is the one its name gives;
+ /// in the archive, over 99% of reports were within this distance of the
+ /// saved place they answered.
+ static let regionRadius: Double = nearDistance
/// A directory place this close to one of the user's places with the same
/// name, in metres, is taken to be that place.
static let matchDistance: Double = 200
diff --git a/Reportage/Views/Home/ReportSummary.swift b/Reportage/Views/Home/ReportSummary.swift
@@ -25,14 +25,9 @@ struct ReportSummary: Equatable {
}
/// Where and the weather, for example 'Suginami, Tokyo · 18° Cloudy'.
- /// Imported placemarks have no city with its region, so they show the
- /// most specific locality they have.
static func contextLine(_ context: Context) -> String? {
var parts: [String] = []
- if let placemark = context.location?.placemark,
- let locality = placemark.cityWithContext ?? placemark.subLocality ?? placemark.locality
- ?? placemark.name
- {
+ if let locality = context.location?.placemark?.displayLocality {
parts.append(locality)
}
if let weather = context.weather {
diff --git a/Reportage/Views/Survey/PlacePicker.swift b/Reportage/Views/Survey/PlacePicker.swift
@@ -135,7 +135,8 @@ final class PlacePicker {
}
/// Chooses the user's place that `query` names, or adds a new place by
- /// that name at the report's location, and clears the query.
+ /// that name at the report's location, and clears the query. A place
+ /// with that name elsewhere doesn't count: see `entry(named:)`.
func addQuery() {
let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty else { return }
@@ -257,13 +258,15 @@ final class PlacePicker {
text.isEmpty
? entries.filter(\.isSavedPlace)
: entries.filter { $0.text.localizedStandardContains(text) }
+ let sharedNames = Self.sharedNames(in: entries)
let own = PlaceRanking.rank(matching, from: origin).map { ranked in
PlaceCandidate(
id: ranked.entry.id,
source: .own,
name: ranked.entry.text,
coordinate: ranked.entry.coordinate,
- distance: ranked.distance
+ distance: ranked.distance,
+ detail: sharedNames.contains(Self.nameKey(ranked.entry.text)) ? ranked.entry.locality : nil
)
}
@@ -274,14 +277,16 @@ final class PlacePicker {
PlaceSection(kind: .yours, candidates: near),
PlaceSection(
kind: .nearby,
- candidates: directoryCandidates(directoryPlaces, excluding: near, from: origin)),
+ candidates: directoryCandidates(
+ directoryPlaces, excluding: near, from: origin, sharedNames: sharedNames)),
]
} else {
sections = [
PlaceSection(kind: .yours, candidates: own),
PlaceSection(
kind: text.isEmpty ? .nearby : .results,
- candidates: directoryCandidates(directoryPlaces, excluding: own, from: origin)),
+ candidates: directoryCandidates(
+ directoryPlaces, excluding: own, from: origin, sharedNames: sharedNames)),
]
}
sections.removeAll { $0.candidates.isEmpty }
@@ -300,16 +305,21 @@ final class PlacePicker {
private func directoryCandidates(
_ places: [DirectoryPlace],
excluding listed: [PlaceCandidate],
- from origin: Coordinate?
+ from origin: Coordinate?,
+ sharedNames: Set<String>
) -> [PlaceCandidate] {
var listed = Set(listed.map(\.id))
return places.compactMap { place in
- let candidate = candidate(for: place, from: origin)
+ let candidate = candidate(for: place, from: origin, sharedNames: sharedNames)
return listed.insert(candidate.id).inserted ? candidate : nil
}
}
- private func candidate(for place: DirectoryPlace, from origin: Coordinate?) -> PlaceCandidate {
+ private func candidate(
+ for place: DirectoryPlace,
+ from origin: Coordinate?,
+ sharedNames: Set<String>
+ ) -> PlaceCandidate {
let distance = origin.map { place.coordinate.distance(to: $0) }
if let entry = PlaceRanking.match(place, in: entries) {
return PlaceCandidate(
@@ -317,7 +327,8 @@ final class PlacePicker {
source: .own,
name: entry.text,
coordinate: place.coordinate,
- distance: distance
+ distance: distance,
+ detail: sharedNames.contains(Self.nameKey(entry.text)) ? entry.locality : nil
)
}
return PlaceCandidate(
@@ -330,11 +341,36 @@ final class PlacePicker {
)
}
+ /// The place that typing `text` names: one with that name whose region
+ /// the report is in, the nearest if there are several. A place with no
+ /// coordinate has no region, so its name alone decides, as it does when
+ /// the report has no location.
private func entry(named text: String) -> VocabularyEntry? {
- entries.first {
- $0.text.compare(text, options: [.caseInsensitive, .diacriticInsensitive])
- == .orderedSame
+ let named = entries.filter { Self.nameKey($0.text) == Self.nameKey(text) }
+ guard let origin = location?.coordinate else { return named.first }
+ let inRegion = named.compactMap { entry -> (entry: VocabularyEntry, distance: Double)? in
+ guard let coordinate = entry.coordinate else { return nil }
+ let distance = coordinate.distance(to: origin)
+ return distance <= PlaceRanking.regionRadius ? (entry, distance) : nil
}
+ return inRegion.min { $0.distance < $1.distance }?.entry
+ ?? named.first { $0.coordinate == nil }
+ }
+
+ /// A name as places are compared by: ignoring case and accents.
+ private static func nameKey(_ text: String) -> String {
+ text.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil)
+ }
+
+ /// Names more than one of `entries` have. Those places show their
+ /// locality, so they can be told apart.
+ private static func sharedNames(in entries: [VocabularyEntry]) -> Set<String> {
+ var seen: Set<String> = []
+ var shared: Set<String> = []
+ for entry in entries where !seen.insert(nameKey(entry.text)).inserted {
+ shared.insert(nameKey(entry.text))
+ }
+ return shared
}
private static let mapKitPrefix = "mapKit:"
diff --git a/Shared/Models/Context.swift b/Shared/Models/Context.swift
@@ -58,6 +58,15 @@ struct Placemark: Codable, Hashable, Sendable {
var shortAddress: String?
}
+extension Placemark {
+ /// Where this is, in a few words: the city with its region, or else the
+ /// most specific locality there is. Imported placemarks have no city
+ /// with its region.
+ var displayLocality: String? {
+ cityWithContext ?? subLocality ?? locality ?? name
+ }
+}
+
struct WeatherContext: Codable, Hashable, Sendable {
enum Source: String, Codable, Sendable {
case wunderground
diff --git a/Shared/Persistence/Vocabulary.swift b/Shared/Persistence/Vocabulary.swift
@@ -13,6 +13,9 @@ struct VocabularyEntry: Identifiable, Hashable, Sendable {
var coordinate: Coordinate?
/// For places picked from a directory.
var externalID: ExternalPlaceID?
+ /// For places: the locality of the most recent report that used it,
+ /// which tells apart places with the same name.
+ var locality: String?
}
/// The derived, local-only index that ranks suggestions from response
@@ -23,7 +26,8 @@ enum Vocabulary {
/// recently used. Archived tokens and tokens merged into others are left
/// out; uses of a merged token count towards the token it was merged into.
/// A place with no coordinate of its own is placed at the centre of where
- /// its answers were given.
+ /// its answers were given, and each place has the locality of the last
+ /// report that used it.
static func entries(
for questionIDs: [String],
in context: NSManagedObjectContext
@@ -50,11 +54,12 @@ enum Vocabulary {
var useCounts: [String: Int] = [:]
var lastUsed: [String: Date] = [:]
var answerCoordinates: [String: (latitude: Double, longitude: Double, count: Int)] = [:]
+ var lastReports: [String: NSManagedObjectID] = [:]
let responseRequest = NSFetchRequest<NSDictionary>(entityName: "ResponseEntity")
responseRequest.resultType = .dictionaryResultType
responseRequest.predicate = NSPredicate(
format: "questionID IN %@ AND value != nil", questionIDs)
- responseRequest.propertiesToFetch = ["value", "report.date"]
+ responseRequest.propertiesToFetch = ["value", "report", "report.date"]
for row in try context.fetch(responseRequest) {
guard let data = row["value"] as? Data else { continue }
let ids: [String]
@@ -62,9 +67,15 @@ enum Vocabulary {
case .tokens(let tokenIDs): ids = tokenIDs
case .place(let place):
ids = [place.tokenID]
+ let id = canonical(place.tokenID)
+ if let report = row["report"] as? NSManagedObjectID,
+ let date = row["report.date"] as? Date, date >= lastUsed[id] ?? .distantPast
+ {
+ lastReports[id] = report
+ }
if let coordinate = place.coordinate {
- let sum = answerCoordinates[canonical(place.tokenID)] ?? (0, 0, 0)
- answerCoordinates[canonical(place.tokenID)] = (
+ let sum = answerCoordinates[id] ?? (0, 0, 0)
+ answerCoordinates[id] = (
sum.latitude + coordinate.latitude,
sum.longitude + coordinate.longitude,
sum.count + 1
@@ -81,6 +92,8 @@ enum Vocabulary {
}
}
+ let localities = try self.localities(of: lastReports, in: context)
+
var entries: [String: [VocabularyEntry]] = [:]
for token in tokens where token.mergedInto == nil && token.archivedAt == nil {
let centre = answerCoordinates[token.id].map {
@@ -95,7 +108,8 @@ enum Vocabulary {
useCount: useCounts[token.id] ?? 0,
lastUsed: lastUsed[token.id],
coordinate: token.place?.coordinate ?? centre,
- externalID: token.place?.externalID
+ externalID: token.place?.externalID,
+ locality: localities[token.id]
))
}
for questionID in entries.keys {
@@ -104,6 +118,25 @@ enum Vocabulary {
return entries
}
+ /// The locality of each report in `reports`, by token ID.
+ private static func localities(
+ of reports: [String: NSManagedObjectID],
+ in context: NSManagedObjectContext
+ ) throws -> [String: String] {
+ guard !reports.isEmpty else { return [:] }
+ let request = ReportEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "self IN %@", Array(Set(reports.values)))
+ var byReport: [NSManagedObjectID: String] = [:]
+ for entity in try context.fetch(request) {
+ guard let data = entity.context,
+ let locality = try ModelCoding.decode(Context.self, from: data).location?.placemark?
+ .displayLocality
+ else { continue }
+ byReport[entity.objectID] = locality
+ }
+ return reports.compactMapValues { byReport[$0] }
+ }
+
static func ranksBefore(_ lhs: VocabularyEntry, _ rhs: VocabularyEntry) -> Bool {
if lhs.useCount != rhs.useCount { return lhs.useCount > rhs.useCount }
let lhsDate = lhs.lastUsed ?? .distantPast
diff --git a/Tests/Unit/PlacePickerTests.swift b/Tests/Unit/PlacePickerTests.swift
@@ -237,6 +237,55 @@ struct PlacePickerTests {
#expect(ids(picker)[.yours] == ["venue"])
}
+ @Test("Typing a place's name outside its region adds a new place with that name")
+ func regions() throws {
+ let entries = [
+ Self.entry("home", "Home", uses: 900, at: Self.north(5_000)),
+ Self.entry("work", "Work", uses: 100, at: Self.north(200)),
+ Self.entry("car", "Car", uses: 10, at: nil),
+ ]
+ let picker = makePicker(entries: entries)
+ picker.setLocation(LocationContext(coordinate: Self.here))
+
+ picker.query = "work"
+ #expect(!picker.canAddQuery)
+ picker.addQuery()
+ #expect(picker.selectedTokenID == "work")
+
+ // A place with no coordinate has no region.
+ picker.query = "Car"
+ #expect(!picker.canAddQuery)
+
+ picker.query = "Home"
+ #expect(picker.canAddQuery)
+ picker.addQuery()
+ let token = try #require(picker.usedNewTokens(now: Date()).first)
+ #expect(token.id != "home")
+ #expect(token.text == "Home")
+ #expect(token.place?.coordinate == Self.here)
+
+ // Without a location, the name alone decides.
+ let unplaced = makePicker(entries: entries)
+ unplaced.setLocation(nil)
+ unplaced.query = "home"
+ #expect(!unplaced.canAddQuery)
+ }
+
+ @Test("Places sharing a name show their locality")
+ func sharedNames() {
+ var home = Self.entry("home", "Home", uses: 900, at: Self.north(100))
+ home.locality = "Musashino"
+ var oldHome = Self.entry("old", "home", uses: 300, at: Self.north(9_000))
+ oldHome.locality = "Suginami"
+ var cafe = Self.entry("cafe", "Café", uses: 20, at: Self.north(60))
+ cafe.locality = "Musashino"
+ let picker = makePicker(entries: [home, oldHome, cafe])
+
+ #expect(picker.candidate(id: "home")?.detail == "Musashino")
+ #expect(picker.candidate(id: "old")?.detail == "Suginami")
+ #expect(picker.candidate(id: "cafe")?.detail == nil)
+ }
+
@Test("Clearing removes the choice and the search")
func clear() throws {
let picker = makePicker()
diff --git a/Tests/Unit/ReportStoreTests.swift b/Tests/Unit/ReportStoreTests.swift
@@ -154,6 +154,31 @@ struct ReportStoreTests {
#expect(byID["U"]?.externalID == nil)
}
+ @Test("A place has the locality of the last report that used it")
+ func placeLocality() async throws {
+ let home = Token(
+ id: "H", questionID: "L", text: "Home", place: PlaceDetails(),
+ modifiedAt: Date(timeIntervalSince1970: 0))
+ func report(_ number: Int, locality: String?) -> Report {
+ var report = Self.report(
+ number,
+ responses: [Response(questionID: "L", prompt: "P", value: .place(PlaceAnswer(tokenID: "H")))])
+ if let locality {
+ report.context.location = LocationContext(
+ coordinate: Coordinate(latitude: 0, longitude: 0),
+ placemark: Placemark(locality: locality))
+ }
+ return report
+ }
+ try await store.insert(report(1, locality: "Suginami"), newTokens: [home])
+ try await store.insert(report(3, locality: "Musashino"))
+ try await store.insert(report(2, locality: "Nakano"))
+ #expect(try await store.vocabulary(for: ["L"])["L"]?.first?.locality == "Musashino")
+
+ try await store.insert(report(4, locality: nil))
+ #expect(try await store.vocabulary(for: ["L"])["L"]?.first?.locality == nil)
+ }
+
@Test("A report and its new tokens are saved together")
func insert() async throws {
let token = Self.token("N", "New")