Reportage/Views/Survey/PlacePicker.swift (16359B)
1import Foundation
2import Observation
3
4
5
6struct PlaceCandidate: Identifiable, Hashable, Sendable {
7 enum Source: Hashable, Sendable {
8 case own
9 case directory
10 }
11
12
13
14 var id: String
15 var source: Source
16 var name: String
17 var coordinate: Coordinate?
18
19 var distance: Double?
20
21 var detail: String?
22}
23
24
25struct PlaceSection: Identifiable, Hashable, Sendable {
26 enum Kind: Hashable, Sendable {
27
28
29 case yours
30
31 case nearby
32
33 case results
34 }
35
36 var kind: Kind
37 var candidates: [PlaceCandidate]
38
39 var id: Kind { kind }
40}
41
42
43
44
45
46
47
48
49
50@MainActor
51@Observable
52final class PlacePicker {
53 enum LocationState: Hashable, Sendable {
54 case locating
55 case found(LocationContext)
56 case unavailable
57 }
58
59 let questionID: String
60
61 var query = "" {
62 didSet {
63 guard query != oldValue else { return }
64 update()
65 search()
66 }
67 }
68
69 private(set) var locationState: LocationState = .locating
70 private(set) var sections: [PlaceSection] = []
71
72 private(set) var canAddQuery = false
73 private(set) var selection: PlaceCandidate? {
74 didSet {
75 if selection?.id != oldValue?.id { onSelectionChange?() }
76 }
77 }
78
79 @ObservationIgnored var onSelectionChange: (() -> Void)?
80
81 private(set) var isSearching = false
82
83
84
85 var prefills = true
86
87 private var entries: [VocabularyEntry]
88 private var nearby: [DirectoryPlace] = []
89 private var results: [DirectoryPlace] = []
90
91 private var newTokens: [String: Token] = [:]
92
93
94 private var directoryTokenIDs: [String: String] = [:]
95
96 private let directory: any PlaceDirectory
97 private let searchDelay: Duration
98 private var nearbyTask: Task<Void, Never>?
99 private var searchTask: Task<Void, Never>?
100
101 init(
102 questionID: String,
103 entries: [VocabularyEntry],
104 directory: any PlaceDirectory,
105 searchDelay: Duration = .milliseconds(300)
106 ) {
107 self.questionID = questionID
108 self.entries = entries
109 self.directory = directory
110 self.searchDelay = searchDelay
111 update()
112 }
113
114 var location: LocationContext? {
115 if case .found(let location) = locationState { location } else { nil }
116 }
117
118
119 var selectedTokenID: String? {
120 guard let selection else { return nil }
121 switch selection.source {
122 case .own: return selection.id
123 case .directory: return directoryTokenIDs[Self.mapKitID(of: selection)]
124 }
125 }
126
127 func isSelected(_ candidate: PlaceCandidate) -> Bool { selection?.id == candidate.id }
128
129
130 func candidate(id: String) -> PlaceCandidate? {
131 sections.lazy.flatMap(\.candidates).first { $0.id == id }
132 }
133
134
135
136 func toggle(_ candidate: PlaceCandidate) {
137 if isSelected(candidate) {
138 selection = nil
139 return
140 }
141 if candidate.source == .directory {
142 adopt(candidate)
143 }
144 selection = candidate
145 }
146
147
148
149
150 func addQuery() {
151 let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
152 guard !text.isEmpty else { return }
153 let chosen: VocabularyEntry
154 if let existing = entry(named: text) {
155 chosen = existing
156 } else {
157 let coordinate = location?.coordinate
158 chosen = VocabularyEntry(id: UUID().uuidString, text: text, useCount: 0, coordinate: coordinate)
159 newTokens[chosen.id] = Token(
160 id: chosen.id,
161 questionID: questionID,
162 text: text,
163 place: PlaceDetails(coordinate: coordinate),
164 modifiedAt: Date()
165 )
166 entries.insert(chosen, at: 0)
167 }
168 query = ""
169 selection = candidate(id: chosen.id)
170 }
171
172 func clear() {
173 selection = nil
174 query = ""
175 }
176
177
178
179 func preselect(_ id: String, entry: VocabularyEntry?) {
180 if let entry, !entries.contains(where: { $0.id == entry.id }) {
181 entries.append(entry)
182 update()
183 }
184 let known = entries.first { $0.id == id }
185 selection =
186 candidate(id: id)
187 ?? PlaceCandidate(
188 id: id,
189 source: .own,
190 name: known?.text ?? "",
191 coordinate: known?.coordinate,
192 distance: location.flatMap { location in
193 known?.coordinate?.distance(to: location.coordinate)
194 }
195 )
196 }
197
198
199 func usedNewTokens(now: Date) -> [Token] {
200 guard let id = selectedTokenID, var token = newTokens[id] else { return [] }
201 token.modifiedAt = now
202 return [token]
203 }
204
205
206
207
208
209
210 private func adopt(_ candidate: PlaceCandidate) {
211 let mapKitID = Self.mapKitID(of: candidate)
212 guard directoryTokenIDs[mapKitID] == nil,
213 let place = (nearby + results).first(where: { $0.id == mapKitID })
214 else { return }
215 let id = UUID().uuidString
216 directoryTokenIDs[mapKitID] = id
217 let coordinate = location.map(\.coordinate).flatMap { here in
218 place.coordinate.distance(to: here) <= PlaceRanking.regionRadius ? here : nil
219 }
220 newTokens[id] = Token(
221 id: id,
222 questionID: questionID,
223 text: place.name,
224 place: PlaceDetails(
225 coordinate: coordinate,
226 names: place.language.map { [LocalisedName(language: $0, text: place.name)] } ?? [],
227 externalID: ExternalPlaceID(source: .mapKit, value: place.id)
228 ),
229 modifiedAt: Date()
230 )
231 }
232
233
234
235
236
237
238 func setLocation(_ location: LocationContext?) {
239 guard locationState == .locating else { return }
240 guard let location else {
241 locationState = .unavailable
242 return
243 }
244 locationState = .found(location)
245 update()
246 if prefills, selection == nil, query.isEmpty,
247 let entry = PlaceRanking.prefill(entries, at: location)
248 {
249 preselect(entry.id, entry: nil)
250 }
251 nearbyTask = Task {
252 let places = (try? await directory.places(near: location.coordinate)) ?? []
253 nearby = places.sorted {
254 $0.coordinate.distance(to: location.coordinate)
255 < $1.coordinate.distance(to: location.coordinate)
256 }
257 update()
258 }
259 if !query.isEmpty { search() }
260 }
261
262
263
264
265
266
267 private func search() {
268 searchTask?.cancel()
269 let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
270 guard !text.isEmpty else {
271 results = []
272 isSearching = false
273 update()
274 return
275 }
276 isSearching = true
277 let near = location?.coordinate
278 searchTask = Task {
279 try? await Task.sleep(for: searchDelay)
280 guard !Task.isCancelled else { return }
281 let found = try? await directory.search(text, near: near)
282 guard !Task.isCancelled else { return }
283 results = found ?? []
284 isSearching = false
285 update()
286 }
287 }
288
289
290 func settle() async {
291 await nearbyTask?.value
292 await searchTask?.value
293 }
294
295
296
297 private func update() {
298 let text = query.trimmingCharacters(in: .whitespacesAndNewlines)
299 let origin = location?.coordinate
300 let matching =
301 text.isEmpty
302 ? entries.filter(\.isSavedPlace)
303 : entries.filter { $0.matches(text) }
304 let sharedNames = Self.sharedNames(in: entries)
305 let own = PlaceRanking.rank(matching, from: origin).map { ranked in
306 PlaceCandidate(
307 id: ranked.entry.id,
308 source: .own,
309 name: ranked.entry.text,
310 coordinate: ranked.entry.coordinate,
311 distance: ranked.distance,
312 detail: sharedNames.contains(Self.nameKey(ranked.entry.text)) ? ranked.entry.locality : nil
313 )
314 }
315
316 let directoryPlaces = text.isEmpty ? nearby : results
317 if text.isEmpty, origin != nil {
318 let near = Array(own.prefix { ($0.distance ?? .infinity) <= PlaceRanking.nearDistance })
319 sections = [
320 PlaceSection(kind: .yours, candidates: near),
321 PlaceSection(
322 kind: .nearby,
323 candidates: directoryCandidates(
324 directoryPlaces, excluding: near, from: origin, sharedNames: sharedNames)),
325 ]
326 } else {
327 sections = [
328 PlaceSection(kind: .yours, candidates: own),
329 PlaceSection(
330 kind: text.isEmpty ? .nearby : .results,
331 candidates: directoryCandidates(
332 directoryPlaces, excluding: own, from: origin, sharedNames: sharedNames)),
333 ]
334 }
335 sections.removeAll { $0.candidates.isEmpty }
336 canAddQuery = !text.isEmpty && entry(named: text) == nil
337
338
339 if let selection {
340 self.selection = candidate(id: selection.id) ?? selection
341 }
342 }
343
344
345
346
347
348 private func directoryCandidates(
349 _ places: [DirectoryPlace],
350 excluding listed: [PlaceCandidate],
351 from origin: Coordinate?,
352 sharedNames: Set<String>
353 ) -> [PlaceCandidate] {
354 var listed = Set(listed.map(\.id))
355 return places.compactMap { place in
356 let candidate = candidate(for: place, from: origin, sharedNames: sharedNames)
357 return listed.insert(candidate.id).inserted ? candidate : nil
358 }
359 }
360
361 private func candidate(
362 for place: DirectoryPlace,
363 from origin: Coordinate?,
364 sharedNames: Set<String>
365 ) -> PlaceCandidate {
366 let distance = origin.map { place.coordinate.distance(to: $0) }
367 if let entry = PlaceRanking.match(place, in: entries) {
368 return PlaceCandidate(
369 id: entry.id,
370 source: .own,
371 name: entry.text,
372 coordinate: place.coordinate,
373 distance: distance,
374 detail: sharedNames.contains(Self.nameKey(entry.text)) ? entry.locality : nil
375 )
376 }
377 return PlaceCandidate(
378 id: Self.mapKitPrefix + place.id,
379 source: .directory,
380 name: place.name,
381 coordinate: place.coordinate,
382 distance: distance,
383 detail: place.detail
384 )
385 }
386
387
388
389
390
391
392 private func entry(named text: String) -> VocabularyEntry? {
393 let key = Self.nameKey(text)
394 var named = entries.filter { Self.nameKey($0.text) == key }
395 if named.isEmpty {
396 named = entries.filter { $0.merged.contains { Self.nameKey($0.text) == key } }
397 }
398 guard let origin = location?.coordinate else { return named.first }
399 let inRegion = named.compactMap { entry -> (entry: VocabularyEntry, distance: Double)? in
400 guard let coordinate = entry.coordinate else { return nil }
401 let distance = coordinate.distance(to: origin)
402 return distance <= PlaceRanking.regionRadius ? (entry, distance) : nil
403 }
404 return inRegion.min { $0.distance < $1.distance }?.entry
405 ?? named.first { $0.coordinate == nil }
406 }
407
408
409 private static func nameKey(_ text: String) -> String {
410 text.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil)
411 }
412
413
414
415 private static func sharedNames(in entries: [VocabularyEntry]) -> Set<String> {
416 var seen: Set<String> = []
417 var shared: Set<String> = []
418 for entry in entries where !seen.insert(nameKey(entry.text)).inserted {
419 shared.insert(nameKey(entry.text))
420 }
421 return shared
422 }
423
424 private static let mapKitPrefix = "mapKit:"
425
426 private static func mapKitID(of candidate: PlaceCandidate) -> String {
427 String(candidate.id.dropFirst(mapKitPrefix.count))
428 }
429}
430
431extension VocabularyEntry {
432
433
434
435
436
437 var isSavedPlace: Bool { externalID == nil || isRenamed || narrativeForm != nil }
438}