← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Views/Survey/PlacePicker.swift (16359B)

1import Foundation
2import Observation
3
4/// A place that can be chosen as an answer: one of the user's own places, or
5/// one from the directory.
6struct PlaceCandidate: Identifiable, Hashable, Sendable {
7    enum Source: Hashable, Sendable {
8        case own
9        case directory
10    }
11
12    /// The token ID for the user's own places; `mapKit:` and the MapKit ID
13    /// for directory places.
14    var id: String
15    var source: Source
16    var name: String
17    var coordinate: Coordinate?
18    /// Metres from the report's location, when both are known.
19    var distance: Double?
20    /// A short address, for directory places.
21    var detail: String?
22}
23
24/// A group of candidates, listed under a heading.
25struct PlaceSection: Identifiable, Hashable, Sendable {
26    enum Kind: Hashable, Sendable {
27        /// The user's places: those near the location, or all of them when
28        /// it isn't known, or those matching a search.
29        case yours
30        /// Directory places around the location.
31        case nearby
32        /// Directory places matching a search.
33        case results
34    }
35
36    var kind: Kind
37    var candidates: [PlaceCandidate]
38
39    var id: Kind { kind }
40}
41
42/// Searching, choosing and adding a place for one `location` question.
43///
44/// Candidates come in the order the design gives: the user's saved places
45/// near the report's location, ranked by distance, then nearby directory
46/// places. Places further away are found by searching, which looks through
47/// the user's places, including venues answered before, and the directory
48/// together. A directory place that's already one
49/// of the user's places is shown as theirs.
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    /// Whether `query` names none of the user's places, so it can be added.
72    private(set) var canAddQuery = false
73    private(set) var selection: PlaceCandidate? {
74        didSet {
75            if selection?.id != oldValue?.id { onSelectionChange?() }
76        }
77    }
78    /// Called when a different place is chosen, or none.
79    @ObservationIgnored var onSelectionChange: (() -> Void)?
80    /// Whether a directory search is under way.
81    private(set) var isSearching = false
82    /// Whether the place the report is at may be chosen when the location
83    /// arrives: see `PlaceRanking.prefill`. Off when editing a report,
84    /// Instant Reports included.
85    var prefills = true
86
87    private var entries: [VocabularyEntry]
88    private var nearby: [DirectoryPlace] = []
89    private var results: [DirectoryPlace] = []
90    /// Places added in this survey, by token ID.
91    private var newTokens: [String: Token] = [:]
92    /// Token IDs given to directory places chosen in this survey, by MapKit
93    /// ID, so choosing one again reuses its token.
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    /// The token ID of the chosen place.
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    /// The listed candidate with `id`, if any.
130    func candidate(id: String) -> PlaceCandidate? {
131        sections.lazy.flatMap(\.candidates).first { $0.id == id }
132    }
133
134    // MARK: Choosing
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    /// Chooses the user's place that `query` names, or adds a new place by
148    /// that name at the report's location, and clears the query. A place
149    /// with that name elsewhere doesn't count: see `entry(named:)`.
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    /// Chooses the place with token `id`, as an existing answer does, adding
178    /// `entry` if the suggestions leave it out.
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    /// The place added in this survey, if it's the one chosen.
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    /// Gives a directory place a token, the first time it's chosen. Its
206    /// coordinate is the report's own location, if the report is within the
207    /// place's region: that comes from the device rather than the directory.
208    /// A place chosen from further away has none, and is found again through
209    /// the directory by its ID.
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    // MARK: Location
234
235    /// Sets the report's location, once: later fixes and a missing one after
236    /// a fix are ignored, so the list doesn't reshuffle under the user's
237    /// finger. `nil` means there won't be one.
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    // MARK: Searching
263
264    /// Searches the directory for `query`, after a pause so a search isn't
265    /// made for every keystroke. Earlier results stay listed until the new
266    /// ones arrive.
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    /// Waits for directory requests under way. For tests.
290    func settle() async {
291        await nearbyTask?.value
292        await searchTask?.value
293    }
294
295    // MARK: Listing
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        // Keep the chosen place's details current, such as its distance once
338        // the location is known.
339        if let selection {
340            self.selection = candidate(id: selection.id) ?? selection
341        }
342    }
343
344    /// Candidates for directory places, leaving out those already listed.
345    /// A directory place that's already one of the user's places is shown
346    /// as theirs, at the directory's coordinate: it's more precise than the
347    /// centre of past answers.
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    /// The place that typing `text` names, or that a place with that name
388    /// was merged into: one with that name whose region
389    /// the report is in, the nearest if there are several. A place with no
390    /// coordinate has no region, so its name alone decides, as it does when
391    /// the report has no location.
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    /// A name as places are compared by: ignoring case and accents.
409    private static func nameKey(_ text: String) -> String {
410        text.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil)
411    }
412
413    /// Names more than one of `entries` have. Those places show their
414    /// locality, so they can be told apart.
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    /// Whether the place is one the user has made their own: saved by name,
433    /// or a venue from a directory they've renamed or given a narrative
434    /// form. Only these are listed without a search, so venues answered once
435    /// don't crowd the list: any other venue answered before comes back when
436    /// the directory lists it again, or when it's searched for.
437    var isSavedPlace: Bool { externalID == nil || isRenamed || narrativeForm != nil }
438}